diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8a5c919..8a74ed4 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/**' diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a80c237..1ed7be9 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.12.2" + ".": "1.12.3" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index 288e44b..3a6a221 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 27 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/moderation-api%2Fmoderation-api-ad93e48ef2ee1066fe81553c7ac1f3be24037c6e1976778acb8b13baedbe5821.yml -openapi_spec_hash: 06e01ccb380f068bff3a571b58089a94 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/moderation-api%2Fmoderation-api-815dce43cbb14e41f094bdbca84682c0b379dcfd02b7e8800f9d8b45c00a76fd.yml +openapi_spec_hash: ab7d073e793fe5a556e64d39963aea93 config_hash: 6b825a08e19dfb747c5dc1766502b789 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a6e4eb..70baa43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.12.3 (2026-03-20) + +Full Changelog: [v1.12.2...v1.12.3](https://github.com/moderation-api/sdk-python/compare/v1.12.2...v1.12.3) + +### Bug Fixes + +* sanitize endpoint path params ([82ab871](https://github.com/moderation-api/sdk-python/commit/82ab8719733bad759fc3e7dc199da0eaa76aca47)) + + +### Chores + +* **internal:** tweak CI branches ([405d710](https://github.com/moderation-api/sdk-python/commit/405d7101d6e0490e1a101d185450a2fa46ebd0d6)) + ## 1.12.2 (2026-03-17) Full Changelog: [v1.12.1...v1.12.2](https://github.com/moderation-api/sdk-python/compare/v1.12.1...v1.12.2) diff --git a/pyproject.toml b/pyproject.toml index 74906b0..8764e96 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "moderation_api" -version = "1.12.2" +version = "1.12.3" description = "The official Python library for the moderation-api API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/moderation_api/_utils/__init__.py b/src/moderation_api/_utils/__init__.py index dc64e29..10cb66d 100644 --- a/src/moderation_api/_utils/__init__.py +++ b/src/moderation_api/_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/moderation_api/_utils/_path.py b/src/moderation_api/_utils/_path.py new file mode 100644 index 0000000..4d6e1e4 --- /dev/null +++ b/src/moderation_api/_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/moderation_api/_version.py b/src/moderation_api/_version.py index ec3ad26..c3e7c65 100644 --- a/src/moderation_api/_version.py +++ b/src/moderation_api/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "moderation_api" -__version__ = "1.12.2" # x-release-please-version +__version__ = "1.12.3" # x-release-please-version diff --git a/src/moderation_api/resources/actions/actions.py b/src/moderation_api/resources/actions/actions.py index 791b94a..b867c61 100644 --- a/src/moderation_api/resources/actions/actions.py +++ b/src/moderation_api/resources/actions/actions.py @@ -17,7 +17,7 @@ AsyncExecuteResourceWithStreamingResponse, ) from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given -from ..._utils import maybe_transform, async_maybe_transform +from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -189,7 +189,7 @@ def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/actions/{id}", + path_template("/actions/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -278,7 +278,7 @@ def update( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._put( - f"/actions/{id}", + path_template("/actions/{id}", id=id), body=maybe_transform( { "built_in": built_in, @@ -365,7 +365,7 @@ def delete( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._delete( - f"/actions/{id}", + path_template("/actions/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -526,7 +526,7 @@ async def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/actions/{id}", + path_template("/actions/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -615,7 +615,7 @@ async def update( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._put( - f"/actions/{id}", + path_template("/actions/{id}", id=id), body=await async_maybe_transform( { "built_in": built_in, @@ -702,7 +702,7 @@ async def delete( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._delete( - f"/actions/{id}", + path_template("/actions/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/moderation_api/resources/actions/execute.py b/src/moderation_api/resources/actions/execute.py index cd27479..2f9110e 100644 --- a/src/moderation_api/resources/actions/execute.py +++ b/src/moderation_api/resources/actions/execute.py @@ -7,7 +7,7 @@ import httpx from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given -from ..._utils import maybe_transform, async_maybe_transform +from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -144,7 +144,7 @@ def execute_by_id( if not action_id: raise ValueError(f"Expected a non-empty value for `action_id` but received {action_id!r}") return self._post( - f"/actions/{action_id}/execute", + path_template("/actions/{action_id}/execute", action_id=action_id), body=maybe_transform( { "author_ids": author_ids, @@ -281,7 +281,7 @@ async def execute_by_id( if not action_id: raise ValueError(f"Expected a non-empty value for `action_id` but received {action_id!r}") return await self._post( - f"/actions/{action_id}/execute", + path_template("/actions/{action_id}/execute", action_id=action_id), body=await async_maybe_transform( { "author_ids": author_ids, diff --git a/src/moderation_api/resources/authors.py b/src/moderation_api/resources/authors.py index a8a90f4..22b8bf1 100644 --- a/src/moderation_api/resources/authors.py +++ b/src/moderation_api/resources/authors.py @@ -9,7 +9,7 @@ from ..types import author_list_params, author_create_params, author_update_params from .._types import Body, Omit, Query, Headers, NotGiven, omit, not_given -from .._utils import maybe_transform, async_maybe_transform +from .._utils import path_template, maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import ( @@ -149,7 +149,7 @@ def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/authors/{id}", + path_template("/authors/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -207,7 +207,7 @@ def update( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._put( - f"/authors/{id}", + path_template("/authors/{id}", id=id), body=maybe_transform( { "email": email, @@ -321,7 +321,7 @@ def delete( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._delete( - f"/authors/{id}", + path_template("/authors/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -450,7 +450,7 @@ async def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/authors/{id}", + path_template("/authors/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -508,7 +508,7 @@ async def update( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._put( - f"/authors/{id}", + path_template("/authors/{id}", id=id), body=await async_maybe_transform( { "email": email, @@ -622,7 +622,7 @@ async def delete( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._delete( - f"/authors/{id}", + path_template("/authors/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/moderation_api/resources/queue/items.py b/src/moderation_api/resources/queue/items.py index 017a6fb..9653876 100644 --- a/src/moderation_api/resources/queue/items.py +++ b/src/moderation_api/resources/queue/items.py @@ -7,7 +7,7 @@ import httpx from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given -from ..._utils import maybe_transform, async_maybe_transform +from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -90,7 +90,7 @@ def list( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/queue/{id}/items", + path_template("/queue/{id}/items", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -152,7 +152,7 @@ def resolve( if not item_id: raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}") return self._post( - f"/queue/{id}/items/{item_id}/resolve", + path_template("/queue/{id}/items/{item_id}/resolve", id=id, item_id=item_id), body=maybe_transform({"comment": comment}, item_resolve_params.ItemResolveParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -196,7 +196,7 @@ def unresolve( if not item_id: raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}") return self._post( - f"/queue/{id}/items/{item_id}/unresolve", + path_template("/queue/{id}/items/{item_id}/unresolve", id=id, item_id=item_id), body=maybe_transform({"comment": comment}, item_unresolve_params.ItemUnresolveParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -270,7 +270,7 @@ async def list( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/queue/{id}/items", + path_template("/queue/{id}/items", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -332,7 +332,7 @@ async def resolve( if not item_id: raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}") return await self._post( - f"/queue/{id}/items/{item_id}/resolve", + path_template("/queue/{id}/items/{item_id}/resolve", id=id, item_id=item_id), body=await async_maybe_transform({"comment": comment}, item_resolve_params.ItemResolveParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -376,7 +376,7 @@ async def unresolve( if not item_id: raise ValueError(f"Expected a non-empty value for `item_id` but received {item_id!r}") return await self._post( - f"/queue/{id}/items/{item_id}/unresolve", + path_template("/queue/{id}/items/{item_id}/unresolve", id=id, item_id=item_id), body=await async_maybe_transform({"comment": comment}, item_unresolve_params.ItemUnresolveParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/moderation_api/resources/queue/queue.py b/src/moderation_api/resources/queue/queue.py index cbf3a48..f1e6975 100644 --- a/src/moderation_api/resources/queue/queue.py +++ b/src/moderation_api/resources/queue/queue.py @@ -14,7 +14,7 @@ ) from ...types import queue_get_stats_params from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given -from ..._utils import maybe_transform, async_maybe_transform +from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -82,7 +82,7 @@ def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/queue/{id}", + path_template("/queue/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -121,7 +121,7 @@ def get_stats( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/queue/{id}/stats", + path_template("/queue/{id}/stats", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -185,7 +185,7 @@ async def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/queue/{id}", + path_template("/queue/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -224,7 +224,7 @@ async def get_stats( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/queue/{id}/stats", + path_template("/queue/{id}/stats", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, diff --git a/src/moderation_api/resources/wordlist/wordlist.py b/src/moderation_api/resources/wordlist/wordlist.py index 7023e0c..9ad95a2 100644 --- a/src/moderation_api/resources/wordlist/wordlist.py +++ b/src/moderation_api/resources/wordlist/wordlist.py @@ -14,7 +14,7 @@ ) from ...types import wordlist_update_params from ..._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given -from ..._utils import maybe_transform, async_maybe_transform +from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -84,7 +84,7 @@ def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/wordlist/{id}", + path_template("/wordlist/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -135,7 +135,7 @@ def update( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._put( - f"/wordlist/{id}", + path_template("/wordlist/{id}", id=id), body=maybe_transform( { "description": description, @@ -199,7 +199,7 @@ def get_embedding_status( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._get( - f"/wordlist/{id}/embedding-status", + path_template("/wordlist/{id}/embedding-status", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -259,7 +259,7 @@ async def retrieve( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/wordlist/{id}", + path_template("/wordlist/{id}", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -310,7 +310,7 @@ async def update( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._put( - f"/wordlist/{id}", + path_template("/wordlist/{id}", id=id), body=await async_maybe_transform( { "description": description, @@ -374,7 +374,7 @@ async def get_embedding_status( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._get( - f"/wordlist/{id}/embedding-status", + path_template("/wordlist/{id}/embedding-status", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/moderation_api/resources/wordlist/words.py b/src/moderation_api/resources/wordlist/words.py index e400ffb..00a3813 100644 --- a/src/moderation_api/resources/wordlist/words.py +++ b/src/moderation_api/resources/wordlist/words.py @@ -5,7 +5,7 @@ import httpx from ..._types import Body, Query, Headers, NotGiven, SequenceNotStr, not_given -from ..._utils import maybe_transform, async_maybe_transform +from ..._utils import path_template, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -73,7 +73,7 @@ def add( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._post( - f"/wordlist/{id}/words", + path_template("/wordlist/{id}/words", id=id), body=maybe_transform({"words": words}, word_add_params.WordAddParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -112,7 +112,7 @@ def remove( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return self._delete( - f"/wordlist/{id}/words", + path_template("/wordlist/{id}/words", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -175,7 +175,7 @@ async def add( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._post( - f"/wordlist/{id}/words", + path_template("/wordlist/{id}/words", id=id), body=await async_maybe_transform({"words": words}, word_add_params.WordAddParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -214,7 +214,7 @@ async def remove( if not id: raise ValueError(f"Expected a non-empty value for `id` but received {id!r}") return await self._delete( - f"/wordlist/{id}/words", + path_template("/wordlist/{id}/words", id=id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, diff --git a/tests/test_utils/test_path.py b/tests/test_utils/test_path.py new file mode 100644 index 0000000..7e6d85a --- /dev/null +++ b/tests/test_utils/test_path.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from typing import Any + +import pytest + +from moderation_api._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)