diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4557576..55f5be4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,12 +1,14 @@ name: CI on: push: - branches-ignore: - - 'generated' - - 'codegen/**' - - 'integrated/**' - - 'stl-preview-head/**' - - 'stl-preview-base/**' + branches: + - '**' + - '!integrated/**' + - '!stl-preview-head/**' + - '!stl-preview-base/**' + - '!generated' + - '!codegen/**' + - 'codegen/stl/**' pull_request: branches-ignore: - 'stl-preview-head/**' @@ -55,14 +57,18 @@ jobs: run: uv build - name: Get GitHub OIDC Token - if: github.repository == 'stainless-sdks/dedalus-sdk-python' + if: |- + github.repository == 'stainless-sdks/dedalus-sdk-python' && + !startsWith(github.ref, 'refs/heads/stl/') id: github-oidc uses: actions/github-script@v8 with: script: core.setOutput('github_token', await core.getIDToken()); - name: Upload tarball - if: github.repository == 'stainless-sdks/dedalus-sdk-python' + if: |- + github.repository == 'stainless-sdks/dedalus-sdk-python' && + !startsWith(github.ref, 'refs/heads/stl/') env: URL: https://pkg.stainless.com/s AUTH: ${{ steps.github-oidc.outputs.github_token }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6b7b74c..cce9240 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.3.0" + ".": "0.3.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 06bcc8b..3ce7384 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 0.3.1 (2026-03-19) + +Full Changelog: [v0.3.0...v0.3.1](https://github.com/dedalus-labs/dedalus-sdk-python/compare/v0.3.0...v0.3.1) + +### Bug Fixes + +* **deps:** bump minimum typing-extensions version ([23ea212](https://github.com/dedalus-labs/dedalus-sdk-python/commit/23ea21291b2cf443c594661acfc6e19e95077162)) +* **pydantic:** do not pass `by_alias` unless set ([b098b05](https://github.com/dedalus-labs/dedalus-sdk-python/commit/b098b05e30ec6487a6467bd928ce3c725d3f2aa0)) +* sanitize endpoint path params ([e385e21](https://github.com/dedalus-labs/dedalus-sdk-python/commit/e385e215a38c3141ff675a58799511a306d2c879)) + + +### Chores + +* **ci:** skip uploading artifacts on stainless-internal branches ([e3ed836](https://github.com/dedalus-labs/dedalus-sdk-python/commit/e3ed83614aa445a6af6d48fbab67edd96d651123)) +* **internal:** tweak CI branches ([1fc1ee4](https://github.com/dedalus-labs/dedalus-sdk-python/commit/1fc1ee460877941fb648448a415b37f868093058)) +* update placeholder string ([3a623d4](https://github.com/dedalus-labs/dedalus-sdk-python/commit/3a623d4779430378efe9ceb6540ba6fddbc70041)) + + +### Refactors + +* **types:** use `extra_items` from PEP 728 ([de6e4e4](https://github.com/dedalus-labs/dedalus-sdk-python/commit/de6e4e466ad9e9f40be8d8d4f7ea6208c076267e)) + ## 0.3.0 (2026-02-28) Full Changelog: [v0.2.0...v0.3.0](https://github.com/dedalus-labs/dedalus-sdk-python/compare/v0.2.0...v0.3.0) diff --git a/pyproject.toml b/pyproject.toml index c409c14..1416f51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "dedalus_labs" -version = "0.3.0" +version = "0.3.1" description = "The official Python library for the Dedalus API" dynamic = ["readme"] license = "MIT" @@ -11,7 +11,7 @@ authors = [ dependencies = [ "httpx>=0.23.0, <1", "pydantic>=1.9.0, <3", - "typing-extensions>=4.10, <5", + "typing-extensions>=4.14, <5", "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", diff --git a/src/dedalus_labs/_compat.py b/src/dedalus_labs/_compat.py index 76d017b..6d465dc 100644 --- a/src/dedalus_labs/_compat.py +++ b/src/dedalus_labs/_compat.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload from datetime import date, datetime -from typing_extensions import Self, Literal +from typing_extensions import Self, Literal, TypedDict import pydantic from pydantic.fields import FieldInfo @@ -131,6 +131,10 @@ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: return model.model_dump_json(indent=indent) +class _ModelDumpKwargs(TypedDict, total=False): + by_alias: bool + + def model_dump( model: pydantic.BaseModel, *, @@ -142,6 +146,9 @@ def model_dump( by_alias: bool | None = None, ) -> dict[str, Any]: if (not PYDANTIC_V1) or hasattr(model, "model_dump"): + kwargs: _ModelDumpKwargs = {} + if by_alias is not None: + kwargs["by_alias"] = by_alias return model.model_dump( mode=mode, exclude=exclude, @@ -149,7 +156,7 @@ def model_dump( exclude_defaults=exclude_defaults, # warnings are not supported in Pydantic v1 warnings=True if PYDANTIC_V1 else warnings, - by_alias=by_alias, + **kwargs, ) return cast( "dict[str, Any]", diff --git a/src/dedalus_labs/_utils/__init__.py b/src/dedalus_labs/_utils/__init__.py index dc64e29..10cb66d 100644 --- a/src/dedalus_labs/_utils/__init__.py +++ b/src/dedalus_labs/_utils/__init__.py @@ -1,3 +1,4 @@ +from ._path import path_template as path_template from ._sync import asyncify as asyncify from ._proxy import LazyProxy as LazyProxy from ._utils import ( diff --git a/src/dedalus_labs/_utils/_path.py b/src/dedalus_labs/_utils/_path.py new file mode 100644 index 0000000..4d6e1e4 --- /dev/null +++ b/src/dedalus_labs/_utils/_path.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import re +from typing import ( + Any, + Mapping, + Callable, +) +from urllib.parse import quote + +# Matches '.' or '..' where each dot is either literal or percent-encoded (%2e / %2E). +_DOT_SEGMENT_RE = re.compile(r"^(?:\.|%2[eE]){1,2}$") + +_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}") + + +def _quote_path_segment_part(value: str) -> str: + """Percent-encode `value` for use in a URI path segment. + + Considers characters not in `pchar` set from RFC 3986 §3.3 to be unsafe. + https://datatracker.ietf.org/doc/html/rfc3986#section-3.3 + """ + # quote() already treats unreserved characters (letters, digits, and -._~) + # as safe, so we only need to add sub-delims, ':', and '@'. + # Notably, unlike the default `safe` for quote(), / is unsafe and must be quoted. + return quote(value, safe="!$&'()*+,;=:@") + + +def _quote_query_part(value: str) -> str: + """Percent-encode `value` for use in a URI query string. + + Considers &, = and characters not in `query` set from RFC 3986 §3.4 to be unsafe. + https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 + """ + return quote(value, safe="!$'()*+,;:@/?") + + +def _quote_fragment_part(value: str) -> str: + """Percent-encode `value` for use in a URI fragment. + + Considers characters not in `fragment` set from RFC 3986 §3.5 to be unsafe. + https://datatracker.ietf.org/doc/html/rfc3986#section-3.5 + """ + return quote(value, safe="!$&'()*+,;=:@/?") + + +def _interpolate( + template: str, + values: Mapping[str, Any], + quoter: Callable[[str], str], +) -> str: + """Replace {name} placeholders in `template`, quoting each value with `quoter`. + + Placeholder names are looked up in `values`. + + Raises: + KeyError: If a placeholder is not found in `values`. + """ + # re.split with a capturing group returns alternating + # [text, name, text, name, ..., text] elements. + parts = _PLACEHOLDER_RE.split(template) + + for i in range(1, len(parts), 2): + name = parts[i] + if name not in values: + raise KeyError(f"a value for placeholder {{{name}}} was not provided") + val = values[name] + if val is None: + parts[i] = "null" + elif isinstance(val, bool): + parts[i] = "true" if val else "false" + else: + parts[i] = quoter(str(values[name])) + + return "".join(parts) + + +def path_template(template: str, /, **kwargs: Any) -> str: + """Interpolate {name} placeholders in `template` from keyword arguments. + + Args: + template: The template string containing {name} placeholders. + **kwargs: Keyword arguments to interpolate into the template. + + Returns: + The template with placeholders interpolated and percent-encoded. + + Safe characters for percent-encoding are dependent on the URI component. + Placeholders in path and fragment portions are percent-encoded where the `segment` + and `fragment` sets from RFC 3986 respectively are considered safe. + Placeholders in the query portion are percent-encoded where the `query` set from + RFC 3986 §3.3 is considered safe except for = and & characters. + + Raises: + KeyError: If a placeholder is not found in `kwargs`. + ValueError: If resulting path contains /./ or /../ segments (including percent-encoded dot-segments). + """ + # Split the template into path, query, and fragment portions. + fragment_template: str | None = None + query_template: str | None = None + + rest = template + if "#" in rest: + rest, fragment_template = rest.split("#", 1) + if "?" in rest: + rest, query_template = rest.split("?", 1) + path_template = rest + + # Interpolate each portion with the appropriate quoting rules. + path_result = _interpolate(path_template, kwargs, _quote_path_segment_part) + + # Reject dot-segments (. and ..) in the final assembled path. The check + # runs after interpolation so that adjacent placeholders or a mix of static + # text and placeholders that together form a dot-segment are caught. + # Also reject percent-encoded dot-segments to protect against incorrectly + # implemented normalization in servers/proxies. + for segment in path_result.split("/"): + if _DOT_SEGMENT_RE.match(segment): + raise ValueError(f"Constructed path {path_result!r} contains dot-segment {segment!r} which is not allowed") + + result = path_result + if query_template is not None: + result += "?" + _interpolate(query_template, kwargs, _quote_query_part) + if fragment_template is not None: + result += "#" + _interpolate(fragment_template, kwargs, _quote_fragment_part) + + return result diff --git a/src/dedalus_labs/_version.py b/src/dedalus_labs/_version.py index 9329938..87c8f21 100644 --- a/src/dedalus_labs/_version.py +++ b/src/dedalus_labs/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "dedalus_labs" -__version__ = "0.3.0" # x-release-please-version +__version__ = "0.3.1" # x-release-please-version diff --git a/src/dedalus_labs/resources/models.py b/src/dedalus_labs/resources/models.py index c56a5e7..a47aff8 100644 --- a/src/dedalus_labs/resources/models.py +++ b/src/dedalus_labs/resources/models.py @@ -5,6 +5,7 @@ import httpx from .._types import Body, Query, Headers, NotGiven, not_given +from .._utils import path_template from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import ( @@ -99,7 +100,7 @@ def retrieve( if not model_id: raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}") return self._get( - f"/v1/models/{model_id}", + path_template("/v1/models/{model_id}", model_id=model_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -213,7 +214,7 @@ async def retrieve( if not model_id: raise ValueError(f"Expected a non-empty value for `model_id` but received {model_id!r}") return await self._get( - f"/v1/models/{model_id}", + path_template("/v1/models/{model_id}", model_id=model_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/dedalus_labs/types/shared_params/reasoning.py b/src/dedalus_labs/types/shared_params/reasoning.py index ea0bb7c..dfe11f2 100644 --- a/src/dedalus_labs/types/shared_params/reasoning.py +++ b/src/dedalus_labs/types/shared_params/reasoning.py @@ -2,13 +2,13 @@ from __future__ import annotations -from typing import Dict, Union, Optional -from typing_extensions import Literal, TypeAlias, TypedDict +from typing import Optional +from typing_extensions import Literal, TypedDict __all__ = ["Reasoning"] -class ReasoningTyped(TypedDict, total=False): +class Reasoning(TypedDict, total=False, extra_items=object): # type: ignore[call-arg] """**gpt-5 and o-series models only** Configuration options for @@ -20,6 +20,3 @@ class ReasoningTyped(TypedDict, total=False): generate_summary: Optional[Literal["auto", "concise", "detailed"]] summary: Optional[Literal["auto", "concise", "detailed"]] - - -Reasoning: TypeAlias = Union[ReasoningTyped, Dict[str, object]] diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index d15a157..ccb9930 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -21,7 +21,7 @@ class TestTranscriptions: @parametrize def test_method_create(self, client: Dedalus) -> None: transcription = client.audio.transcriptions.create( - file=b"raw file contents", + file=b"Example data", model="model", ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @@ -30,7 +30,7 @@ def test_method_create(self, client: Dedalus) -> None: @parametrize def test_method_create_with_all_params(self, client: Dedalus) -> None: transcription = client.audio.transcriptions.create( - file=b"raw file contents", + file=b"Example data", model="model", language="language", prompt="prompt", @@ -43,7 +43,7 @@ def test_method_create_with_all_params(self, client: Dedalus) -> None: @parametrize def test_raw_response_create(self, client: Dedalus) -> None: response = client.audio.transcriptions.with_raw_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) @@ -56,7 +56,7 @@ def test_raw_response_create(self, client: Dedalus) -> None: @parametrize def test_streaming_response_create(self, client: Dedalus) -> None: with client.audio.transcriptions.with_streaming_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) as response: assert not response.is_closed @@ -77,7 +77,7 @@ class TestAsyncTranscriptions: @parametrize async def test_method_create(self, async_client: AsyncDedalus) -> None: transcription = await async_client.audio.transcriptions.create( - file=b"raw file contents", + file=b"Example data", model="model", ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @@ -86,7 +86,7 @@ async def test_method_create(self, async_client: AsyncDedalus) -> None: @parametrize async def test_method_create_with_all_params(self, async_client: AsyncDedalus) -> None: transcription = await async_client.audio.transcriptions.create( - file=b"raw file contents", + file=b"Example data", model="model", language="language", prompt="prompt", @@ -99,7 +99,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncDedalus) - @parametrize async def test_raw_response_create(self, async_client: AsyncDedalus) -> None: response = await async_client.audio.transcriptions.with_raw_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) @@ -112,7 +112,7 @@ async def test_raw_response_create(self, async_client: AsyncDedalus) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncDedalus) -> None: async with async_client.audio.transcriptions.with_streaming_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) as response: assert not response.is_closed diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index b005e5c..a3dce3d 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -21,7 +21,7 @@ class TestTranslations: @parametrize def test_method_create(self, client: Dedalus) -> None: translation = client.audio.translations.create( - file=b"raw file contents", + file=b"Example data", model="model", ) assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @@ -30,7 +30,7 @@ def test_method_create(self, client: Dedalus) -> None: @parametrize def test_method_create_with_all_params(self, client: Dedalus) -> None: translation = client.audio.translations.create( - file=b"raw file contents", + file=b"Example data", model="model", prompt="prompt", response_format="response_format", @@ -42,7 +42,7 @@ def test_method_create_with_all_params(self, client: Dedalus) -> None: @parametrize def test_raw_response_create(self, client: Dedalus) -> None: response = client.audio.translations.with_raw_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) @@ -55,7 +55,7 @@ def test_raw_response_create(self, client: Dedalus) -> None: @parametrize def test_streaming_response_create(self, client: Dedalus) -> None: with client.audio.translations.with_streaming_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) as response: assert not response.is_closed @@ -76,7 +76,7 @@ class TestAsyncTranslations: @parametrize async def test_method_create(self, async_client: AsyncDedalus) -> None: translation = await async_client.audio.translations.create( - file=b"raw file contents", + file=b"Example data", model="model", ) assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @@ -85,7 +85,7 @@ async def test_method_create(self, async_client: AsyncDedalus) -> None: @parametrize async def test_method_create_with_all_params(self, async_client: AsyncDedalus) -> None: translation = await async_client.audio.translations.create( - file=b"raw file contents", + file=b"Example data", model="model", prompt="prompt", response_format="response_format", @@ -97,7 +97,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncDedalus) - @parametrize async def test_raw_response_create(self, async_client: AsyncDedalus) -> None: response = await async_client.audio.translations.with_raw_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) @@ -110,7 +110,7 @@ async def test_raw_response_create(self, async_client: AsyncDedalus) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncDedalus) -> None: async with async_client.audio.translations.with_streaming_response.create( - file=b"raw file contents", + file=b"Example data", model="model", ) as response: assert not response.is_closed diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index b797e15..35b7f9c 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -21,7 +21,7 @@ class TestImages: @parametrize def test_method_create_variation(self, client: Dedalus) -> None: image = client.images.create_variation( - image=b"raw file contents", + image=b"Example data", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -29,7 +29,7 @@ def test_method_create_variation(self, client: Dedalus) -> None: @parametrize def test_method_create_variation_with_all_params(self, client: Dedalus) -> None: image = client.images.create_variation( - image=b"raw file contents", + image=b"Example data", model="model", n=0, response_format="response_format", @@ -42,7 +42,7 @@ def test_method_create_variation_with_all_params(self, client: Dedalus) -> None: @parametrize def test_raw_response_create_variation(self, client: Dedalus) -> None: response = client.images.with_raw_response.create_variation( - image=b"raw file contents", + image=b"Example data", ) assert response.is_closed is True @@ -54,7 +54,7 @@ def test_raw_response_create_variation(self, client: Dedalus) -> None: @parametrize def test_streaming_response_create_variation(self, client: Dedalus) -> None: with client.images.with_streaming_response.create_variation( - image=b"raw file contents", + image=b"Example data", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -68,7 +68,7 @@ def test_streaming_response_create_variation(self, client: Dedalus) -> None: @parametrize def test_method_edit(self, client: Dedalus) -> None: image = client.images.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -77,9 +77,9 @@ def test_method_edit(self, client: Dedalus) -> None: @parametrize def test_method_edit_with_all_params(self, client: Dedalus) -> None: image = client.images.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", - mask=b"raw file contents", + mask=b"Example data", model="model", n=0, response_format="response_format", @@ -92,7 +92,7 @@ def test_method_edit_with_all_params(self, client: Dedalus) -> None: @parametrize def test_raw_response_edit(self, client: Dedalus) -> None: response = client.images.with_raw_response.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", ) @@ -105,7 +105,7 @@ def test_raw_response_edit(self, client: Dedalus) -> None: @parametrize def test_streaming_response_edit(self, client: Dedalus) -> None: with client.images.with_streaming_response.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", ) as response: assert not response.is_closed @@ -181,7 +181,7 @@ class TestAsyncImages: @parametrize async def test_method_create_variation(self, async_client: AsyncDedalus) -> None: image = await async_client.images.create_variation( - image=b"raw file contents", + image=b"Example data", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -189,7 +189,7 @@ async def test_method_create_variation(self, async_client: AsyncDedalus) -> None @parametrize async def test_method_create_variation_with_all_params(self, async_client: AsyncDedalus) -> None: image = await async_client.images.create_variation( - image=b"raw file contents", + image=b"Example data", model="model", n=0, response_format="response_format", @@ -202,7 +202,7 @@ async def test_method_create_variation_with_all_params(self, async_client: Async @parametrize async def test_raw_response_create_variation(self, async_client: AsyncDedalus) -> None: response = await async_client.images.with_raw_response.create_variation( - image=b"raw file contents", + image=b"Example data", ) assert response.is_closed is True @@ -214,7 +214,7 @@ async def test_raw_response_create_variation(self, async_client: AsyncDedalus) - @parametrize async def test_streaming_response_create_variation(self, async_client: AsyncDedalus) -> None: async with async_client.images.with_streaming_response.create_variation( - image=b"raw file contents", + image=b"Example data", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -228,7 +228,7 @@ async def test_streaming_response_create_variation(self, async_client: AsyncDeda @parametrize async def test_method_edit(self, async_client: AsyncDedalus) -> None: image = await async_client.images.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -237,9 +237,9 @@ async def test_method_edit(self, async_client: AsyncDedalus) -> None: @parametrize async def test_method_edit_with_all_params(self, async_client: AsyncDedalus) -> None: image = await async_client.images.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", - mask=b"raw file contents", + mask=b"Example data", model="model", n=0, response_format="response_format", @@ -252,7 +252,7 @@ async def test_method_edit_with_all_params(self, async_client: AsyncDedalus) -> @parametrize async def test_raw_response_edit(self, async_client: AsyncDedalus) -> None: response = await async_client.images.with_raw_response.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", ) @@ -265,7 +265,7 @@ async def test_raw_response_edit(self, async_client: AsyncDedalus) -> None: @parametrize async def test_streaming_response_edit(self, async_client: AsyncDedalus) -> None: async with async_client.images.with_streaming_response.edit( - image=b"raw file contents", + image=b"Example data", prompt="prompt", ) as response: assert not response.is_closed diff --git a/tests/test_utils/test_path.py b/tests/test_utils/test_path.py new file mode 100644 index 0000000..c8eb92a --- /dev/null +++ b/tests/test_utils/test_path.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from typing import Any + +import pytest + +from dedalus_labs._utils._path import path_template + + +@pytest.mark.parametrize( + "template, kwargs, expected", + [ + ("/v1/{id}", dict(id="abc"), "/v1/abc"), + ("/v1/{a}/{b}", dict(a="x", b="y"), "/v1/x/y"), + ("/v1/{a}{b}/path/{c}?val={d}#{e}", dict(a="x", b="y", c="z", d="u", e="v"), "/v1/xy/path/z?val=u#v"), + ("/{w}/{w}", dict(w="echo"), "/echo/echo"), + ("/v1/static", {}, "/v1/static"), + ("", {}, ""), + ("/v1/?q={n}&count=10", dict(n=42), "/v1/?q=42&count=10"), + ("/v1/{v}", dict(v=None), "/v1/null"), + ("/v1/{v}", dict(v=True), "/v1/true"), + ("/v1/{v}", dict(v=False), "/v1/false"), + ("/v1/{v}", dict(v=".hidden"), "/v1/.hidden"), # dot prefix ok + ("/v1/{v}", dict(v="file.txt"), "/v1/file.txt"), # dot in middle ok + ("/v1/{v}", dict(v="..."), "/v1/..."), # triple dot ok + ("/v1/{a}{b}", dict(a=".", b="txt"), "/v1/.txt"), # dot var combining with adjacent to be ok + ("/items?q={v}#{f}", dict(v=".", f=".."), "/items?q=.#.."), # dots in query/fragment are fine + ( + "/v1/{a}?query={b}", + dict(a="../../other/endpoint", b="a&bad=true"), + "/v1/..%2F..%2Fother%2Fendpoint?query=a%26bad%3Dtrue", + ), + ("/v1/{val}", dict(val="a/b/c"), "/v1/a%2Fb%2Fc"), + ("/v1/{val}", dict(val="a/b/c?query=value"), "/v1/a%2Fb%2Fc%3Fquery=value"), + ("/v1/{val}", dict(val="a/b/c?query=value&bad=true"), "/v1/a%2Fb%2Fc%3Fquery=value&bad=true"), + ("/v1/{val}", dict(val="%20"), "/v1/%2520"), # escapes escape sequences in input + # Query: slash and ? are safe, # is not + ("/items?q={v}", dict(v="a/b"), "/items?q=a/b"), + ("/items?q={v}", dict(v="a?b"), "/items?q=a?b"), + ("/items?q={v}", dict(v="a#b"), "/items?q=a%23b"), + ("/items?q={v}", dict(v="a b"), "/items?q=a%20b"), + # Fragment: slash and ? are safe + ("/docs#{v}", dict(v="a/b"), "/docs#a/b"), + ("/docs#{v}", dict(v="a?b"), "/docs#a?b"), + # Path: slash, ? and # are all encoded + ("/v1/{v}", dict(v="a/b"), "/v1/a%2Fb"), + ("/v1/{v}", dict(v="a?b"), "/v1/a%3Fb"), + ("/v1/{v}", dict(v="a#b"), "/v1/a%23b"), + # same var encoded differently by component + ( + "/v1/{v}?q={v}#{v}", + dict(v="a/b?c#d"), + "/v1/a%2Fb%3Fc%23d?q=a/b?c%23d#a/b?c%23d", + ), + ("/v1/{val}", dict(val="x?admin=true"), "/v1/x%3Fadmin=true"), # query injection + ("/v1/{val}", dict(val="x#admin"), "/v1/x%23admin"), # fragment injection + ], +) +def test_interpolation(template: str, kwargs: dict[str, Any], expected: str) -> None: + assert path_template(template, **kwargs) == expected + + +def test_missing_kwarg_raises_key_error() -> None: + with pytest.raises(KeyError, match="org_id"): + path_template("/v1/{org_id}") + + +@pytest.mark.parametrize( + "template, kwargs", + [ + ("{a}/path", dict(a=".")), + ("{a}/path", dict(a="..")), + ("/v1/{a}", dict(a=".")), + ("/v1/{a}", dict(a="..")), + ("/v1/{a}/path", dict(a=".")), + ("/v1/{a}/path", dict(a="..")), + ("/v1/{a}{b}", dict(a=".", b=".")), # adjacent vars → ".." + ("/v1/{a}.", dict(a=".")), # var + static → ".." + ("/v1/{a}{b}", dict(a="", b=".")), # empty + dot → "." + ("/v1/%2e/{x}", dict(x="ok")), # encoded dot in static text + ("/v1/%2e./{x}", dict(x="ok")), # mixed encoded ".." in static + ("/v1/.%2E/{x}", dict(x="ok")), # mixed encoded ".." in static + ("/v1/{v}?q=1", dict(v="..")), + ("/v1/{v}#frag", dict(v="..")), + ], +) +def test_dot_segment_rejected(template: str, kwargs: dict[str, Any]) -> None: + with pytest.raises(ValueError, match="dot-segment"): + path_template(template, **kwargs) diff --git a/uv.lock b/uv.lock index fb6d812..723b067 100644 --- a/uv.lock +++ b/uv.lock @@ -456,7 +456,7 @@ requires-dist = [ { name = "pydantic", specifier = ">=1.9.0,<3" }, { name = "pyjwt", extras = ["crypto"], marker = "extra == 'auth'", specifier = ">=2.10.1" }, { name = "sniffio" }, - { name = "typing-extensions", specifier = ">=4.10,<5" }, + { name = "typing-extensions", specifier = ">=4.14,<5" }, ] provides-extras = ["aiohttp", "auth"]