diff --git a/clients/python/README.md b/clients/python/README.md index ba0bed88..5fac3481 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -156,34 +156,63 @@ 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) ``` +### 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, 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` 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 + +# The recipient can fetch this with any HTTP client, no auth header needed. +url = session.presigned_object_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/__init__.py b/clients/python/src/objectstore_client/__init__.py index fa26f417..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, TokenGenerator, TokenProvider +from objectstore_client.auth import Permission, SecretKey, TokenGenerator, TokenProvider from objectstore_client.client import ( Client, GetResponse, @@ -29,6 +29,7 @@ "TimeToIdle", "TimeToLive", "TokenProvider", + "SecretKey", "TokenGenerator", "MetricsBackend", "NoOpMetricsBackend", diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 4afc2315..99376ac4 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,28 @@ def sign_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 -TokenProvider = TokenGenerator | 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 + 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. """ + +# Deprecated: use SecretKey instead. +TokenGenerator = SecretKey diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 0779529f..06598045 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -1,7 +1,9 @@ from __future__ import annotations +import math 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,8 +13,8 @@ import zstandard from urllib3.connectionpool import HTTPConnectionPool -from objectstore_client import utils -from objectstore_client.auth import Permission, TokenGenerator, TokenProvider +from objectstore_client import presign, utils +from objectstore_client.auth import Permission, SecretKey, TokenProvider from objectstore_client.errors import raise_for_status from objectstore_client.metadata import ( HEADER_EXPIRATION, @@ -117,9 +119,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. """ @@ -237,13 +239,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, @@ -252,8 +253,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 @@ -446,6 +447,66 @@ def object_url(self, key: str) -> str: """ return self._make_url(key, full=True) + def presigned_object_url( + self, + method: Literal["GET", "HEAD"], + key: str, + 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``. + + 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. + + 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. + + 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( + f"unsupported pre-signed method {method!r}, " + f"expected one of {presign.SUPPORTED_METHODS}" + ) + + if not isinstance(self._token, SecretKey): + raise ValueError("no secret key configured on this session") + + if duration > presign.MAX_PRESIGN_DURATION: + raise ValueError( + f"duration {duration} exceeds the maximum of " + f"{presign.MAX_PRESIGN_DURATION}" + ) + 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") + 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_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 + # 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..b97a8a08 --- /dev/null +++ b/clients/python/src/objectstore_client/presign.py @@ -0,0 +1,85 @@ +"""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. + +See ``objectstore-types/src/presign.rs`` for details on the scheme. +""" + +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" + +# 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") + + +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`). + """ + 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}" diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 359be23d..c5e79261 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,8 +15,8 @@ import pytest import urllib3 import zstandard -from objectstore_client import Client, Usecase -from objectstore_client.auth import Permission, TokenGenerator +from objectstore_client import Client, Session, Usecase +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 @@ -39,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 @@ -141,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", @@ -173,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", @@ -197,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", @@ -218,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", @@ -249,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", @@ -267,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", @@ -286,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( @@ -311,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)), @@ -335,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", @@ -360,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", @@ -383,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", @@ -406,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", @@ -445,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", @@ -475,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", @@ -515,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", @@ -535,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", @@ -560,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", @@ -574,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", @@ -601,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", @@ -620,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", @@ -653,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", @@ -678,3 +680,151 @@ 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=TestSecretKey.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_object_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_object_url( + "HEAD", "presigned-head", duration=timedelta(hours=1) + ) + status, _ = _fetch(url, method="HEAD") + + assert status == 204 + + +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_object_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 = 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 secret key"): + 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_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_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_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") + + 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. +# +# 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", + "café-unicode", + "emoji-😀", + "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 + "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_object_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..a9964580 --- /dev/null +++ b/clients/python/tests/test_presign.py @@ -0,0 +1,75 @@ +"""Unit tests for the pre-signed URL signing utilities.""" + +import base64 +import os + +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 + +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. +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_form( + "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_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"), + ) + 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_form( + "HEAD", path, query + ) == presign.build_canonical_form("GET", path, query) + + +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: + public_key = load_pem_public_key(f.read()) + assert isinstance(public_key, Ed25519PublicKey) + + 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 = key.signature_for_canonical_form(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