Skip to content
Merged
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
9 changes: 5 additions & 4 deletions clients/python/src/objectstore_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def _make_headers(self) -> dict[str, str]:

def _make_url(self, key: str | None, full: bool = False) -> str:
relative_path = f"/v1/objects/{self._usecase.name}/{self._scope}/{key or ''}"
path = self._base_path.rstrip("/") + relative_path
path = utils.encode_path(self._base_path.rstrip("/") + relative_path)
if full:
return f"http://{self._pool.host}:{self._pool.port}{path}"
return path
Expand All @@ -290,7 +290,7 @@ def _make_multipart_url(
resource = "objects:multipart"

relative_path = f"/v1/{resource}/{self._usecase.name}/{self._scope}/{key or ''}"
path = self._base_path.rstrip("/") + relative_path
path = utils.encode_path(self._base_path.rstrip("/") + relative_path)
if query:
return f"{path}?{query}"
return path
Expand Down Expand Up @@ -485,9 +485,10 @@ def presigned_object_url(
)
duration_secs = math.ceil(duration.total_seconds())

encoded_path = presign.encode_path(self._make_url(key))
# `_make_url` already percent-encodes the path identically to the wire.
encoded_path = self._make_url(key)
timestamp = datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
encoded_query = presign.encode_query(
encoded_query = utils.encode_query(
f"{presign.PARAM_KID}={self._token.kid}"
f"&{presign.PARAM_TIMESTAMP}={timestamp}"
f"&{presign.PARAM_DURATION}={duration_secs}"
Expand Down
37 changes: 2 additions & 35 deletions clients/python/src/objectstore_client/presign.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,6 @@
"""

from datetime import timedelta
from urllib.parse import quote

# Characters left unescaped when percent-encoding, expressed in RFC 3986 terms.
# `urllib.parse.quote` already leaves the *unreserved* set (ALPHA / DIGIT /
# "-._~") untouched, so `safe` only lists the extra characters permitted in a
# path or query without escaping:
# - sub-delims: "!$&'()*+,;="
# - path extras: ":" "@" "/" (the pchar set plus the "/" segment separator)
# - query also allows "?"
# This is the same set urllib3 leaves unescaped, so the encoding is a fixed
# point of the HTTP client that ultimately sends the URL and survives on the
# wire verbatim. It is also byte-for-byte identical to the Rust client's
# `percent_encoding` set (see `objectstore-types/src/presign.rs`), so the two
# clients produce the same signed bytes for any key.
_PATH_SAFE = "/:@!$&'()*+,;="
_QUERY_SAFE = _PATH_SAFE + "?"

# Query parameter carrying the RFC 3339 time at which the request was signed.
PARAM_TIMESTAMP = "os_timestamp"
Expand All @@ -44,29 +28,12 @@
SUPPORTED_METHODS = ("GET", "HEAD")


def encode_path(path: str) -> str:
"""Percent-encodes a request path as it will appear on the wire.

Leaves the RFC 3986 unreserved set, sub-delims, and ``:`` ``@`` ``/``
unescaped (see :data:`_PATH_SAFE`); everything else is percent-encoded.
"""
return quote(path, safe=_PATH_SAFE)


def encode_query(query: str) -> str:
"""Percent-encodes a query string as it will appear on the wire.

Same set as :func:`encode_path`, additionally leaving ``?`` unescaped
(see :data:`_QUERY_SAFE`).
"""
return quote(query, safe=_QUERY_SAFE)


def build_canonical_form(method: str, encoded_path: str, encoded_query: str) -> str:
"""Builds the canonical form of a request to be signed.

``encoded_path`` and ``encoded_query`` must already be percent-encoded as
they will appear on the wire (see :func:`encode_path` / :func:`encode_query`).
they will appear on the wire (see :func:`objectstore_client.utils.encode_path`
and :func:`objectstore_client.utils.encode_query`).
"""
normalized_method = "GET" if method.upper() == "HEAD" else method.upper()

Expand Down
35 changes: 35 additions & 0 deletions clients/python/src/objectstore_client/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,45 @@

import io
from typing import IO, Any
from urllib.parse import quote

import filetype # type: ignore[import-untyped]
from zstandard import ZstdCompressionReader

# Characters left unescaped when percent-encoding a URL path or query, expressed
# in RFC 3986 terms. `urllib.parse.quote` already leaves the *unreserved* set
# (ALPHA / DIGIT / "-._~") untouched, so `safe` only lists the extra characters
# permitted without escaping:
# - sub-delims: "!$&'()*+,;="
# - path extras: ":" "@" "/" (the pchar set plus the "/" segment separator)
# - query also allows "?"
# This is the same set urllib3 leaves unescaped, so the encoding is a fixed point
# of the HTTP client that ultimately sends the URL and survives on the wire
# verbatim. It is also byte-for-byte identical to the Rust client's
# `percent_encoding` set (see `objectstore-types/src/presign.rs`), so the two
# clients produce the same bytes for any key.
_PATH_SAFE = "/:@!$&'()*+,;="
_QUERY_SAFE = _PATH_SAFE + "?"


def encode_path(path: str) -> str:
"""Percent-encodes a request path as it will appear on the wire.

Leaves the RFC 3986 unreserved set, sub-delims, and ``:`` ``@`` ``/``
unescaped (see :data:`_PATH_SAFE`); everything else is percent-encoded. This
treats the input as a literal string: a literal ``%`` becomes ``%25``.
"""
return quote(path, safe=_PATH_SAFE)


def encode_query(query: str) -> str:
"""Percent-encodes a query string as it will appear on the wire.

Same set as :func:`encode_path`, additionally leaving ``?`` unescaped
(see :data:`_QUERY_SAFE`).
"""
return quote(query, safe=_QUERY_SAFE)


def parse_accept_encoding(header: str) -> list[str]:
"""Parse an Accept-Encoding header value for use in objectstore GET requests.
Expand Down
39 changes: 28 additions & 11 deletions clients/python/tests/test_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -788,15 +788,11 @@ def test_presigned_tampered_signature_unauthorized(server_url: str) -> None:


# Object keys exercising URL-encoding corner cases. Each must round-trip: the
# normal urllib3 `put` and the pre-signed `urllib` GET encode the path
# identically, so they resolve to the same stored object. `?`/`#` are excluded
# because urllib3's `put` path treats them as query/fragment delimiters.
#
# Keys containing a literal `%XX` (percent followed by two hex digits) currently
# diverge and are excluded: presigning uses `urllib.parse.quote`, which escapes
# the `%` to `%25` (targeting the literal key), whereas urllib3's `put` path
# treats `%20` as an existing escape and leaves it intact, so the two resolve to
# different stored objects. See `looks%20encoded` below.
# normal `put` and the pre-signed `urllib` GET percent-encode the path
# identically (both treat the key as a literal string, see
# `utils.encode_path`), so they resolve to the same stored object. This
# includes keys containing a literal `%XX`: the `%` is escaped to `%25` rather
# than mistaken for an existing escape (see `test_put_stores_under_literal_key`).
ENCODING_CORNER_CASE_KEYS = [
"plain-key",
"with space",
Expand All @@ -805,8 +801,8 @@ def test_presigned_tampered_signature_unauthorized(server_url: str) -> None:
"plus+sign",
"sub!$'()*+,=delims",
"tilde~dot.key",
"100%literal-percent", # `%li` isn't a valid escape, so both escape the `%`
# "looks%20encoded", # diverges: quote -> %2520, urllib3 put -> %20
"100%literal-percent",
"looks%20encoded",
"nested/path/segments",
"quote'apostrophe",
"at@sign",
Expand All @@ -828,3 +824,24 @@ def test_presigned_get_encoding_corner_cases(server_url: str, key: str) -> None:

assert status == 200, f"key {key!r} failed with status {status}"
assert body == payload


def test_put_stores_under_literal_key(server_url: str) -> None:
# A literal "%XX" in a key must be stored verbatim, not decoded: `put` sends
# `looks%2520encoded` on the wire, which the server decodes back to the
# literal key `looks%20encoded` rather than `looks encoded`. The server
# echoes the stored key in the `put` response body, so we can assert directly
# which key the object landed under.
session = _presign_session(server_url)
key = "looks%20encoded"
payload = b"literal percent key"

stored_key = session.put(payload, key=key)
assert stored_key == key

# Retrievable by that same literal key, both normally and pre-signed.
assert session.get(key).payload.read() == payload
url = session.presigned_object_url("GET", key, duration=timedelta(hours=1))
status, body = _fetch(url)
assert status == 200
assert body == payload
16 changes: 8 additions & 8 deletions clients/python/tests/test_presign.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from objectstore_client import presign
from objectstore_client import presign, utils
from objectstore_client.auth import SecretKey

TEST_EDDSA_PRIVKEY_PATH = os.path.join(os.path.dirname(__file__), "ed25519.private.pem")
Expand All @@ -26,7 +26,7 @@ def test_canonical_form_full_query() -> None:
# key lowercasing, and query sort order.
path = "/v1/objects/testing/org=17;project=42/foo/bar"
canonical = presign.build_canonical_form(
"GET", presign.encode_path(path), presign.encode_query(SAMPLE_QUERY)
"GET", utils.encode_path(path), utils.encode_query(SAMPLE_QUERY)
)
assert canonical == (
"GET\n"
Expand All @@ -38,15 +38,15 @@ def test_canonical_form_full_query() -> None:
def test_canonical_form_duplicate_keys_preserved_and_sorted() -> None:
canonical = presign.build_canonical_form(
"GET",
presign.encode_path("/v1/objects/testing/_/key"),
presign.encode_query("dup=b&dup=a&x=1"),
utils.encode_path("/v1/objects/testing/_/key"),
utils.encode_query("dup=b&dup=a&x=1"),
)
assert canonical == "GET\n/v1/objects/testing/_/key\ndup=a&dup=b&x=1"


def test_head_is_normalized_to_get() -> None:
path = presign.encode_path("/v1/objects/testing/_/key")
query = presign.encode_query(SAMPLE_QUERY)
path = utils.encode_path("/v1/objects/testing/_/key")
query = utils.encode_query(SAMPLE_QUERY)
assert presign.build_canonical_form(
"HEAD", path, query
) == presign.build_canonical_form("GET", path, query)
Expand All @@ -63,8 +63,8 @@ def test_sign_canonical_form_roundtrips_with_public_key() -> None:

canonical = presign.build_canonical_form(
"GET",
presign.encode_path("/v1/objects/testing/_/key"),
presign.encode_query(SAMPLE_QUERY),
utils.encode_path("/v1/objects/testing/_/key"),
utils.encode_query(SAMPLE_QUERY),
)
signature_b64 = key.signature_for_canonical_form(canonical)

Expand Down
Loading