From aa4d4bf91087af826f199e9dfab4d68c56714a93 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Wed, 8 Jul 2026 17:33:26 +0200 Subject: [PATCH 01/13] feat(python): Add pre-signed URL support to the client Add Session.presigned_url(method, key, duration) to mint time-limited, Ed25519-signed URLs authorizing a single GET/HEAD/DELETE without an auth token. The signing scheme mirrors the server-side canonical form in objectstore-types/src/presign.rs. The client must sign the exact path/query bytes its HTTP client puts on the wire, since the server verifies the signature against the raw, still percent-encoded request it receives. To guarantee that match, the encoding reuses urllib3's own request-target encoder rather than reimplementing it. Raises ValueError when the session has no TokenGenerator (a static token string cannot sign), when the method is unsupported, or when the duration is not a positive whole number of seconds up to the one-week maximum. IPv6 hosts are bracketed so the generated URL is valid. Includes a unit-level encoding test bench asserting parity with urllib3's wire encoding across URL-encoding corner cases, plus end-to-end tests that fetch the signed URLs against a live server with urllib. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01Ka5MAEnDBSQjZjHbArRXkN --- clients/python/README.md | 23 +++ .../python/src/objectstore_client/client.py | 75 ++++++++- .../python/src/objectstore_client/presign.py | 114 +++++++++++++ clients/python/tests/test_e2e.py | 156 +++++++++++++++++- clients/python/tests/test_presign.py | 149 +++++++++++++++++ clients/python/tests/test_smoke.py | 44 +++++ 6 files changed, 559 insertions(+), 2 deletions(-) create mode 100644 clients/python/src/objectstore_client/presign.py create mode 100644 clients/python/tests/test_presign.py diff --git a/clients/python/README.md b/clients/python/README.md index ba0bed88..0fbb31c2 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -184,6 +184,29 @@ token = TokenGenerator( client = Client("http://localhost:8888", token=token) ``` +### Pre-signed URLs + +A **pre-signed URL** is a time-limited URL that authorizes a single request on +one object without the recipient needing an auth token. This is useful for +handing a download link to a browser or an external service. + +`Session.presigned_url` signs the URL with the session's `TokenGenerator` +keypair, so it requires a `TokenGenerator` (a static token string cannot sign) +and raises `ValueError` otherwise. Only `GET`, `HEAD`, and `DELETE` may be +pre-signed, the granted permissions are those configured server-side for the +signing key, and the validity may not exceed one week. + +```python +from datetime import timedelta + +# The recipient can fetch this with any HTTP client, no auth header needed. +url = session.presigned_url("GET", "my-key", duration=timedelta(hours=1)) + +import urllib.request +with urllib.request.urlopen(url) as resp: + content = resp.read() +``` + ## Configuration In production, store the `Client` and `Usecase` at module level and reuse them. diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 0779529f..f44a1be4 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -2,6 +2,7 @@ from collections.abc import Mapping, Sequence from dataclasses import asdict, dataclass +from datetime import UTC, datetime, timedelta from io import BytesIO from typing import IO, Any, Literal, NamedTuple, cast from urllib.parse import urlparse @@ -11,7 +12,7 @@ import zstandard from urllib3.connectionpool import HTTPConnectionPool -from objectstore_client import utils +from objectstore_client import presign, utils from objectstore_client.auth import Permission, TokenGenerator, TokenProvider from objectstore_client.errors import raise_for_status from objectstore_client.metadata import ( @@ -446,6 +447,78 @@ def object_url(self, key: str) -> str: """ return self._make_url(key, full=True) + def presigned_url( + self, + method: Literal["GET", "HEAD", "DELETE"], + key: str, + duration: timedelta, + ) -> str: + """ + Generates a pre-signed URL authorizing a single ``method`` request on the + object with the given ``key``, valid for ``duration``. + + The returned URL carries an Ed25519 signature in its query string, so the + recipient can perform the request without an auth token. It can be handed + to any HTTP client (``urllib``, ``requests``, a browser, ...); the URL is + already percent-encoded and must be transmitted verbatim. + + Only ``GET``, ``HEAD`` and ``DELETE`` may be pre-signed. The permissions + granted are those configured server-side for the signing key, so a + read-only key cannot produce a working ``DELETE`` URL. ``duration`` must + not exceed one week. + + Raises ``ValueError`` if no ``TokenGenerator`` is configured on this + session (a static token string cannot sign), if ``method`` is not + supported, or if ``duration`` is not a positive whole number of seconds + up to the one-week maximum. + """ + normalized_method = method.upper() + if normalized_method not in presign.SUPPORTED_METHODS: + raise ValueError( + f"unsupported pre-signed method {method!r}, " + f"expected one of {presign.SUPPORTED_METHODS}" + ) + + if not isinstance(self._token, TokenGenerator): + raise ValueError("no token generator configured on this session") + + if duration > presign.MAX_PRESIGN_DURATION: + raise ValueError( + f"duration {duration} exceeds the maximum of " + f"{presign.MAX_PRESIGN_DURATION}" + ) + # The validity is transmitted as whole seconds, so anything that + # truncates to zero (or less) would yield an already-expired URL. + duration_secs = int(duration.total_seconds()) + if duration_secs < 1: + raise ValueError( + f"duration {duration} is too short; must be at least one second" + ) + + encoded_path = presign.encode_path(self._make_url(key)) + timestamp = datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + encoded_query = presign.encode_query( + f"{presign.PARAM_KID}={self._token.kid}" + f"&{presign.PARAM_TIMESTAMP}={timestamp}" + f"&{presign.PARAM_DURATION}={duration_secs}" + ) + + canonical = presign.build_canonical( + normalized_method, encoded_path, encoded_query + ) + signature = presign.sign_canonical(self._token.secret_key, canonical) + + # urllib3 stores IPv6 hosts unbracketed (e.g. "::1"); bracket them so the + # result is a valid absolute URL. + host = self._pool.host + if ":" in host: + host = f"[{host}]" + + return ( + f"{self._pool.scheme}://{host}:{self._pool.port}" + f"{encoded_path}?{encoded_query}&{presign.PARAM_SIG}={signature}" + ) + def head(self, key: str) -> Metadata | None: """ Checks whether an object exists and retrieves its metadata. diff --git a/clients/python/src/objectstore_client/presign.py b/clients/python/src/objectstore_client/presign.py new file mode 100644 index 00000000..7fac5407 --- /dev/null +++ b/clients/python/src/objectstore_client/presign.py @@ -0,0 +1,114 @@ +"""Utilities for signing pre-signed URLs. + +A pre-signed URL lets a client that owns an Ed25519 keypair hand out a +time-limited URL that authorizes a specific request, without the recipient +needing an auth token. + +This mirrors the server-side scheme defined in ``objectstore-types/src/presign.rs``. +The signature covers a canonical form of the request: + + \\n\\n + +- normalized method: the uppercase HTTP method, with ``HEAD`` mapped to ``GET``; +- path: the request path, exactly as transmitted on the wire; +- canonical query string: every query parameter except ``os_sig``, with keys + lowercased, sorted lexicographically, joined with ``&``. + +The signature is Ed25519 over the canonical form's UTF-8 bytes, encoded as +base64url without padding, and carried in the ``os_sig`` query parameter. + +Encoding note: the server verifies the signature against the raw (still +percent-encoded) path and query it receives, without normalizing them. The +client must therefore sign the *exact bytes* its HTTP client puts on the wire. +The Python client uses urllib3, whose ``HTTPConnectionPool.urlopen`` encodes +request targets with ``urllib3.util.url._encode_target``. We reuse those same +internal helpers here so the encoding we sign matches the wire encoding by +construction; a parity test guards against upstream changes. +""" + +import base64 +from datetime import timedelta + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import load_pem_private_key + +# urllib3 internals that produce the on-the-wire request target. These are the +# exact functions urllib3 applies in `HTTPConnectionPool.urlopen`, so signing +# their output guarantees a byte-for-byte match with what the client sends. +from urllib3.util.url import ( # type: ignore[attr-defined] + _PATH_CHARS, + _QUERY_CHARS, + _encode_invalid_chars, +) + +# Query parameter carrying the RFC 3339 time at which the request was signed. +PARAM_TIMESTAMP = "os_timestamp" + +# Query parameter carrying the validity duration, in seconds. +PARAM_DURATION = "os_duration" + +# Query parameter naming the key ID used to sign the request. +PARAM_KID = "os_kid" + +# Query parameter carrying the base64url-encoded signature. +PARAM_SIG = "os_sig" + +# Maximum validity accepted by the server for a pre-signed URL. +MAX_PRESIGN_DURATION = timedelta(days=7) + +# HTTP methods that may be pre-signed. The server rejects all others. +SUPPORTED_METHODS = ("GET", "HEAD", "DELETE") + + +def encode_path(path: str) -> str: + """Percent-encodes a request path the same way urllib3 sends it on the wire. + + Unlike urllib3's full request-target encoder, this also encodes ``?`` and + ``#`` (which are not in the path character set), so that those characters + appearing inside an object key cannot be mistaken for the query or fragment + delimiter. + """ + return _encode_invalid_chars(path, _PATH_CHARS) + + +def encode_query(query: str) -> str: + """Percent-encodes a query string the same way urllib3 sends it on the wire.""" + return _encode_invalid_chars(query, _QUERY_CHARS) + + +def build_canonical(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`). + """ + normalized_method = "GET" if method.upper() == "HEAD" else method.upper() + + pairs = [] + for pair in encoded_query.split("&"): + if not pair: + continue + key, sep, value = pair.partition("=") + key = key.lower() + if key == PARAM_SIG: + continue + pairs.append(f"{key}={value}" if sep else key) + pairs.sort() + canonical_query = "&".join(pairs) + + return f"{normalized_method}\n{encoded_path}\n{canonical_query}" + + +def sign_canonical(secret_key_pem: str, canonical: str) -> str: + """Signs a canonical request with an Ed25519 private key. + + ``secret_key_pem`` is a PEM-encoded Ed25519 private key (the same key a + :class:`~objectstore_client.auth.TokenGenerator` uses to sign JWTs). Returns + the base64url-encoded (no padding) signature, suitable as the value of the + ``os_sig`` query parameter. + """ + key = load_pem_private_key(secret_key_pem.encode(), password=None) + if not isinstance(key, Ed25519PrivateKey): + raise ValueError("pre-signed URLs require an Ed25519 private key") + signature = key.sign(canonical.encode()) + return base64.urlsafe_b64encode(signature).rstrip(b"=").decode() diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 359be23d..c6e84cfb 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -5,6 +5,8 @@ import subprocess import tempfile import time +import urllib.error +import urllib.request from collections.abc import Generator from datetime import timedelta from io import BytesIO @@ -13,7 +15,7 @@ import pytest import urllib3 import zstandard -from objectstore_client import Client, Usecase +from objectstore_client import Client, Session, Usecase from objectstore_client.auth import Permission, TokenGenerator from objectstore_client.errors import RequestError from objectstore_client.metadata import TimeToLive @@ -678,3 +680,155 @@ def put_part(part_number: int, data: bytes) -> CompletePart: retrieved = session.get(final_key) assert retrieved.payload.read() == b"".join(chunks) + + +def _fetch(url: str, method: str = "GET") -> tuple[int, bytes]: + """Fetches ``url`` with plain urllib (no auth header), returning (status, body). + + Using stdlib urllib proves the pre-signed URL is transmitted verbatim by an + HTTP client other than the objectstore client itself. + """ + req = urllib.request.Request(url, method=method) + try: + with urllib.request.urlopen(req, timeout=5) as resp: + return resp.status, resp.read() + except urllib.error.HTTPError as e: + return e.code, e.read() + + +def _presign_session(server_url: str) -> Session: + client = Client(server_url, token=TestTokenGenerator.get()) + # Store uncompressed so a raw (non-decompressing) urllib GET of the + # pre-signed URL returns the original bytes verbatim. + usecase = Usecase( + "test-usecase", + compression="none", + expiration_policy=TimeToLive(timedelta(days=1)), + ) + return client.session(usecase, org=42, project=1337) + + +def test_presigned_get_succeeds(server_url: str) -> None: + session = _presign_session(server_url) + session.put(b"presigned hello", key="presigned-get") + + url = session.presigned_url("GET", "presigned-get", duration=timedelta(hours=1)) + status, body = _fetch(url) + + assert status == 200 + assert body == b"presigned hello" + + +def test_presigned_head_succeeds(server_url: str) -> None: + session = _presign_session(server_url) + session.put(b"presigned hello", key="presigned-head") + + url = session.presigned_url("HEAD", "presigned-head", duration=timedelta(hours=1)) + status, _ = _fetch(url, method="HEAD") + + assert status == 204 + + +def test_presigned_delete_succeeds_then_gone(server_url: str) -> None: + session = _presign_session(server_url) + session.put(b"presigned hello", key="presigned-delete") + + delete_url = session.presigned_url( + "DELETE", "presigned-delete", duration=timedelta(hours=1) + ) + status, _ = _fetch(delete_url, method="DELETE") + assert status == 204 + + # A subsequent pre-signed GET should now 404. + get_url = session.presigned_url( + "GET", "presigned-delete", duration=timedelta(hours=1) + ) + status, _ = _fetch(get_url) + assert status == 404 + + +def test_presigned_case_insensitive_method(server_url: str) -> None: + session = _presign_session(server_url) + session.put(b"lowercase method", key="presigned-lower") + + # Lowercase method is normalized to uppercase at runtime. + url = session.presigned_url("get", "presigned-lower", duration=timedelta(hours=1)) # type: ignore[arg-type] + status, body = _fetch(url) + + assert status == 200 + assert body == b"lowercase method" + + +def test_presigned_requires_token_generator(server_url: str) -> None: + # A static token string cannot sign pre-signed URLs. + token = TestTokenGenerator.get().sign_for_scope( + "test-usecase", Scope(org=42, project=1337) + ) + client = Client(server_url, token=token) + usecase = Usecase("test-usecase") + session = client.session(usecase, org=42, project=1337) + + with pytest.raises(ValueError, match="no token generator"): + session.presigned_url("GET", "whatever", duration=timedelta(hours=1)) + + +def test_presigned_rejects_unsupported_method(server_url: str) -> None: + session = _presign_session(server_url) + with pytest.raises(ValueError, match="unsupported pre-signed method"): + session.presigned_url("PUT", "whatever", duration=timedelta(hours=1)) # type: ignore[arg-type] + + +def test_presigned_rejects_duration_over_max(server_url: str) -> None: + session = _presign_session(server_url) + with pytest.raises(ValueError, match="exceeds the maximum"): + session.presigned_url("GET", "whatever", duration=timedelta(days=8)) + + +def test_presigned_tampered_signature_unauthorized(server_url: str) -> None: + session = _presign_session(server_url) + session.put(b"presigned hello", key="presigned-tamper") + + url = session.presigned_url("GET", "presigned-tamper", duration=timedelta(hours=1)) + # Flip the last character of the signature. + last = url[-1] + tampered = url[:-1] + ("A" if last != "A" else "B") + + status, _ = _fetch(tampered) + assert status == 401 + + +# 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. +ENCODING_CORNER_CASE_KEYS = [ + "plain-key", + "with space", + "café-unicode", + "emoji-😀", + "plus+sign", + "sub!$'()*+,=delims", + "tilde~dot.key", + "100%literal-percent", + "looks%20encoded", + "nested/path/segments", + "quote'apostrophe", + "at@sign", + "colon:separated", + "ampersand&inside", + "semi;colon", + "equals=sign", +] + + +@pytest.mark.parametrize("key", ENCODING_CORNER_CASE_KEYS) +def test_presigned_get_encoding_corner_cases(server_url: str, key: str) -> None: + session = _presign_session(server_url) + payload = f"payload for {key}".encode() + session.put(payload, key=key) + + url = session.presigned_url("GET", key, duration=timedelta(hours=1)) + status, body = _fetch(url) + + assert status == 200, f"key {key!r} failed with status {status}" + assert body == payload diff --git a/clients/python/tests/test_presign.py b/clients/python/tests/test_presign.py new file mode 100644 index 00000000..c9365f5c --- /dev/null +++ b/clients/python/tests/test_presign.py @@ -0,0 +1,149 @@ +"""Unit tests for the pre-signed URL signing utilities. + +These pin the canonical form against the Rust reference vectors +(``objectstore-types/src/presign.rs``) and, crucially, assert that our path/query +encoding matches byte-for-byte what urllib3 puts on the wire. +""" + +import base64 +import os + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey +from cryptography.hazmat.primitives.serialization import load_pem_public_key +from objectstore_client import presign + +# urllib3's real request-target encoder: the ground truth for wire encoding. +from urllib3.util.url import _encode_target # type: ignore[attr-defined] + +TEST_EDDSA_PRIVKEY_PATH = os.path.join(os.path.dirname(__file__), "ed25519.private.pem") +TEST_EDDSA_PUBKEY_PATH = os.path.join(os.path.dirname(__file__), "ed25519.public.pem") + +# Raw query string as it would appear on the wire: unsorted, includes the +# os_sig that must be excluded. Mirrors `sample_query()` in presign.rs. +SAMPLE_QUERY = ( + "os_timestamp=1985-04-12T23:20:50.52Z" + "&os_kid=relay" + "&os_duration=3600" + "&os_sig=should-be-excluded" +) + + +def test_canonical_form_full_query() -> None: + # Base case: pins path (slashes, `=`, `;` unencoded), os_sig exclusion, + # key lowercasing, and query sort order. + path = "/v1/objects/testing/org=17;project=42/foo/bar" + canonical = presign.build_canonical( + "GET", presign.encode_path(path), presign.encode_query(SAMPLE_QUERY) + ) + assert canonical == ( + "GET\n" + "/v1/objects/testing/org=17;project=42/foo/bar\n" + "os_duration=3600&os_kid=relay&os_timestamp=1985-04-12T23:20:50.52Z" + ) + + +def test_canonical_form_empty_query() -> None: + canonical = presign.build_canonical( + "GET", presign.encode_path("/v1/objects/testing/_/key"), "" + ) + assert canonical == "GET\n/v1/objects/testing/_/key\n" + + +def test_canonical_form_duplicate_keys_preserved_and_sorted() -> None: + canonical = presign.build_canonical( + "GET", + presign.encode_path("/v1/objects/testing/_/key"), + presign.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) + assert presign.build_canonical("HEAD", path, query) == presign.build_canonical( + "GET", path, query + ) + + +# Keys that round-trip through urllib3's request-target encoder (no `?`/`#`, +# which urllib3 would treat as the query/fragment delimiter). +WIRE_SAFE_KEYS = [ + "simple", + "hello world", + "café", + "emoji-😀-key", + "plus+plus", + "sub!$&'()*+,;=delims", + "tilde~and.dot", + "100%done", + "already%20encoded", + "nested/a/b/c", + "trailing space ", + "quote'apostrophe", + "at@sign", + "colon:and/slash", +] + + +@pytest.mark.parametrize("key", WIRE_SAFE_KEYS) +def test_encode_path_matches_urllib3_wire_encoding(key: str) -> None: + # Our signed path encoding must equal exactly what urllib3 sends on the wire. + path = f"/v1/objects/test/org=1/{key}" + assert presign.encode_path(path) == _encode_target(path) + + +@pytest.mark.parametrize( + ("key", "encoded"), + [ + ("has?question", "has%3Fquestion"), + ("has#hash", "has%23hash"), + ], +) +def test_encode_path_encodes_query_and_fragment_delimiters( + key: str, encoded: str +) -> None: + # Unlike urllib3's target encoder (which would split on `?`/`#`), we encode + # them so they can appear literally inside an object key. + path = f"/v1/objects/test/org=1/{key}" + assert presign.encode_path(path) == f"/v1/objects/test/org=1/{encoded}" + + +def test_sign_canonical_roundtrips_with_public_key() -> None: + with open(TEST_EDDSA_PRIVKEY_PATH) as f: + secret_key = f.read() + with open(TEST_EDDSA_PUBKEY_PATH, "rb") as f: + public_key = load_pem_public_key(f.read()) + assert isinstance(public_key, Ed25519PublicKey) + + canonical = presign.build_canonical( + "GET", + presign.encode_path("/v1/objects/testing/_/key"), + presign.encode_query(SAMPLE_QUERY), + ) + signature_b64 = presign.sign_canonical(secret_key, canonical) + + # Decode the base64url-no-pad signature and verify with the public key. + padding = "=" * (-len(signature_b64) % 4) + signature = base64.urlsafe_b64decode(signature_b64 + padding) + assert len(signature) == 64 + public_key.verify(signature, canonical.encode()) # raises on mismatch + + +def test_sign_canonical_rejects_non_ed25519_key() -> None: + # An RSA key is a valid PEM private key but not Ed25519. + from cryptography.hazmat.primitives.asymmetric import rsa + from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + ) + + rsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = rsa_key.private_bytes( + Encoding.PEM, PrivateFormat.PKCS8, NoEncryption() + ).decode() + + with pytest.raises(ValueError, match="Ed25519"): + presign.sign_canonical(pem, "GET\n/x\n") diff --git a/clients/python/tests/test_smoke.py b/clients/python/tests/test_smoke.py index 2e51ea14..25a94acc 100644 --- a/clients/python/tests/test_smoke.py +++ b/clients/python/tests/test_smoke.py @@ -1,4 +1,23 @@ +from datetime import timedelta + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, +) from objectstore_client import Client, Usecase +from objectstore_client.auth import TokenGenerator + + +def _token_generator() -> TokenGenerator: + pem = ( + Ed25519PrivateKey.generate() + .private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + .decode() + ) + return TokenGenerator(kid="test-kid", secret_key=pem) def test_imports() -> None: @@ -26,3 +45,28 @@ def test_object_url_with_base_path() -> None: session.object_url("foo/bar") == "http://127.0.0.1:8888/api/prefix/v1/objects/testing/org=12345;project=1337/foo/bar" ) + + +def test_presigned_url_brackets_ipv6_host() -> None: + client = Client("http://[::1]:8888", token=_token_generator()) + session = client.session(Usecase("testing"), org=1) + + url = session.presigned_url("GET", "foo", duration=timedelta(hours=1)) + + assert url.startswith("http://[::1]:8888/v1/objects/testing/org=1/foo?") + + +@pytest.mark.parametrize( + "duration", + [ + timedelta(0), + timedelta(seconds=-1), + timedelta(milliseconds=500), + ], +) +def test_presigned_url_rejects_nonpositive_duration(duration: timedelta) -> None: + client = Client("http://127.0.0.1:8888", token=_token_generator()) + session = client.session(Usecase("testing"), org=1) + + with pytest.raises(ValueError, match="too short"): + session.presigned_url("GET", "foo", duration=duration) From b72ed340b72e6054fd98c65043214e9eeb275d75 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 10:10:14 +0200 Subject: [PATCH 02/13] improve --- clients/python/README.md | 4 +- .../python/src/objectstore_client/client.py | 2 +- clients/python/tests/test_e2e.py | 28 +++++++----- clients/python/tests/test_smoke.py | 44 ------------------- 4 files changed, 21 insertions(+), 57 deletions(-) diff --git a/clients/python/README.md b/clients/python/README.md index 0fbb31c2..f4a65d18 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -190,7 +190,7 @@ A **pre-signed URL** is a time-limited URL that authorizes a single request on one object without the recipient needing an auth token. This is useful for handing a download link to a browser or an external service. -`Session.presigned_url` signs the URL with the session's `TokenGenerator` +`Session.presigned_object_url` signs the URL with the session's `TokenGenerator` keypair, so it requires a `TokenGenerator` (a static token string cannot sign) and raises `ValueError` otherwise. Only `GET`, `HEAD`, and `DELETE` may be pre-signed, the granted permissions are those configured server-side for the @@ -200,7 +200,7 @@ signing key, and the validity may not exceed one week. from datetime import timedelta # The recipient can fetch this with any HTTP client, no auth header needed. -url = session.presigned_url("GET", "my-key", duration=timedelta(hours=1)) +url = session.presigned_object_url("GET", "my-key", duration=timedelta(hours=1)) import urllib.request with urllib.request.urlopen(url) as resp: diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index f44a1be4..2ea60e32 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -447,7 +447,7 @@ def object_url(self, key: str) -> str: """ return self._make_url(key, full=True) - def presigned_url( + def presigned_object_url( self, method: Literal["GET", "HEAD", "DELETE"], key: str, diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index c6e84cfb..9bb375c8 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -712,7 +712,9 @@ def test_presigned_get_succeeds(server_url: str) -> None: session = _presign_session(server_url) session.put(b"presigned hello", key="presigned-get") - url = session.presigned_url("GET", "presigned-get", duration=timedelta(hours=1)) + url = session.presigned_object_url( + "GET", "presigned-get", duration=timedelta(hours=1) + ) status, body = _fetch(url) assert status == 200 @@ -723,7 +725,9 @@ def test_presigned_head_succeeds(server_url: str) -> None: session = _presign_session(server_url) session.put(b"presigned hello", key="presigned-head") - url = session.presigned_url("HEAD", "presigned-head", duration=timedelta(hours=1)) + url = session.presigned_object_url( + "HEAD", "presigned-head", duration=timedelta(hours=1) + ) status, _ = _fetch(url, method="HEAD") assert status == 204 @@ -733,14 +737,14 @@ def test_presigned_delete_succeeds_then_gone(server_url: str) -> None: session = _presign_session(server_url) session.put(b"presigned hello", key="presigned-delete") - delete_url = session.presigned_url( + delete_url = session.presigned_object_url( "DELETE", "presigned-delete", duration=timedelta(hours=1) ) status, _ = _fetch(delete_url, method="DELETE") assert status == 204 # A subsequent pre-signed GET should now 404. - get_url = session.presigned_url( + get_url = session.presigned_object_url( "GET", "presigned-delete", duration=timedelta(hours=1) ) status, _ = _fetch(get_url) @@ -752,7 +756,9 @@ def test_presigned_case_insensitive_method(server_url: str) -> None: session.put(b"lowercase method", key="presigned-lower") # Lowercase method is normalized to uppercase at runtime. - url = session.presigned_url("get", "presigned-lower", duration=timedelta(hours=1)) # type: ignore[arg-type] + url = session.presigned_object_url( + "GET", "presigned-lower", duration=timedelta(hours=1) + ) # type: ignore[arg-type] status, body = _fetch(url) assert status == 200 @@ -769,26 +775,28 @@ def test_presigned_requires_token_generator(server_url: str) -> None: session = client.session(usecase, org=42, project=1337) with pytest.raises(ValueError, match="no token generator"): - session.presigned_url("GET", "whatever", duration=timedelta(hours=1)) + session.presigned_object_url("GET", "whatever", duration=timedelta(hours=1)) def test_presigned_rejects_unsupported_method(server_url: str) -> None: session = _presign_session(server_url) with pytest.raises(ValueError, match="unsupported pre-signed method"): - session.presigned_url("PUT", "whatever", duration=timedelta(hours=1)) # type: ignore[arg-type] + session.presigned_object_url("PUT", "whatever", duration=timedelta(hours=1)) # type: ignore[arg-type] def test_presigned_rejects_duration_over_max(server_url: str) -> None: session = _presign_session(server_url) with pytest.raises(ValueError, match="exceeds the maximum"): - session.presigned_url("GET", "whatever", duration=timedelta(days=8)) + session.presigned_object_url("GET", "whatever", duration=timedelta(days=8)) def test_presigned_tampered_signature_unauthorized(server_url: str) -> None: session = _presign_session(server_url) session.put(b"presigned hello", key="presigned-tamper") - url = session.presigned_url("GET", "presigned-tamper", duration=timedelta(hours=1)) + url = session.presigned_object_url( + "GET", "presigned-tamper", duration=timedelta(hours=1) + ) # Flip the last character of the signature. last = url[-1] tampered = url[:-1] + ("A" if last != "A" else "B") @@ -827,7 +835,7 @@ def test_presigned_get_encoding_corner_cases(server_url: str, key: str) -> None: payload = f"payload for {key}".encode() session.put(payload, key=key) - url = session.presigned_url("GET", key, duration=timedelta(hours=1)) + url = session.presigned_object_url("GET", key, duration=timedelta(hours=1)) status, body = _fetch(url) assert status == 200, f"key {key!r} failed with status {status}" diff --git a/clients/python/tests/test_smoke.py b/clients/python/tests/test_smoke.py index 25a94acc..2e51ea14 100644 --- a/clients/python/tests/test_smoke.py +++ b/clients/python/tests/test_smoke.py @@ -1,23 +1,4 @@ -from datetime import timedelta - -import pytest -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from cryptography.hazmat.primitives.serialization import ( - Encoding, - NoEncryption, - PrivateFormat, -) from objectstore_client import Client, Usecase -from objectstore_client.auth import TokenGenerator - - -def _token_generator() -> TokenGenerator: - pem = ( - Ed25519PrivateKey.generate() - .private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) - .decode() - ) - return TokenGenerator(kid="test-kid", secret_key=pem) def test_imports() -> None: @@ -45,28 +26,3 @@ def test_object_url_with_base_path() -> None: session.object_url("foo/bar") == "http://127.0.0.1:8888/api/prefix/v1/objects/testing/org=12345;project=1337/foo/bar" ) - - -def test_presigned_url_brackets_ipv6_host() -> None: - client = Client("http://[::1]:8888", token=_token_generator()) - session = client.session(Usecase("testing"), org=1) - - url = session.presigned_url("GET", "foo", duration=timedelta(hours=1)) - - assert url.startswith("http://[::1]:8888/v1/objects/testing/org=1/foo?") - - -@pytest.mark.parametrize( - "duration", - [ - timedelta(0), - timedelta(seconds=-1), - timedelta(milliseconds=500), - ], -) -def test_presigned_url_rejects_nonpositive_duration(duration: timedelta) -> None: - client = Client("http://127.0.0.1:8888", token=_token_generator()) - session = client.session(Usecase("testing"), org=1) - - with pytest.raises(ValueError, match="too short"): - session.presigned_url("GET", "foo", duration=duration) From 74e73394c68730dbb587e9d425275458f87b2158 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 10:38:02 +0200 Subject: [PATCH 03/13] only GET+HEAD --- clients/python/README.md | 6 +++--- .../python/src/objectstore_client/client.py | 9 ++++----- .../python/src/objectstore_client/presign.py | 2 +- clients/python/tests/test_e2e.py | 18 ------------------ 4 files changed, 8 insertions(+), 27 deletions(-) diff --git a/clients/python/README.md b/clients/python/README.md index f4a65d18..a481aa34 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -192,9 +192,9 @@ handing a download link to a browser or an external service. `Session.presigned_object_url` signs the URL with the session's `TokenGenerator` keypair, so it requires a `TokenGenerator` (a static token string cannot sign) -and raises `ValueError` otherwise. Only `GET`, `HEAD`, and `DELETE` may be -pre-signed, the granted permissions are those configured server-side for the -signing key, and the validity may not exceed one week. +and raises `ValueError` otherwise. Only `GET` and `HEAD` may be pre-signed, +the granted permissions are those configured server-side for the signing key, +and the validity may not exceed one week. ```python from datetime import timedelta diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 2ea60e32..4cbd2ddd 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -449,7 +449,7 @@ def object_url(self, key: str) -> str: def presigned_object_url( self, - method: Literal["GET", "HEAD", "DELETE"], + method: Literal["GET", "HEAD"], key: str, duration: timedelta, ) -> str: @@ -462,10 +462,9 @@ def presigned_object_url( to any HTTP client (``urllib``, ``requests``, a browser, ...); the URL is already percent-encoded and must be transmitted verbatim. - Only ``GET``, ``HEAD`` and ``DELETE`` may be pre-signed. The permissions - granted are those configured server-side for the signing key, so a - read-only key cannot produce a working ``DELETE`` URL. ``duration`` must - not exceed one week. + Only ``GET`` and ``HEAD`` may be pre-signed. The permissions granted + are those configured server-side for the signing key. ``duration`` + must not exceed one week. Raises ``ValueError`` if no ``TokenGenerator`` is configured on this session (a static token string cannot sign), if ``method`` is not diff --git a/clients/python/src/objectstore_client/presign.py b/clients/python/src/objectstore_client/presign.py index 7fac5407..083eca48 100644 --- a/clients/python/src/objectstore_client/presign.py +++ b/clients/python/src/objectstore_client/presign.py @@ -57,7 +57,7 @@ MAX_PRESIGN_DURATION = timedelta(days=7) # HTTP methods that may be pre-signed. The server rejects all others. -SUPPORTED_METHODS = ("GET", "HEAD", "DELETE") +SUPPORTED_METHODS = ("GET", "HEAD") def encode_path(path: str) -> str: diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 9bb375c8..29aa31fd 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -733,24 +733,6 @@ def test_presigned_head_succeeds(server_url: str) -> None: assert status == 204 -def test_presigned_delete_succeeds_then_gone(server_url: str) -> None: - session = _presign_session(server_url) - session.put(b"presigned hello", key="presigned-delete") - - delete_url = session.presigned_object_url( - "DELETE", "presigned-delete", duration=timedelta(hours=1) - ) - status, _ = _fetch(delete_url, method="DELETE") - assert status == 204 - - # A subsequent pre-signed GET should now 404. - get_url = session.presigned_object_url( - "GET", "presigned-delete", duration=timedelta(hours=1) - ) - status, _ = _fetch(get_url) - assert status == 404 - - def test_presigned_case_insensitive_method(server_url: str) -> None: session = _presign_session(server_url) session.put(b"lowercase method", key="presigned-lower") From 3690bd5891af25939ae377ae84adccac9d133251 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 10:58:00 +0200 Subject: [PATCH 04/13] refactor(python): Rename TokenGenerator to SecretKey TokenGenerator was tightly coupled to JWT generation. Now that the key also signs pre-signed URLs, SecretKey better reflects its role as a general-purpose EdDSA signing identity. - TokenGenerator -> SecretKey - sign_for_scope -> token_for_scope - presign.sign() moved to SecretKey.sign_canonical() - Updated README, docstrings, tests, and exports --- clients/python/README.md | 26 ++++---- .../python/src/objectstore_client/__init__.py | 4 +- clients/python/src/objectstore_client/auth.py | 42 ++++++++---- .../python/src/objectstore_client/client.py | 31 +++++---- .../python/src/objectstore_client/presign.py | 52 ++------------- clients/python/tests/test_e2e.py | 64 +++++++++---------- clients/python/tests/test_presign.py | 24 ++++--- 7 files changed, 108 insertions(+), 135 deletions(-) diff --git a/clients/python/README.md b/clients/python/README.md index a481aa34..7fd30256 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -156,30 +156,30 @@ key = resumed.complete(new_parts + existing_parts) If your Objectstore instance enforces authorization, you must configure authentication via the `token` parameter on `Client`. It accepts either: -- A **`TokenGenerator`** — for internal services that have access to an EdDSA keypair. - The generator signs a fresh JWT for each request, scoped to the specific usecase - and scope being accessed. +- A **`SecretKey`** — for internal services that have access to an EdDSA keypair. + The key signs a fresh JWT for each request, scoped to the specific usecase + and scope being accessed, and can also sign pre-signed URLs. - A **`str`** — a pre-signed JWT, used as-is for every request. Use this for external services that receive a token from another source. ```python from objectstore_client import Client, Usecase -from objectstore_client.auth import TokenGenerator +from objectstore_client.auth import SecretKey # Option 1: Internal service with a keypair client = Client( "http://localhost:8888", - token=TokenGenerator(kid="my-service", secret_key=""), + token=SecretKey(kid="my-service", secret_key=""), ) # Option 2: External service with a pre-signed JWT -# Use TokenGenerator.sign_for_scope() to obtain a static token from an +# Use SecretKey.token_for_scope() to obtain a static token from an # internal service, then pass it to the external consumer: from objectstore_client.scope import Scope -token = TokenGenerator( +token = SecretKey( kid="my-service", secret_key="", -).sign_for_scope("my_app", Scope(org=42, project=1337)) +).token_for_scope("my_app", Scope(org=42, project=1337)) client = Client("http://localhost:8888", token=token) ``` @@ -190,11 +190,11 @@ A **pre-signed URL** is a time-limited URL that authorizes a single request on one object without the recipient needing an auth token. This is useful for handing a download link to a browser or an external service. -`Session.presigned_object_url` signs the URL with the session's `TokenGenerator` -keypair, so it requires a `TokenGenerator` (a static token string cannot sign) -and raises `ValueError` otherwise. Only `GET` and `HEAD` may be pre-signed, -the granted permissions are those configured server-side for the signing key, -and the validity may not exceed one week. +`Session.presigned_object_url` signs the URL with the session's `SecretKey`, +so it requires a `SecretKey` (a static token string cannot sign) and raises +`ValueError` otherwise. Only `GET` and `HEAD` may be pre-signed, the granted +permissions are those configured server-side for the signing key, and the +validity may not exceed one week. ```python from datetime import timedelta diff --git a/clients/python/src/objectstore_client/__init__.py b/clients/python/src/objectstore_client/__init__.py index fa26f417..a7917966 100644 --- a/clients/python/src/objectstore_client/__init__.py +++ b/clients/python/src/objectstore_client/__init__.py @@ -1,4 +1,4 @@ -from objectstore_client.auth import Permission, TokenGenerator, TokenProvider +from objectstore_client.auth import Permission, SecretKey, TokenProvider from objectstore_client.client import ( Client, GetResponse, @@ -29,7 +29,7 @@ "TimeToIdle", "TimeToLive", "TokenProvider", - "TokenGenerator", + "SecretKey", "MetricsBackend", "NoOpMetricsBackend", "parse_accept_encoding", diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 4afc2315..15d18c82 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -1,8 +1,11 @@ +import base64 from datetime import UTC, datetime, timedelta from enum import StrEnum from typing import Self import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import load_pem_private_key from objectstore_client.scope import Scope @@ -21,13 +24,13 @@ def max(cls) -> list[Self]: return list(cls.__members__.values()) -class TokenGenerator: +class SecretKey: """ - A utility to generate auth tokens for Objectstore requests. + An EdDSA keypair used to authenticate with Objectstore. - Use this for internal services that have access to an EdDSA keypair. You can - pass a ``TokenGenerator`` directly to ``Client(token=...)`` and it will sign - a fresh JWT for each request. + Can generate JWTs for request-level auth and sign canonical forms for + pre-signed URLs. Pass a ``SecretKey`` directly to ``Client(token=...)`` + and it will sign a fresh JWT for each request. """ def __init__( @@ -42,7 +45,7 @@ def __init__( self.expiry_seconds = expiry_seconds self.permissions = permissions if permissions is not None else Permission.max() - def sign_for_scope( + def token_for_scope( self, usecase: str, scope: Scope, @@ -53,14 +56,13 @@ def sign_for_scope( Sign a JWT for the passed-in usecase and scope using the configured key information, expiry, and permissions. - When ``permissions`` is ``None``, the generator's default permissions are - used. When provided, they override the defaults for this token only. + When ``permissions`` is ``None``, the default permissions are used. + When provided, they override the defaults for this token only. - When ``expiry_seconds`` is ``None``, the generator's default expiry is - used. + When ``expiry_seconds`` is ``None``, the default expiry is used. Raises ``ValueError`` if any requested permission is not granted to - this generator. + this key. The JWT is signed using EdDSA, so ``self.secret_key`` must be an EdDSA private key. ``self.kid`` is used by the Objectstore server to load the @@ -71,7 +73,7 @@ def sign_for_scope( if escalated: raise ValueError( "requested permissions not granted to this " - f"token generator: {sorted(escalated)}" + f"secret key: {sorted(escalated)}" ) headers = {"kid": self.kid} @@ -89,10 +91,22 @@ def sign_for_scope( return jwt.encode(claims, self.secret_key, algorithm="EdDSA", headers=headers) + def sign_canonical(self, canonical_form: str) -> str: + """Signs a canonical request form with the Ed25519 private key. -TokenProvider = TokenGenerator | str + Returns the base64url-encoded (no padding) signature, suitable as the + value of the ``os_sig`` query parameter. + """ + key = load_pem_private_key(self.secret_key.encode(), password=None) + if not isinstance(key, Ed25519PrivateKey): + raise ValueError("pre-signed URLs require an Ed25519 private key") + signature = key.sign(canonical_form.encode()) + return base64.urlsafe_b64encode(signature).rstrip(b"=").decode() + + +TokenProvider = SecretKey | str """Authentication provider for Objectstore requests. -Can be either a :class:`TokenGenerator` that signs a fresh JWT per request, +Can be either a :class:`SecretKey` that signs a fresh JWT per request, or a static pre-signed JWT string. """ diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 4cbd2ddd..303df045 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -13,7 +13,7 @@ from urllib3.connectionpool import HTTPConnectionPool from objectstore_client import presign, utils -from objectstore_client.auth import Permission, TokenGenerator, TokenProvider +from objectstore_client.auth import Permission, SecretKey, TokenProvider from objectstore_client.errors import raise_for_status from objectstore_client.metadata import ( HEADER_EXPIRATION, @@ -118,9 +118,9 @@ class Client: connection_kwargs: Additional keyword arguments to pass to the underlying urllib3 connection pool (e.g., custom headers, SSL settings, advanced timeouts). - token: A ``TokenGenerator`` that signs a fresh JWT for each request + token: A ``SecretKey`` that signs a fresh JWT for each request using an EdDSA keypair, or a static pre-signed JWT string used - as-is for every request. Use a ``TokenGenerator`` for internal + as-is for every request. Use a ``SecretKey`` for internal services that have access to the signing key, and a string for external services that receive a token from another source. """ @@ -238,13 +238,12 @@ def mint_token( When ``expiry_seconds`` is ``None``, the generator's default expiry is used. - Raises ``ValueError`` if no ``TokenGenerator`` is configured - or if any requested permission is not granted to the - generator. + Raises ``ValueError`` if no ``SecretKey`` is configured + or if any requested permission is not granted to the key. """ - if not isinstance(self._token, TokenGenerator): - raise ValueError("no token generator configured on this session") - return self._token.sign_for_scope( + if not isinstance(self._token, SecretKey): + raise ValueError("no secret key configured on this session") + return self._token.token_for_scope( self._usecase.name, self._scope, permissions, @@ -253,8 +252,8 @@ def mint_token( def _auth_token(self) -> str | None: """Returns a token for internal auth headers.""" - if isinstance(self._token, TokenGenerator): - return self._token.sign_for_scope(self._usecase.name, self._scope) + if isinstance(self._token, SecretKey): + return self._token.token_for_scope(self._usecase.name, self._scope) elif isinstance(self._token, str): return self._token return None @@ -466,7 +465,7 @@ def presigned_object_url( are those configured server-side for the signing key. ``duration`` must not exceed one week. - Raises ``ValueError`` if no ``TokenGenerator`` is configured on this + Raises ``ValueError`` if no ``SecretKey`` is configured on this session (a static token string cannot sign), if ``method`` is not supported, or if ``duration`` is not a positive whole number of seconds up to the one-week maximum. @@ -478,8 +477,8 @@ def presigned_object_url( f"expected one of {presign.SUPPORTED_METHODS}" ) - if not isinstance(self._token, TokenGenerator): - raise ValueError("no token generator configured on this session") + if not isinstance(self._token, SecretKey): + raise ValueError("no secret key configured on this session") if duration > presign.MAX_PRESIGN_DURATION: raise ValueError( @@ -502,10 +501,10 @@ def presigned_object_url( f"&{presign.PARAM_DURATION}={duration_secs}" ) - canonical = presign.build_canonical( + canonical = presign.build_canonical_form( normalized_method, encoded_path, encoded_query ) - signature = presign.sign_canonical(self._token.secret_key, canonical) + signature = self._token.sign_canonical(canonical) # urllib3 stores IPv6 hosts unbracketed (e.g. "::1"); bracket them so the # result is a valid absolute URL. diff --git a/clients/python/src/objectstore_client/presign.py b/clients/python/src/objectstore_client/presign.py index 083eca48..e68e7402 100644 --- a/clients/python/src/objectstore_client/presign.py +++ b/clients/python/src/objectstore_client/presign.py @@ -1,37 +1,14 @@ -"""Utilities for signing pre-signed URLs. +"""Utilities for pre-signed URLs. A pre-signed URL lets a client that owns an Ed25519 keypair hand out a time-limited URL that authorizes a specific request, without the recipient needing an auth token. -This mirrors the server-side scheme defined in ``objectstore-types/src/presign.rs``. -The signature covers a canonical form of the request: - - \\n\\n - -- normalized method: the uppercase HTTP method, with ``HEAD`` mapped to ``GET``; -- path: the request path, exactly as transmitted on the wire; -- canonical query string: every query parameter except ``os_sig``, with keys - lowercased, sorted lexicographically, joined with ``&``. - -The signature is Ed25519 over the canonical form's UTF-8 bytes, encoded as -base64url without padding, and carried in the ``os_sig`` query parameter. - -Encoding note: the server verifies the signature against the raw (still -percent-encoded) path and query it receives, without normalizing them. The -client must therefore sign the *exact bytes* its HTTP client puts on the wire. -The Python client uses urllib3, whose ``HTTPConnectionPool.urlopen`` encodes -request targets with ``urllib3.util.url._encode_target``. We reuse those same -internal helpers here so the encoding we sign matches the wire encoding by -construction; a parity test guards against upstream changes. +See ``objectstore-types/src/presign.rs`` for details on the scheme. """ -import base64 from datetime import timedelta -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from cryptography.hazmat.primitives.serialization import load_pem_private_key - # urllib3 internals that produce the on-the-wire request target. These are the # exact functions urllib3 applies in `HTTPConnectionPool.urlopen`, so signing # their output guarantees a byte-for-byte match with what the client sends. @@ -61,13 +38,7 @@ def encode_path(path: str) -> str: - """Percent-encodes a request path the same way urllib3 sends it on the wire. - - Unlike urllib3's full request-target encoder, this also encodes ``?`` and - ``#`` (which are not in the path character set), so that those characters - appearing inside an object key cannot be mistaken for the query or fragment - delimiter. - """ + """Percent-encodes a request path the same way urllib3 sends it on the wire.""" return _encode_invalid_chars(path, _PATH_CHARS) @@ -76,7 +47,7 @@ def encode_query(query: str) -> str: return _encode_invalid_chars(query, _QUERY_CHARS) -def build_canonical(method: str, encoded_path: str, encoded_query: str) -> str: +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 @@ -97,18 +68,3 @@ def build_canonical(method: str, encoded_path: str, encoded_query: str) -> str: canonical_query = "&".join(pairs) return f"{normalized_method}\n{encoded_path}\n{canonical_query}" - - -def sign_canonical(secret_key_pem: str, canonical: str) -> str: - """Signs a canonical request with an Ed25519 private key. - - ``secret_key_pem`` is a PEM-encoded Ed25519 private key (the same key a - :class:`~objectstore_client.auth.TokenGenerator` uses to sign JWTs). Returns - the base64url-encoded (no padding) signature, suitable as the value of the - ``os_sig`` query parameter. - """ - key = load_pem_private_key(secret_key_pem.encode(), password=None) - if not isinstance(key, Ed25519PrivateKey): - raise ValueError("pre-signed URLs require an Ed25519 private key") - signature = key.sign(canonical.encode()) - return base64.urlsafe_b64encode(signature).rstrip(b"=").decode() diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 29aa31fd..7d2fe518 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -16,7 +16,7 @@ import urllib3 import zstandard from objectstore_client import Client, Session, Usecase -from objectstore_client.auth import Permission, TokenGenerator +from objectstore_client.auth import Permission, SecretKey from objectstore_client.errors import RequestError from objectstore_client.metadata import TimeToLive from objectstore_client.multipart import CompletePart, MultipartCompleteError @@ -41,21 +41,21 @@ def tell(self) -> int: raise OSError("stream does not expose a stable position") -class TestTokenGenerator: - _instance: TokenGenerator | None = None +class TestSecretKey: + _instance: SecretKey | None = None @classmethod def create( cls, expiry_seconds: int = 60, permissions: list[Permission] = Permission.max() - ) -> TokenGenerator: + ) -> SecretKey: with open(TEST_EDDSA_PRIVKEY_PATH) as f: - return TokenGenerator(TEST_EDDSA_KID, f.read(), expiry_seconds, permissions) + return SecretKey(TEST_EDDSA_KID, f.read(), expiry_seconds, permissions) @classmethod - def get(cls) -> TokenGenerator: + def get(cls) -> SecretKey: if not cls._instance: with open(TEST_EDDSA_PRIVKEY_PATH) as f: - cls._instance = TokenGenerator(TEST_EDDSA_KID, f.read()) + cls._instance = SecretKey(TEST_EDDSA_KID, f.read()) return cls._instance @@ -143,7 +143,7 @@ def server_url() -> Generator[str]: def test_full_cycle(server_url: str) -> None: client = Client( server_url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -175,7 +175,7 @@ def test_full_cycle(server_url: str) -> None: def test_head(server_url: str) -> None: client = Client( server_url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -199,7 +199,7 @@ def test_head(server_url: str) -> None: def test_full_cycle_with_origin(server_url: str) -> None: client = Client( server_url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -220,7 +220,7 @@ def test_full_cycle_with_origin(server_url: str) -> None: def test_full_cycle_uncompressed(server_url: str) -> None: client = Client( server_url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -251,7 +251,7 @@ def test_full_cycle_uncompressed(server_url: str) -> None: def test_full_cycle_structured_key(server_url: str) -> None: client = Client( server_url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -269,7 +269,7 @@ def test_full_cycle_structured_key(server_url: str) -> None: def test_not_found_with_different_scope(server_url: str) -> None: client = Client( server_url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -288,8 +288,8 @@ def test_not_found_with_different_scope(server_url: str) -> None: def test_full_cycle_with_static_token(server_url: str) -> None: - token_generator = TestTokenGenerator.get() - token = token_generator.sign_for_scope("test-usecase", Scope(org=42, project=1337)) + token_generator = TestSecretKey.get() + token = token_generator.token_for_scope("test-usecase", Scope(org=42, project=1337)) client = Client(server_url, token=token) test_usecase = Usecase( @@ -313,7 +313,7 @@ def test_full_cycle_with_static_token(server_url: str) -> None: def test_fails_with_insufficient_auth_perms(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.create(permissions=[])) + client = Client(server_url, token=TestSecretKey.create(permissions=[])) test_usecase = Usecase( "test-usecase", expiration_policy=TimeToLive(timedelta(days=1)), @@ -337,7 +337,7 @@ def test_read_timeout() -> None: client = Client( url, timeout_ms=500, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -362,7 +362,7 @@ def test_connect_timeout() -> None: # Do NOT set timeout_ms to ensure we exercise default timeouts client = Client( url, - token=TestTokenGenerator.get(), + token=TestSecretKey.get(), ) test_usecase = Usecase( "test-usecase", @@ -385,7 +385,7 @@ def test_connect_timeout() -> None: def test_multipart_full_cycle_uncompressed(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -408,7 +408,7 @@ def test_multipart_full_cycle_uncompressed(server_url: str) -> None: def test_multipart_full_cycle_compressed(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -447,7 +447,7 @@ def test_multipart_full_cycle_compressed(server_url: str) -> None: def test_multipart_streaming_part_upload_uncompressed(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -477,7 +477,7 @@ def test_multipart_streaming_part_upload_uncompressed(server_url: str) -> None: def test_multipart_streaming_part_upload_compressed(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -517,7 +517,7 @@ def test_multipart_streaming_part_upload_compressed(server_url: str) -> None: def test_multipart_server_generated_key(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -537,7 +537,7 @@ def test_multipart_server_generated_key(server_url: str) -> None: def test_multipart_list_parts(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -562,7 +562,7 @@ def test_multipart_list_parts(server_url: str) -> None: def test_multipart_abort(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -576,7 +576,7 @@ def test_multipart_abort(server_url: str) -> None: def test_multipart_metadata_preserved(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -603,7 +603,7 @@ def test_multipart_metadata_preserved(server_url: str) -> None: def test_multipart_complete_with_bad_etag(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -622,7 +622,7 @@ def test_multipart_complete_with_bad_etag(server_url: str) -> None: def test_multipart_resume(server_url: str) -> None: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -655,7 +655,7 @@ def test_multipart_resume(server_url: str) -> None: def test_multipart_concurrent_part_uploads(server_url: str) -> None: from concurrent.futures import ThreadPoolExecutor - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) usecase = Usecase( "test-usecase", compression="none", @@ -697,7 +697,7 @@ def _fetch(url: str, method: str = "GET") -> tuple[int, bytes]: def _presign_session(server_url: str) -> Session: - client = Client(server_url, token=TestTokenGenerator.get()) + client = Client(server_url, token=TestSecretKey.get()) # Store uncompressed so a raw (non-decompressing) urllib GET of the # pre-signed URL returns the original bytes verbatim. usecase = Usecase( @@ -749,14 +749,14 @@ def test_presigned_case_insensitive_method(server_url: str) -> None: def test_presigned_requires_token_generator(server_url: str) -> None: # A static token string cannot sign pre-signed URLs. - token = TestTokenGenerator.get().sign_for_scope( + token = TestSecretKey.get().token_for_scope( "test-usecase", Scope(org=42, project=1337) ) client = Client(server_url, token=token) usecase = Usecase("test-usecase") session = client.session(usecase, org=42, project=1337) - with pytest.raises(ValueError, match="no token generator"): + with pytest.raises(ValueError, match="no secret key"): session.presigned_object_url("GET", "whatever", duration=timedelta(hours=1)) diff --git a/clients/python/tests/test_presign.py b/clients/python/tests/test_presign.py index c9365f5c..81310f2d 100644 --- a/clients/python/tests/test_presign.py +++ b/clients/python/tests/test_presign.py @@ -12,6 +12,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.auth import SecretKey # urllib3's real request-target encoder: the ground truth for wire encoding. from urllib3.util.url import _encode_target # type: ignore[attr-defined] @@ -33,7 +34,7 @@ def test_canonical_form_full_query() -> None: # Base case: pins path (slashes, `=`, `;` unencoded), os_sig exclusion, # key lowercasing, and query sort order. path = "/v1/objects/testing/org=17;project=42/foo/bar" - canonical = presign.build_canonical( + canonical = presign.build_canonical_form( "GET", presign.encode_path(path), presign.encode_query(SAMPLE_QUERY) ) assert canonical == ( @@ -44,14 +45,14 @@ def test_canonical_form_full_query() -> None: def test_canonical_form_empty_query() -> None: - canonical = presign.build_canonical( + canonical = presign.build_canonical_form( "GET", presign.encode_path("/v1/objects/testing/_/key"), "" ) assert canonical == "GET\n/v1/objects/testing/_/key\n" def test_canonical_form_duplicate_keys_preserved_and_sorted() -> None: - canonical = presign.build_canonical( + canonical = presign.build_canonical_form( "GET", presign.encode_path("/v1/objects/testing/_/key"), presign.encode_query("dup=b&dup=a&x=1"), @@ -62,9 +63,9 @@ def test_canonical_form_duplicate_keys_preserved_and_sorted() -> None: def test_head_is_normalized_to_get() -> None: path = presign.encode_path("/v1/objects/testing/_/key") query = presign.encode_query(SAMPLE_QUERY) - assert presign.build_canonical("HEAD", path, query) == presign.build_canonical( - "GET", path, query - ) + assert presign.build_canonical_form( + "HEAD", path, query + ) == presign.build_canonical_form("GET", path, query) # Keys that round-trip through urllib3's request-target encoder (no `?`/`#`, @@ -112,17 +113,19 @@ def test_encode_path_encodes_query_and_fragment_delimiters( def test_sign_canonical_roundtrips_with_public_key() -> None: with open(TEST_EDDSA_PRIVKEY_PATH) as f: - secret_key = f.read() + secret_key_pem = f.read() with open(TEST_EDDSA_PUBKEY_PATH, "rb") as f: public_key = load_pem_public_key(f.read()) assert isinstance(public_key, Ed25519PublicKey) - canonical = presign.build_canonical( + key = SecretKey("test_kid", secret_key_pem) + + canonical = presign.build_canonical_form( "GET", presign.encode_path("/v1/objects/testing/_/key"), presign.encode_query(SAMPLE_QUERY), ) - signature_b64 = presign.sign_canonical(secret_key, canonical) + signature_b64 = key.sign_canonical(canonical) # Decode the base64url-no-pad signature and verify with the public key. padding = "=" * (-len(signature_b64) % 4) @@ -145,5 +148,6 @@ def test_sign_canonical_rejects_non_ed25519_key() -> None: Encoding.PEM, PrivateFormat.PKCS8, NoEncryption() ).decode() + key = SecretKey("test_kid", pem) with pytest.raises(ValueError, match="Ed25519"): - presign.sign_canonical(pem, "GET\n/x\n") + key.sign_canonical("GET\n/x\n") From b8cd6d4f6d7477ed9350ffb36441fad52ab8256d Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 11:06:40 +0200 Subject: [PATCH 05/13] improve --- clients/python/src/objectstore_client/__init__.py | 15 +++++++++++++++ clients/python/src/objectstore_client/auth.py | 15 ++++++++++++++- clients/python/src/objectstore_client/client.py | 2 +- clients/python/tests/test_presign.py | 8 ++++---- 4 files changed, 34 insertions(+), 6 deletions(-) diff --git a/clients/python/src/objectstore_client/__init__.py b/clients/python/src/objectstore_client/__init__.py index a7917966..08bf6def 100644 --- a/clients/python/src/objectstore_client/__init__.py +++ b/clients/python/src/objectstore_client/__init__.py @@ -30,7 +30,22 @@ "TimeToLive", "TokenProvider", "SecretKey", + "TokenGenerator", "MetricsBackend", "NoOpMetricsBackend", "parse_accept_encoding", ] + + +def __getattr__(name: str) -> type: + import warnings + + if name == "TokenGenerator": + warnings.warn( + "TokenGenerator has been renamed to SecretKey; " + "update your imports to use SecretKey instead", + DeprecationWarning, + stacklevel=2, + ) + return SecretKey + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 15d18c82..97bedd17 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -91,7 +91,7 @@ def token_for_scope( return jwt.encode(claims, self.secret_key, algorithm="EdDSA", headers=headers) - def sign_canonical(self, canonical_form: str) -> str: + def sign_canonical_form(self, canonical_form: str) -> str: """Signs a canonical request form with the Ed25519 private key. Returns the base64url-encoded (no padding) signature, suitable as the @@ -110,3 +110,16 @@ def sign_canonical(self, canonical_form: str) -> str: Can be either a :class:`SecretKey` that signs a fresh JWT per request, or a static pre-signed JWT string. """ + + +def __getattr__(name: str) -> type: + import warnings + + if name == "TokenGenerator": + warnings.warn( + "TokenGenerator has been renamed to SecretKey", + DeprecationWarning, + stacklevel=2, + ) + return SecretKey + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 303df045..84a6878e 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -504,7 +504,7 @@ def presigned_object_url( canonical = presign.build_canonical_form( normalized_method, encoded_path, encoded_query ) - signature = self._token.sign_canonical(canonical) + signature = self._token.sign_canonical_form(canonical) # urllib3 stores IPv6 hosts unbracketed (e.g. "::1"); bracket them so the # result is a valid absolute URL. diff --git a/clients/python/tests/test_presign.py b/clients/python/tests/test_presign.py index 81310f2d..b34c63bb 100644 --- a/clients/python/tests/test_presign.py +++ b/clients/python/tests/test_presign.py @@ -111,7 +111,7 @@ def test_encode_path_encodes_query_and_fragment_delimiters( assert presign.encode_path(path) == f"/v1/objects/test/org=1/{encoded}" -def test_sign_canonical_roundtrips_with_public_key() -> None: +def test_sign_canonical_form_roundtrips_with_public_key() -> None: with open(TEST_EDDSA_PRIVKEY_PATH) as f: secret_key_pem = f.read() with open(TEST_EDDSA_PUBKEY_PATH, "rb") as f: @@ -125,7 +125,7 @@ def test_sign_canonical_roundtrips_with_public_key() -> None: presign.encode_path("/v1/objects/testing/_/key"), presign.encode_query(SAMPLE_QUERY), ) - signature_b64 = key.sign_canonical(canonical) + signature_b64 = key.sign_canonical_form(canonical) # Decode the base64url-no-pad signature and verify with the public key. padding = "=" * (-len(signature_b64) % 4) @@ -134,7 +134,7 @@ def test_sign_canonical_roundtrips_with_public_key() -> None: public_key.verify(signature, canonical.encode()) # raises on mismatch -def test_sign_canonical_rejects_non_ed25519_key() -> None: +def test_sign_canonical_form_rejects_non_ed25519_key() -> None: # An RSA key is a valid PEM private key but not Ed25519. from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import ( @@ -150,4 +150,4 @@ def test_sign_canonical_rejects_non_ed25519_key() -> None: key = SecretKey("test_kid", pem) with pytest.raises(ValueError, match="Ed25519"): - key.sign_canonical("GET\n/x\n") + key.sign_canonical_form("GET\n/x\n") From 78fc8fc90469936739ab7930ef54f98e5c1ec849 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 12:15:29 +0200 Subject: [PATCH 06/13] improve --- clients/python/tests/test_presign.py | 82 +--------------------------- 1 file changed, 2 insertions(+), 80 deletions(-) diff --git a/clients/python/tests/test_presign.py b/clients/python/tests/test_presign.py index b34c63bb..0029c44f 100644 --- a/clients/python/tests/test_presign.py +++ b/clients/python/tests/test_presign.py @@ -1,27 +1,18 @@ -"""Unit tests for the pre-signed URL signing utilities. - -These pin the canonical form against the Rust reference vectors -(``objectstore-types/src/presign.rs``) and, crucially, assert that our path/query -encoding matches byte-for-byte what urllib3 puts on the wire. -""" +"""Unit tests for the pre-signed URL signing utilities.""" import base64 import os -import pytest 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.auth import SecretKey -# urllib3's real request-target encoder: the ground truth for wire encoding. -from urllib3.util.url import _encode_target # type: ignore[attr-defined] - TEST_EDDSA_PRIVKEY_PATH = os.path.join(os.path.dirname(__file__), "ed25519.private.pem") TEST_EDDSA_PUBKEY_PATH = os.path.join(os.path.dirname(__file__), "ed25519.public.pem") # Raw query string as it would appear on the wire: unsorted, includes the -# os_sig that must be excluded. Mirrors `sample_query()` in presign.rs. +# os_sig that must be excluded. SAMPLE_QUERY = ( "os_timestamp=1985-04-12T23:20:50.52Z" "&os_kid=relay" @@ -44,13 +35,6 @@ def test_canonical_form_full_query() -> None: ) -def test_canonical_form_empty_query() -> None: - canonical = presign.build_canonical_form( - "GET", presign.encode_path("/v1/objects/testing/_/key"), "" - ) - assert canonical == "GET\n/v1/objects/testing/_/key\n" - - def test_canonical_form_duplicate_keys_preserved_and_sorted() -> None: canonical = presign.build_canonical_form( "GET", @@ -68,49 +52,6 @@ def test_head_is_normalized_to_get() -> None: ) == presign.build_canonical_form("GET", path, query) -# Keys that round-trip through urllib3's request-target encoder (no `?`/`#`, -# which urllib3 would treat as the query/fragment delimiter). -WIRE_SAFE_KEYS = [ - "simple", - "hello world", - "café", - "emoji-😀-key", - "plus+plus", - "sub!$&'()*+,;=delims", - "tilde~and.dot", - "100%done", - "already%20encoded", - "nested/a/b/c", - "trailing space ", - "quote'apostrophe", - "at@sign", - "colon:and/slash", -] - - -@pytest.mark.parametrize("key", WIRE_SAFE_KEYS) -def test_encode_path_matches_urllib3_wire_encoding(key: str) -> None: - # Our signed path encoding must equal exactly what urllib3 sends on the wire. - path = f"/v1/objects/test/org=1/{key}" - assert presign.encode_path(path) == _encode_target(path) - - -@pytest.mark.parametrize( - ("key", "encoded"), - [ - ("has?question", "has%3Fquestion"), - ("has#hash", "has%23hash"), - ], -) -def test_encode_path_encodes_query_and_fragment_delimiters( - key: str, encoded: str -) -> None: - # Unlike urllib3's target encoder (which would split on `?`/`#`), we encode - # them so they can appear literally inside an object key. - path = f"/v1/objects/test/org=1/{key}" - assert presign.encode_path(path) == f"/v1/objects/test/org=1/{encoded}" - - def test_sign_canonical_form_roundtrips_with_public_key() -> None: with open(TEST_EDDSA_PRIVKEY_PATH) as f: secret_key_pem = f.read() @@ -132,22 +73,3 @@ def test_sign_canonical_form_roundtrips_with_public_key() -> None: signature = base64.urlsafe_b64decode(signature_b64 + padding) assert len(signature) == 64 public_key.verify(signature, canonical.encode()) # raises on mismatch - - -def test_sign_canonical_form_rejects_non_ed25519_key() -> None: - # An RSA key is a valid PEM private key but not Ed25519. - from cryptography.hazmat.primitives.asymmetric import rsa - from cryptography.hazmat.primitives.serialization import ( - Encoding, - NoEncryption, - PrivateFormat, - ) - - rsa_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) - pem = rsa_key.private_bytes( - Encoding.PEM, PrivateFormat.PKCS8, NoEncryption() - ).decode() - - key = SecretKey("test_kid", pem) - with pytest.raises(ValueError, match="Ed25519"): - key.sign_canonical_form("GET\n/x\n") From 1f3867bcc6550c41652aa1e83e3b85ca4388cbbd Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 12:18:53 +0200 Subject: [PATCH 07/13] improve --- clients/python/src/objectstore_client/auth.py | 2 +- clients/python/src/objectstore_client/client.py | 2 +- clients/python/tests/test_presign.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 97bedd17..93fa3cb0 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -91,7 +91,7 @@ def token_for_scope( return jwt.encode(claims, self.secret_key, algorithm="EdDSA", headers=headers) - def sign_canonical_form(self, canonical_form: str) -> str: + def signature_for_canonical_form(self, canonical_form: str) -> str: """Signs a canonical request form with the Ed25519 private key. Returns the base64url-encoded (no padding) signature, suitable as the diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 84a6878e..8b2ac393 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -504,7 +504,7 @@ def presigned_object_url( canonical = presign.build_canonical_form( normalized_method, encoded_path, encoded_query ) - signature = self._token.sign_canonical_form(canonical) + signature = self._token.signature_for_canonical_form(canonical) # urllib3 stores IPv6 hosts unbracketed (e.g. "::1"); bracket them so the # result is a valid absolute URL. diff --git a/clients/python/tests/test_presign.py b/clients/python/tests/test_presign.py index 0029c44f..a9964580 100644 --- a/clients/python/tests/test_presign.py +++ b/clients/python/tests/test_presign.py @@ -66,7 +66,7 @@ def test_sign_canonical_form_roundtrips_with_public_key() -> None: presign.encode_path("/v1/objects/testing/_/key"), presign.encode_query(SAMPLE_QUERY), ) - signature_b64 = key.sign_canonical_form(canonical) + signature_b64 = key.signature_for_canonical_form(canonical) # Decode the base64url-no-pad signature and verify with the public key. padding = "=" * (-len(signature_b64) % 4) From b8861a580f57b13ff47d05ab3ecb59cf102836ae Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 12:21:51 +0200 Subject: [PATCH 08/13] improve --- clients/python/src/objectstore_client/__init__.py | 15 --------------- clients/python/src/objectstore_client/auth.py | 13 ------------- 2 files changed, 28 deletions(-) diff --git a/clients/python/src/objectstore_client/__init__.py b/clients/python/src/objectstore_client/__init__.py index 08bf6def..a7917966 100644 --- a/clients/python/src/objectstore_client/__init__.py +++ b/clients/python/src/objectstore_client/__init__.py @@ -30,22 +30,7 @@ "TimeToLive", "TokenProvider", "SecretKey", - "TokenGenerator", "MetricsBackend", "NoOpMetricsBackend", "parse_accept_encoding", ] - - -def __getattr__(name: str) -> type: - import warnings - - if name == "TokenGenerator": - warnings.warn( - "TokenGenerator has been renamed to SecretKey; " - "update your imports to use SecretKey instead", - DeprecationWarning, - stacklevel=2, - ) - return SecretKey - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 93fa3cb0..7d9d302a 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -110,16 +110,3 @@ def signature_for_canonical_form(self, canonical_form: str) -> str: Can be either a :class:`SecretKey` that signs a fresh JWT per request, or a static pre-signed JWT string. """ - - -def __getattr__(name: str) -> type: - import warnings - - if name == "TokenGenerator": - warnings.warn( - "TokenGenerator has been renamed to SecretKey", - DeprecationWarning, - stacklevel=2, - ) - return SecretKey - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") From 83f190e362808b24cc92de579dc26b851213256b Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 12:35:16 +0200 Subject: [PATCH 09/13] improve --- clients/python/src/objectstore_client/client.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 8b2ac393..14fef1ed 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -470,8 +470,7 @@ def presigned_object_url( supported, or if ``duration`` is not a positive whole number of seconds up to the one-week maximum. """ - normalized_method = method.upper() - if normalized_method not in presign.SUPPORTED_METHODS: + if method not in presign.SUPPORTED_METHODS: raise ValueError( f"unsupported pre-signed method {method!r}, " f"expected one of {presign.SUPPORTED_METHODS}" @@ -485,8 +484,6 @@ def presigned_object_url( f"duration {duration} exceeds the maximum of " f"{presign.MAX_PRESIGN_DURATION}" ) - # The validity is transmitted as whole seconds, so anything that - # truncates to zero (or less) would yield an already-expired URL. duration_secs = int(duration.total_seconds()) if duration_secs < 1: raise ValueError( @@ -501,9 +498,7 @@ def presigned_object_url( f"&{presign.PARAM_DURATION}={duration_secs}" ) - canonical = presign.build_canonical_form( - normalized_method, encoded_path, encoded_query - ) + canonical = presign.build_canonical_form(method, encoded_path, encoded_query) signature = self._token.signature_for_canonical_form(canonical) # urllib3 stores IPv6 hosts unbracketed (e.g. "::1"); bracket them so the From 10d95e9100986b21fe8d0bb4a444a406abc50f71 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 13:07:07 +0200 Subject: [PATCH 10/13] improve --- .../python/src/objectstore_client/presign.py | 41 +++++++++++++------ clients/python/tests/test_e2e.py | 10 ++++- 2 files changed, 36 insertions(+), 15 deletions(-) diff --git a/clients/python/src/objectstore_client/presign.py b/clients/python/src/objectstore_client/presign.py index e68e7402..b97a8a08 100644 --- a/clients/python/src/objectstore_client/presign.py +++ b/clients/python/src/objectstore_client/presign.py @@ -8,15 +8,22 @@ """ from datetime import timedelta - -# urllib3 internals that produce the on-the-wire request target. These are the -# exact functions urllib3 applies in `HTTPConnectionPool.urlopen`, so signing -# their output guarantees a byte-for-byte match with what the client sends. -from urllib3.util.url import ( # type: ignore[attr-defined] - _PATH_CHARS, - _QUERY_CHARS, - _encode_invalid_chars, -) +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" @@ -38,13 +45,21 @@ def encode_path(path: str) -> str: - """Percent-encodes a request path the same way urllib3 sends it on the wire.""" - return _encode_invalid_chars(path, _PATH_CHARS) + """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 the same way urllib3 sends it on the wire.""" - return _encode_invalid_chars(query, _QUERY_CHARS) + """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: diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 7d2fe518..c5e79261 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -791,6 +791,12 @@ def test_presigned_tampered_signature_unauthorized(server_url: str) -> None: # 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. ENCODING_CORNER_CASE_KEYS = [ "plain-key", "with space", @@ -799,8 +805,8 @@ def test_presigned_tampered_signature_unauthorized(server_url: str) -> None: "plus+sign", "sub!$'()*+,=delims", "tilde~dot.key", - "100%literal-percent", - "looks%20encoded", + "100%literal-percent", # `%li` isn't a valid escape, so both escape the `%` + # "looks%20encoded", # diverges: quote -> %2520, urllib3 put -> %20 "nested/path/segments", "quote'apostrophe", "at@sign", From f1a31b528da8aa3f0f0fae9c94d6f7ef888842ac Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Thu, 9 Jul 2026 13:47:29 +0200 Subject: [PATCH 11/13] improve --- clients/python/src/objectstore_client/client.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 14fef1ed..cdb02996 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -1,5 +1,6 @@ from __future__ import annotations +import math from collections.abc import Mapping, Sequence from dataclasses import asdict, dataclass from datetime import UTC, datetime, timedelta @@ -467,8 +468,7 @@ def presigned_object_url( Raises ``ValueError`` if no ``SecretKey`` is configured on this session (a static token string cannot sign), if ``method`` is not - supported, or if ``duration`` is not a positive whole number of seconds - up to the one-week maximum. + supported, or if ``duration`` is above the one-week maximum. """ if method not in presign.SUPPORTED_METHODS: raise ValueError( @@ -484,11 +484,7 @@ def presigned_object_url( f"duration {duration} exceeds the maximum of " f"{presign.MAX_PRESIGN_DURATION}" ) - duration_secs = int(duration.total_seconds()) - if duration_secs < 1: - raise ValueError( - f"duration {duration} is too short; must be at least one second" - ) + duration_secs = math.ceil(duration.total_seconds()) encoded_path = presign.encode_path(self._make_url(key)) timestamp = datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ") From cc111d767188093f9c5c7c65048a5bb65bf7eb44 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Fri, 10 Jul 2026 10:23:28 +0200 Subject: [PATCH 12/13] address commnets --- clients/python/README.md | 14 +++++++++---- .../python/src/objectstore_client/client.py | 21 +++++++++---------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/clients/python/README.md b/clients/python/README.md index 7fd30256..5fac3481 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -188,12 +188,18 @@ client = Client("http://localhost:8888", token=token) A **pre-signed URL** is a time-limited URL that authorizes a single request on one object without the recipient needing an auth token. This is useful for -handing a download link to a browser or an external service. +handing a download link to a browser or an external service, or for returning +an HTTP redirect so that clients can download objects directly from +Objectstore. + +Pre-signed URLS currently only support `GET` and `HEAD` (a pre-signed URL for +`GET` authorizes `HEAD` too, and viceversa), so for uploads you should use +scoped JWTs, as described above. `Session.presigned_object_url` signs the URL with the session's `SecretKey`, -so it requires a `SecretKey` (a static token string cannot sign) and raises -`ValueError` otherwise. Only `GET` and `HEAD` may be pre-signed, the granted -permissions are those configured server-side for the signing key, and the +so it requires a `SecretKey` and raises `ValueError` otherwise. +Only `GET` and `HEAD` may be pre-signed, the granted permissions are those +configured server-side for the signing key, and the validity may not exceed one week. ```python diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index cdb02996..06598045 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -451,24 +451,23 @@ def presigned_object_url( self, method: Literal["GET", "HEAD"], key: str, - duration: timedelta, + duration: timedelta = timedelta(hours=1), ) -> str: """ Generates a pre-signed URL authorizing a single ``method`` request on the object with the given ``key``, valid for ``duration``. - The returned URL carries an Ed25519 signature in its query string, so the - recipient can perform the request without an auth token. It can be handed - to any HTTP client (``urllib``, ``requests``, a browser, ...); the URL is - already percent-encoded and must be transmitted verbatim. + Raises ``ValueError`` if no ``SecretKey`` is configured on this + session's client, if ``method`` is not supported, or if ``duration`` + is above the one-week maximum. - Only ``GET`` and ``HEAD`` may be pre-signed. The permissions granted - are those configured server-side for the signing key. ``duration`` - must not exceed one week. + The returned URL carries a signature that allows the recipient to perform + a request without an auth token. It can be handed to any HTTP client; + the URL is already percent-encoded, and must be transmitted verbatim. - Raises ``ValueError`` if no ``SecretKey`` is configured on this - session (a static token string cannot sign), if ``method`` is not - supported, or if ``duration`` is above the one-week maximum. + Note that `HEAD` and `GET` are considered equivalent from the point of view + of signatures, meaning that a signature for `GET` can also be used for + `HEAD`, and viceversa. """ if method not in presign.SUPPORTED_METHODS: raise ValueError( From bee92254578125082dbf4d3e93df1001d3f116c4 Mon Sep 17 00:00:00 2001 From: lcian <17258265+lcian@users.noreply.github.com> Date: Fri, 10 Jul 2026 10:31:02 +0200 Subject: [PATCH 13/13] keep legacy aliases --- clients/python/src/objectstore_client/__init__.py | 3 ++- clients/python/src/objectstore_client/auth.py | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/clients/python/src/objectstore_client/__init__.py b/clients/python/src/objectstore_client/__init__.py index a7917966..e8d97f77 100644 --- a/clients/python/src/objectstore_client/__init__.py +++ b/clients/python/src/objectstore_client/__init__.py @@ -1,4 +1,4 @@ -from objectstore_client.auth import Permission, SecretKey, TokenProvider +from objectstore_client.auth import Permission, SecretKey, TokenGenerator, TokenProvider from objectstore_client.client import ( Client, GetResponse, @@ -30,6 +30,7 @@ "TimeToLive", "TokenProvider", "SecretKey", + "TokenGenerator", "MetricsBackend", "NoOpMetricsBackend", "parse_accept_encoding", diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 7d9d302a..99376ac4 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -91,6 +91,9 @@ def token_for_scope( return jwt.encode(claims, self.secret_key, algorithm="EdDSA", headers=headers) + # Deprecated: use token_for_scope() instead. + sign_for_scope = token_for_scope + def signature_for_canonical_form(self, canonical_form: str) -> str: """Signs a canonical request form with the Ed25519 private key. @@ -110,3 +113,6 @@ def signature_for_canonical_form(self, canonical_form: str) -> str: Can be either a :class:`SecretKey` that signs a fresh JWT per request, or a static pre-signed JWT string. """ + +# Deprecated: use SecretKey instead. +TokenGenerator = SecretKey