Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
fix(python-sdk): URL-encode namespaced template IDs and aliases (#1691)
cursor[bot]e2eebd570fe0
diff --git a/.changeset/python-template-alias-encoding.md b/.changeset/python-template-alias-encoding.mdnew file mode 100644index 000000000..25db1a681--- /dev/null+++ b/.changeset/python-template-alias-encoding.md@@ -0,0 +1,28 @@+---+"@e2b/python-sdk": patch+---++Fix URL encoding of namespaced template names and aliases in the Python SDK.++The endpoints that take a template ID also accept a template name, and names may+be namespaced (e.g. `namespace/name`). The SDK interpolated them into the request+path without encoding, so a call like `Template.exists("namespace/name")` hit+`/templates/aliases/namespace/name` instead of+`/templates/aliases/namespace%2Fname` — the slash split the route rather than+staying inside one path segment. Every method that takes a template ID or name,+an alias, or a snapshot ID in the path — `Template.exists` / `alias_exists`,+`get_tags`, the build/upload/status calls, and `Sandbox.delete_snapshot` (whose+snapshot IDs are `namespace/name:tag`) — now percent-encodes the value, matching+the JavaScript SDK (which already encodes path parameters via+`encodeURIComponent`).++```python+from e2b import Template, Sandbox++# Namespaced templates now resolve correctly+Template.exists("my-team/my-template")+Template.get_tags("my-team/my-template")++# Namespaced snapshots can now be deleted+Sandbox.delete_snapshot("my-team/my-snapshot:default")+```diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.pyindex 7becc8ae0..2db0fa80c 100644--- a/packages/python-sdk/e2b/api/__init__.py+++ b/packages/python-sdk/e2b/api/__init__.py@@ -5,6 +5,7 @@ import refrom dataclasses import dataclassfrom types import TracebackTypefrom typing import NamedTuple, Optional, Protocol, Tuple, Union+from urllib.parse import quoteimport httpxfrom httpx import AsyncBaseTransport, BaseTransport, Timeout@@ -22,6 +23,18 @@ from e2b.exceptions import ()+def encode_path_param(value: str) -> str:+ """+ Percent-encode a template ID, name, or alias for use as one URL path segment.++ Endpoints that take a template ID also accept a name, which may be+ namespaced (``namespace/name``) and carry a ``:tag``. Escaping those+ separators keeps the value inside a single segment instead of splitting the+ route, matching the JS SDK's ``encodeURIComponent``.+ """+ return quote(value, safe="")++def make_logging_event_hooks(log: Optional[logging.Logger]) -> dict:"""Build synchronous httpx ``event_hooks`` that log requests and responsesto the given ``logging.Logger``. Requests log at ``INFO``, successfuldiff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex bebf68634..ce65ddc33 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -8,6 +8,7 @@ from typing_extensions import Unpackfrom e2b.api import (SandboxCreateResponse,api_exception_from_code,+ encode_path_param,handle_api_exception,)from e2b.api.client.api.sandboxes import (@@ -420,7 +421,7 @@ class SandboxApi(SandboxBase):api_client = get_api_client(config)res = await delete_templates_template_id.asyncio_detailed(- snapshot_id,+ encode_path_param(snapshot_id),client=api_client,)diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex e4a8cc0af..e30555ea0 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -8,6 +8,7 @@ from typing_extensions import Unpackfrom e2b.api import (SandboxCreateResponse,api_exception_from_code,+ encode_path_param,handle_api_exception,)from e2b.api.client.api.sandboxes import (@@ -547,7 +548,7 @@ class SandboxApi(SandboxBase):api_client = get_api_client(config)res = delete_templates_template_id.sync_detailed(- snapshot_id,+ encode_path_param(snapshot_id),client=api_client,)diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.pyindex 3d8c8f774..9a822cd51 100644--- a/packages/python-sdk/e2b/template_async/build_api.py+++ b/packages/python-sdk/e2b/template_async/build_api.py@@ -7,7 +7,7 @@ import httpxfrom pyqwest import HTTPTransportfrom pyqwest.httpx import AsyncPyqwestTransport-from e2b.api import handle_api_exception, proxy_to_config+from e2b.api import encode_path_param, handle_api_exception, proxy_to_configfrom e2b.io_utils import aiter_io_chunksfrom e2b.api.client.api.templates import (post_v3_templates,@@ -81,7 +81,7 @@ async def get_file_upload_link(stack_trace: Optional[TracebackType] = None,) -> TemplateBuildFileUpload:res = await get_templates_template_id_files_hash.asyncio_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id),hash_=files_hash,client=client,)@@ -186,7 +186,7 @@ async def trigger_build(template_data = TemplateBuildStartV2.from_dict(template)res = await post_v_2_templates_template_id_builds_build_id.asyncio_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id),build_id=build_id,client=client,body=template_data,@@ -227,7 +227,7 @@ async def get_build_status(client: AuthenticatedClient, template_id: str, build_id: str, logs_offset: int) -> TemplateBuildStatusResponse:res = await get_templates_template_id_builds_build_id_status.asyncio_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id),build_id=build_id,client=client,logs_offset=logs_offset,@@ -324,7 +324,7 @@ async def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool:True if the alias exists, False otherwise"""res = await get_templates_aliases_alias.asyncio_detailed(- alias=alias,+ alias=encode_path_param(alias),client=client,)@@ -403,17 +403,17 @@ async def remove_tags(client: AuthenticatedClient, name: str, tags: List[str]) -async def get_template_tags(- client: AuthenticatedClient, template_id: str+ client: AuthenticatedClient, template_id_or_name: str) -> List[TemplateTag]:"""Get all tags for a template.Args:client: Authenticated API client- template_id: Template ID or name+ template_id_or_name: Template ID or name (a name may be namespaced)"""res = await get_templates_template_id_tags.asyncio_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id_or_name),client=client,)diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.pyindex 0525fa457..2bc918ab2 100644--- a/packages/python-sdk/e2b/template_sync/build_api.py+++ b/packages/python-sdk/e2b/template_sync/build_api.py@@ -6,7 +6,7 @@ import httpxfrom pyqwest import SyncHTTPTransportfrom pyqwest.httpx import PyqwestTransport-from e2b.api import handle_api_exception, proxy_to_config+from e2b.api import encode_path_param, handle_api_exception, proxy_to_configfrom e2b.api.client.api.templates import (post_v3_templates,get_templates_template_id_files_hash,@@ -79,7 +79,7 @@ def get_file_upload_link(stack_trace: Optional[TracebackType] = None,) -> TemplateBuildFileUpload:res = get_templates_template_id_files_hash.sync_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id),hash_=files_hash,client=client,)@@ -178,7 +178,7 @@ def trigger_build(template_data = TemplateBuildStartV2.from_dict(template)res = post_v_2_templates_template_id_builds_build_id.sync_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id),build_id=build_id,client=client,body=template_data,@@ -219,7 +219,7 @@ def get_build_status(client: AuthenticatedClient, template_id: str, build_id: str, logs_offset: int) -> TemplateBuildStatusResponse:res = get_templates_template_id_builds_build_id_status.sync_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id),build_id=build_id,client=client,logs_offset=logs_offset,@@ -314,7 +314,7 @@ def check_alias_exists(client: AuthenticatedClient, alias: str) -> bool:True if the alias exists, False otherwise"""res = get_templates_aliases_alias.sync_detailed(- alias=alias,+ alias=encode_path_param(alias),client=client,)@@ -393,17 +393,17 @@ def remove_tags(client: AuthenticatedClient, name: str, tags: List[str]) -> Nonedef get_template_tags(- client: AuthenticatedClient, template_id: str+ client: AuthenticatedClient, template_id_or_name: str) -> List[TemplateTag]:"""Get all tags for a template.Args:client: Authenticated API client- template_id: Template ID or name+ template_id_or_name: Template ID or name (a name may be namespaced)"""res = get_templates_template_id_tags.sync_detailed(- template_id=template_id,+ template_id=encode_path_param(template_id_or_name),client=client,)diff --git a/packages/python-sdk/tests/shared/api/test_encode_path_param.py b/packages/python-sdk/tests/shared/api/test_encode_path_param.pynew file mode 100644index 000000000..228365ea7--- /dev/null+++ b/packages/python-sdk/tests/shared/api/test_encode_path_param.py@@ -0,0 +1,35 @@+from e2b.api import encode_path_param+++def test_leaves_simple_names_unchanged():+ assert encode_path_param("my-template") == "my-template"+++def test_encodes_slash_in_namespaced_id():+ # Namespaced template IDs / aliases must have their slash percent-encoded+ # so the whole value stays a single path segment.+ assert encode_path_param("namespace/name") == "namespace%2Fname"+++def test_encodes_every_slash_in_deeply_namespaced_id():+ assert encode_path_param("a/b/c") == "a%2Fb%2Fc"+++def test_keeps_unreserved_characters_unencoded():+ # RFC 3986 unreserved characters must not be encoded.+ assert encode_path_param("a-b_c.d~e") == "a-b_c.d~e"+++def test_encodes_other_reserved_characters():+ # Mirrors JS `encodeURIComponent`, which also encodes ":" and spaces.+ assert encode_path_param("name:tag") == "name%3Atag"+ assert encode_path_param("a b") == "a%20b"+++def test_encodes_namespaced_snapshot_id_with_tag():+ # Snapshot IDs are `namespace/name:tag`; both separators must be encoded so+ # DELETE /templates/{id} stays a single path segment.+ assert (+ encode_path_param("team-slug/my-snapshot:default")+ == "team-slug%2Fmy-snapshot%3Adefault"+ )diff --git a/packages/python-sdk/tests/shared/template/test_build_api_path_encoding.py b/packages/python-sdk/tests/shared/template/test_build_api_path_encoding.pynew file mode 100644index 000000000..2eb600c37--- /dev/null+++ b/packages/python-sdk/tests/shared/template/test_build_api_path_encoding.py@@ -0,0 +1,112 @@+import httpx++from e2b.api.client.client import AuthenticatedClient+from e2b.sandbox_async.sandbox_api import SandboxApi as AsyncSandboxApi+from e2b.sandbox_sync.sandbox_api import SandboxApi as SyncSandboxApi+from e2b.template_async import build_api as async_build_api+from e2b.template_sync import build_api as sync_build_api++NAMESPACED = "my-team/my-template"+NAMESPACED_SNAPSHOT = "team-slug/my-snapshot:default"+BASE_URL = "https://api.e2b.dev"+++def _handler(request: httpx.Request) -> httpx.Response:+ if request.method == "DELETE":+ return httpx.Response(200, json={})+ if request.url.path.endswith("/tags"):+ return httpx.Response(200, json=[])+ return httpx.Response(404, json={"code": 404, "message": "not found"})+++def _recording_client() -> tuple[AuthenticatedClient, list[httpx.Request]]:+ """Client whose requests are answered locally and recorded for assertions."""+ requests: list[httpx.Request] = []++ def record(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return _handler(request)++ transport = httpx.MockTransport(record)+ client = AuthenticatedClient(base_url=BASE_URL, token="e2b_test")+ client.set_httpx_client(httpx.Client(base_url=BASE_URL, transport=transport))+ client.set_async_httpx_client(+ httpx.AsyncClient(base_url=BASE_URL, transport=transport)+ )+ return client, requests+++def test_sync_alias_check_sends_encoded_alias():+ client, requests = _recording_client()++ assert sync_build_api.check_alias_exists(client, NAMESPACED) is False++ # raw_path is what goes on the wire: the slash stays encoded, so the whole+ # alias remains a single path segment instead of splitting the route.+ assert requests[0].url.raw_path == b"/templates/aliases/my-team%2Fmy-template"+++def test_sync_alias_check_leaves_plain_alias_untouched():+ client, requests = _recording_client()++ assert sync_build_api.check_alias_exists(client, "my-template") is False++ assert requests[0].url.raw_path == b"/templates/aliases/my-template"+++def test_sync_get_template_tags_sends_encoded_template_id():+ client, requests = _recording_client()++ assert sync_build_api.get_template_tags(client, NAMESPACED) == []++ assert requests[0].url.raw_path == b"/templates/my-team%2Fmy-template/tags"+++async def test_async_alias_check_sends_encoded_alias():+ client, requests = _recording_client()++ assert await async_build_api.check_alias_exists(client, NAMESPACED) is False++ assert requests[0].url.raw_path == b"/templates/aliases/my-team%2Fmy-template"+++async def test_async_alias_check_leaves_plain_alias_untouched():+ client, requests = _recording_client()++ assert await async_build_api.check_alias_exists(client, "my-template") is False++ assert requests[0].url.raw_path == b"/templates/aliases/my-template"+++async def test_async_get_template_tags_sends_encoded_template_id():+ client, requests = _recording_client()++ assert await async_build_api.get_template_tags(client, NAMESPACED) == []++ assert requests[0].url.raw_path == b"/templates/my-team%2Fmy-template/tags"+++def test_sync_delete_snapshot_sends_encoded_snapshot_id(monkeypatch):+ client, requests = _recording_client()+ monkeypatch.setattr(+ "e2b.sandbox_sync.sandbox_api.get_api_client", lambda config: client+ )++ assert SyncSandboxApi._cls_delete_snapshot(NAMESPACED_SNAPSHOT, api_key="e2b_test")++ # Snapshot IDs carry both a namespace slash and a `:tag`; both must stay+ # encoded so DELETE /templates/{id} targets one path segment.+ assert requests[0].url.raw_path == b"/templates/team-slug%2Fmy-snapshot%3Adefault"+++async def test_async_delete_snapshot_sends_encoded_snapshot_id(monkeypatch):+ client, requests = _recording_client()+ monkeypatch.setattr(+ "e2b.sandbox_async.sandbox_api.get_api_client", lambda config: client+ )++ assert await AsyncSandboxApi._cls_delete_snapshot(+ NAMESPACED_SNAPSHOT, api_key="e2b_test"+ )++ assert requests[0].url.raw_path == b"/templates/team-slug%2Fmy-snapshot%3Adefault"