diff --git a/clients/python/README.md b/clients/python/README.md index 7cd45433..e21cf5fd 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -121,30 +121,31 @@ session.put(b"payload", metadata={"source": "upload-service"}) If your Objectstore instance enforces authorization, you must configure authentication via the `token` parameter on `Client`. It accepts either: -- 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 **`TokenGenerator`** — for internal services that have access to an EdDSA keypair. + It wraps a `SecretKey` and signs a fresh JWT for each request, scoped to the + specific usecase and scope being accessed. Its key can also sign pre-signed URLs. + The generator's `expiry_seconds` and `permissions` are the defaults for every + token it signs; per-token overrides can only narrow them. - 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 SecretKey +from objectstore_client.auth import SecretKey, TokenGenerator + +key = SecretKey(kid="my-service", secret_key="") # Option 1: Internal service with a keypair -client = Client( - "http://localhost:8888", - token=SecretKey(kid="my-service", secret_key=""), -) +client = Client("http://localhost:8888", token=TokenGenerator(key)) # Option 2: External service with a pre-signed JWT -# Use SecretKey.token_for_scope() to obtain a static token from an +# Use TokenGenerator.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 = SecretKey( - kid="my-service", secret_key="", -).token_for_scope("my_app", Scope(org=42, project=1337)) +token = TokenGenerator(key, expiry_seconds=300).token_for_scope( + "my_app", Scope(org=42, project=1337) +) client = Client("http://localhost:8888", token=token) ``` @@ -154,7 +155,7 @@ client = Client("http://localhost:8888", token=token) `Session.object_url` returns a GET URL for an object. By default the URL carries no auth, so the recipient needs their own key to generate a token for it. Pass `token_validity` to embed a read-only token in the URL instead, valid for the -given duration (requires `SecretKey` authentication - see above section). +given duration (requires `TokenGenerator` authentication - see above section). ```python from datetime import timedelta @@ -177,8 +178,8 @@ 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. +`Session.presigned_object_url` signs the URL with the `SecretKey` of the session's +`TokenGenerator`, so it requires a `TokenGenerator` 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. diff --git a/clients/python/src/objectstore_client/__init__.py b/clients/python/src/objectstore_client/__init__.py index d5c9955f..8cd93138 100644 --- a/clients/python/src/objectstore_client/__init__.py +++ b/clients/python/src/objectstore_client/__init__.py @@ -1,4 +1,10 @@ -from objectstore_client.auth import Permission, SecretKey, TokenGenerator, TokenProvider +from objectstore_client.auth import ( + Permission, + SecretKey, + Token, + TokenGenerator, + TokenProvider, +) from objectstore_client.client import ( Client, GetResponse, @@ -35,6 +41,7 @@ "TimeToIdle", "TimeToLive", "TokenProvider", + "Token", "SecretKey", "TokenGenerator", "MetricsBackend", diff --git a/clients/python/src/objectstore_client/auth.py b/clients/python/src/objectstore_client/auth.py index 99376ac4..14d18bc9 100644 --- a/clients/python/src/objectstore_client/auth.py +++ b/clients/python/src/objectstore_client/auth.py @@ -28,20 +28,51 @@ class SecretKey: """ An EdDSA keypair used to authenticate with Objectstore. - 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. + ``kid`` is the key ID that the Objectstore server uses to load the + corresponding public key from its configuration, and ``secret_key`` is the + PEM-encoded EdDSA private key. + + A ``SecretKey`` only identifies the signer. To authenticate requests, wrap + it in a :class:`TokenGenerator`, which adds the expiry and permissions for + the tokens it signs. + """ + + def __init__(self, kid: str, secret_key: str): + self.kid = kid + self.secret_key = secret_key + + 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() + + +class TokenGenerator: + """ + Generates auth tokens for Objectstore requests, signed with a :class:`SecretKey`. + + ``expiry_seconds`` and ``permissions`` are the defaults for every token this + generator signs. Per-token overrides may shorten the expiry or narrow the + permissions, but cannot grant permissions beyond ``permissions``. + + Pass a ``TokenGenerator`` directly to ``Client(token=...)`` and it will sign a + fresh JWT for each request. Its key is also used to sign pre-signed URLs. """ def __init__( self, - kid: str, - secret_key: str, + key: SecretKey, expiry_seconds: int = 60, permissions: list[Permission] | None = None, ): - self.kid = kid - self.secret_key = secret_key + self.key = key self.expiry_seconds = expiry_seconds self.permissions = permissions if permissions is not None else Permission.max() @@ -53,8 +84,8 @@ def token_for_scope( expiry_seconds: int | None = None, ) -> str: """ - Sign a JWT for the passed-in usecase and scope using the configured key - information, expiry, and permissions. + Sign a JWT for the passed-in usecase and scope using this generator's + key, expiry, and permissions. When ``permissions`` is ``None``, the default permissions are used. When provided, they override the defaults for this token only. @@ -62,21 +93,17 @@ def token_for_scope( When ``expiry_seconds`` is ``None``, the default expiry is used. Raises ``ValueError`` if any requested permission is not granted to - 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 - corresponding public key from its configuration. + this generator. """ if permissions is not None: escalated = set(permissions) - set(self.permissions) if escalated: raise ValueError( "requested permissions not granted to this " - f"secret key: {sorted(escalated)}" + f"token generator: {sorted(escalated)}" ) - headers = {"kid": self.kid} + headers = {"kid": self.key.kid} expiry = expiry_seconds if expiry_seconds is not None else self.expiry_seconds claims = { "res": { @@ -89,30 +116,17 @@ def token_for_scope( "exp": datetime.now(tz=UTC) + timedelta(seconds=expiry), } - return jwt.encode(claims, self.secret_key, algorithm="EdDSA", headers=headers) + return jwt.encode( + claims, self.key.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. +Token = str +"""A static, pre-signed JWT used as-is for every request.""" - 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 +TokenProvider = TokenGenerator | Token """Authentication provider for Objectstore requests. -Can be either a :class:`SecretKey` that signs a fresh JWT per request, -or a static pre-signed JWT string. +Can be either a :class:`TokenGenerator` that signs a fresh JWT per request, +or a static pre-signed :data:`Token`. """ - -# 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 f659ce5f..4d1819a3 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -16,7 +16,7 @@ from urllib3.connectionpool import HTTPConnectionPool from objectstore_client import _resumable, presign, utils -from objectstore_client.auth import Permission, SecretKey, TokenProvider +from objectstore_client.auth import Permission, TokenGenerator, TokenProvider from objectstore_client.errors import ( ExpiryExtensionRejected, ObjectNotFound, @@ -171,9 +171,9 @@ class Client: timeouts). By default, requests carry a ``User-Agent`` header of ``objectstore-client/{version}``; pass a ``headers`` mapping with a ``User-Agent`` key here to override it. - token: A ``SecretKey`` that signs a fresh JWT for each request + token: A ``TokenGenerator`` 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 ``SecretKey`` for internal + as-is for every request. Use a ``TokenGenerator`` for internal services that have access to the signing key, and a string for external services that receive a token from another source. spool_dir: Directory that temporary files are created in when preparing @@ -297,11 +297,11 @@ def mint_token( When ``expiry_seconds`` is ``None``, the generator's default expiry is used. - Raises ``ValueError`` if no ``SecretKey`` is configured - or if any requested permission is not granted to the key. + Raises ``ValueError`` if no ``TokenGenerator`` is configured + or if any requested permission is not granted to the generator. """ - if not isinstance(self._token, SecretKey): - raise ValueError("no secret key configured on this session") + if not isinstance(self._token, TokenGenerator): + raise ValueError("no token generator configured on this session") resolved_expiry = ( expiry_seconds if expiry_seconds is not None else self._token.expiry_seconds @@ -328,7 +328,7 @@ def mint_token( def _auth_token(self) -> str | None: """Returns a token for internal auth headers.""" - if isinstance(self._token, SecretKey): + if isinstance(self._token, TokenGenerator): return self._token.token_for_scope(self._usecase.name, self._scope) elif isinstance(self._token, str): return self._token @@ -683,7 +683,7 @@ def object_url( Use :meth:`presigned_object_url` to bind the options to a signature. Raises ``ValueError`` if ``token_validity`` is provided but no - ``SecretKey`` is configured on this session, or if disposition is invalid. + ``TokenGenerator`` is configured on this session, or if disposition is invalid. """ url = self._make_url(key, full=True) if response_content_disposition is not None: @@ -715,7 +715,7 @@ def presigned_object_url( Experimental: pre-signed URLs are an experimental feature and this API may change in a future release. - Raises ``ValueError`` if no ``SecretKey`` is configured on this + Raises ``ValueError`` if no ``TokenGenerator`` is configured on this session's client, if ``method`` is not supported, or if ``duration`` is above the one-week maximum, or if disposition is invalid. @@ -738,8 +738,8 @@ def presigned_object_url( f"expected one of {presign.SUPPORTED_METHODS}" ) - if not isinstance(self._token, SecretKey): - raise ValueError("no secret key configured on this session") + if not isinstance(self._token, TokenGenerator): + raise ValueError("no token generator configured on this session") if duration > presign.MAX_PRESIGN_DURATION: raise ValueError( @@ -760,7 +760,7 @@ def presigned_object_url( encoded_path = self._make_url(key) timestamp = datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ") encoded_query = utils.encode_query( - f"{presign.PARAM_KID}={self._token.kid}" + f"{presign.PARAM_KID}={self._token.key.kid}" f"&{presign.PARAM_TIMESTAMP}={timestamp}" f"&{presign.PARAM_DURATION}={duration_secs}" ) @@ -773,7 +773,7 @@ def presigned_object_url( canonical = presign.build_canonical_form( method, encoded_path, encoded_query ) - signature = self._token.signature_for_canonical_form(canonical) + signature = self._token.key.signature_for_canonical_form(canonical) return ( f"{self._base_url()}" diff --git a/clients/python/tests/test_auth.py b/clients/python/tests/test_auth.py new file mode 100644 index 00000000..a4682e4d --- /dev/null +++ b/clients/python/tests/test_auth.py @@ -0,0 +1,56 @@ +import base64 +import os + +import jwt +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, utils +from objectstore_client.auth import Permission, SecretKey, TokenGenerator +from objectstore_client.scope import Scope + +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") + + +def _key() -> SecretKey: + with open(TEST_EDDSA_PRIVKEY_PATH) as f: + return SecretKey("test_kid", f.read()) + + +def test_token_generator_signs_with_key_and_defaults() -> None: + generator = TokenGenerator(_key(), permissions=[Permission.OBJECT_READ]) + token = generator.token_for_scope("testing", Scope(org=1)) + + assert jwt.get_unverified_header(token)["kid"] == "test_kid" + with open(TEST_EDDSA_PUBKEY_PATH) as f: + claims = jwt.decode(token, f.read(), algorithms=["EdDSA"]) + assert claims["res"]["os:usecase"] == "testing" + assert claims["permissions"] == [Permission.OBJECT_READ] + + +def test_token_generator_rejects_escalated_permissions() -> None: + generator = TokenGenerator(_key(), permissions=[Permission.OBJECT_READ]) + with pytest.raises(ValueError, match="not granted to this token generator"): + generator.token_for_scope( + "testing", Scope(org=1), permissions=[Permission.OBJECT_WRITE] + ) + + +def test_sign_canonical_form_roundtrips_with_public_key() -> None: + 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_form( + "GET", + utils.encode_path("/v1/objects/testing/_/key"), + utils.encode_query("os_kid=test_kid&os_duration=3600"), + ) + 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 diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 3e82abda..81cc9c23 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -31,7 +31,7 @@ UploadIncomplete, UploadOffsetMismatch, ) -from objectstore_client.auth import Permission, SecretKey +from objectstore_client.auth import Permission, SecretKey, TokenGenerator from objectstore_client.errors import RequestError from objectstore_client.metadata import TimeToLive from objectstore_client.scope import Scope @@ -58,21 +58,21 @@ def tell(self) -> int: raise OSError("stream does not expose a stable position") -class TestSecretKey: - _instance: SecretKey | None = None +class TestTokenGenerator: + _instance: TokenGenerator | None = None @classmethod def create( cls, expiry_seconds: int = 60, permissions: list[Permission] = Permission.max() - ) -> SecretKey: + ) -> TokenGenerator: with open(TEST_EDDSA_PRIVKEY_PATH) as f: - return SecretKey(TEST_EDDSA_KID, f.read(), expiry_seconds, permissions) + key = SecretKey(TEST_EDDSA_KID, f.read()) + return TokenGenerator(key, expiry_seconds, permissions) @classmethod - def get(cls) -> SecretKey: + def get(cls) -> TokenGenerator: if not cls._instance: - with open(TEST_EDDSA_PRIVKEY_PATH) as f: - cls._instance = SecretKey(TEST_EDDSA_KID, f.read()) + cls._instance = cls.create() return cls._instance @@ -160,7 +160,7 @@ def server_url() -> Generator[str]: def test_full_cycle(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -190,7 +190,7 @@ def test_full_cycle(server_url: str) -> None: def test_resumable_upload(server_url: str) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase("test-usecase", expiration_policy=TimeToLive(timedelta(days=1))), org=42, project=1337, @@ -236,7 +236,7 @@ def test_resumable_upload(server_url: str) -> None: def test_resumable_upload_precompressed(server_url: str) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase("test-usecase", compression="none"), org=42, project=1337 ) payload = b"abcdef" @@ -258,7 +258,7 @@ def test_resumable_upload_precompressed(server_url: str) -> None: def test_resumable_upload_cancel(server_url: str) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase("test-usecase"), org=42, project=1337 ) upload = session._create_upload(6) @@ -274,7 +274,7 @@ def test_resumable_upload_cancel(server_url: str) -> None: def test_head(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -301,7 +301,7 @@ def test_head(server_url: str) -> None: def test_full_cycle_with_origin(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -323,7 +323,7 @@ def test_full_cycle_with_origin(server_url: str) -> None: def test_full_cycle_with_unicode_metadata(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -359,7 +359,7 @@ def test_full_cycle_with_unicode_metadata(server_url: str) -> None: def test_round_trips_expiration_policy_beyond_a_year(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) # Serializes as "400d 1h 18m 31s" @@ -384,7 +384,7 @@ def test_round_trips_expiration_policy_beyond_a_year(server_url: str) -> None: def test_extend_expiry(server_url: str) -> None: - client = Client(server_url, token=TestSecretKey.get()) + client = Client(server_url, token=TestTokenGenerator.get()) policy = TimeToLive(timedelta(days=1)) session = client.session(Usecase("test-usecase", expiration_policy=policy), org=42) key = session.put(b"payload") @@ -403,7 +403,7 @@ def test_extend_expiry(server_url: str) -> None: def test_extend_expiry_missing_object(server_url: str) -> None: - client = Client(server_url, token=TestSecretKey.get()) + client = Client(server_url, token=TestTokenGenerator.get()) session = client.session(Usecase("test-usecase"), org=42) with pytest.raises(ObjectNotFound) as error: session.extend_expiry("missing", from_now=timedelta(days=1)) @@ -411,7 +411,7 @@ def test_extend_expiry_missing_object(server_url: str) -> None: def test_extend_expiry_non_expiring_object(server_url: str) -> None: - client = Client(server_url, token=TestSecretKey.get()) + client = Client(server_url, token=TestTokenGenerator.get()) session = client.session(Usecase("test-usecase"), org=42) key = session.put(b"payload") with pytest.raises(ExpiryExtensionRejected) as error: @@ -422,7 +422,7 @@ def test_extend_expiry_non_expiring_object(server_url: str) -> None: def test_full_cycle_uncompressed(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -454,7 +454,7 @@ def test_full_cycle_uncompressed(server_url: str) -> None: def test_precompressed_is_stored_verbatim(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase("test-usecase") session = client.session(test_usecase, org=42, project=1337) @@ -478,7 +478,7 @@ def test_precompressed_is_stored_verbatim(server_url: str) -> None: def test_precompressed_rejects_conflicting_arguments(server_url: str) -> None: - client = Client(server_url, token=TestSecretKey.get()) + client = Client(server_url, token=TestTokenGenerator.get()) session = client.session(Usecase("test-usecase"), org=42, project=1337) with pytest.raises(ValueError): @@ -494,7 +494,7 @@ def test_precompressed_rejects_conflicting_arguments(server_url: str) -> None: def test_full_cycle_structured_key(server_url: str) -> None: client = Client( server_url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -513,7 +513,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=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -530,7 +530,7 @@ def test_not_found_with_different_scope(server_url: str) -> None: def test_full_cycle_with_static_token(server_url: str) -> None: - token_generator = TestSecretKey.get() + token_generator = TestTokenGenerator.get() token = token_generator.token_for_scope("test-usecase", Scope(org=42, project=1337)) client = Client(server_url, token=token) @@ -554,7 +554,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=TestSecretKey.create(permissions=[])) + client = Client(server_url, token=TestTokenGenerator.create(permissions=[])) test_usecase = Usecase( "test-usecase", expiration_policy=TimeToLive(timedelta(days=1)), @@ -578,7 +578,7 @@ def test_read_timeout() -> None: client = Client( url, timeout_ms=500, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -603,7 +603,7 @@ def test_connect_timeout() -> None: # Do NOT set timeout_ms to ensure we exercise default timeouts client = Client( url, - token=TestSecretKey.get(), + token=TestTokenGenerator.get(), ) test_usecase = Usecase( "test-usecase", @@ -640,7 +640,7 @@ def _fetch(url: str, method: str = "GET") -> tuple[int, bytes]: def _presign_session(server_url: str) -> Session: - client = Client(server_url, token=TestSecretKey.get()) + 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( @@ -692,14 +692,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 = TestSecretKey.get().token_for_scope( + token = TestTokenGenerator.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"): + with pytest.raises(ValueError, match="no token generator"): session.presigned_object_url("GET", "whatever", duration=timedelta(hours=1)) @@ -808,7 +808,7 @@ def test_jwt_response_options_remain_editable(server_url: str) -> None: def test_inline_preserves_stored_mime_type_and_compression(server_url: str) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase("test-usecase", compression="zstd"), org=42, project=1337 ) payload = b'' @@ -859,15 +859,15 @@ def test_object_url_without_token_is_unauthorized(server_url: str) -> None: assert status == 400 -def test_object_url_read_only_token_requires_secret_key(server_url: str) -> None: +def test_object_url_read_only_token_requires_token_generator(server_url: str) -> None: # A static token string cannot mint a re-scoped read-only token. - token = TestSecretKey.get().token_for_scope( + token = TestTokenGenerator.get().token_for_scope( "test-usecase", Scope(org=42, project=1337) ) client = Client(server_url, token=token) session = client.session(Usecase("test-usecase"), org=42, project=1337) - with pytest.raises(ValueError, match="no secret key"): + with pytest.raises(ValueError, match="no token generator"): session.object_url("whatever", token_validity=timedelta(minutes=5)) @@ -900,7 +900,7 @@ def test_put_stores_under_literal_key(server_url: str) -> None: def test_automatic_resumable_upload( server_url: str, source_kind: str, compression: str, threshold: int ) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase( "test-usecase", compression="zstd" if compression == "zstd" else "none", @@ -956,7 +956,7 @@ def test_automatic_resumable_upload( def test_resumable_creation_fallback( server_url: str, monkeypatch: pytest.MonkeyPatch, error: RequestError | None ) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase("test-usecase", resumable_threshold_bytes=1) ) create = Mock(return_value=None, side_effect=error) @@ -973,7 +973,7 @@ def test_resumable_creation_fallback( @pytest.mark.parametrize("compress", [False, True]) def test_nonseekable_upload(server_url: str, compress: bool) -> None: - session = Client(server_url, token=TestSecretKey.get()).session( + session = Client(server_url, token=TestTokenGenerator.get()).session( Usecase("test-usecase", resumable_threshold_bytes=1) ) with UnrewindableStream(b"payload") as source: diff --git a/clients/python/tests/test_presign.py b/clients/python/tests/test_presign.py index c5b3cbae..c88a5fb9 100644 --- a/clients/python/tests/test_presign.py +++ b/clients/python/tests/test_presign.py @@ -1,18 +1,14 @@ """Unit tests for the pre-signed URL signing utilities.""" -import base64 import os from datetime import UTC, datetime, timedelta from unittest.mock import patch from urllib.parse import parse_qs, urlsplit -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey -from cryptography.hazmat.primitives.serialization import load_pem_public_key from objectstore_client import Client, Usecase, presign, utils -from objectstore_client.auth import SecretKey +from objectstore_client.auth import SecretKey, TokenGenerator 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. @@ -55,35 +51,12 @@ def test_head_is_normalized_to_get() -> None: ) == 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", - utils.encode_path("/v1/objects/testing/_/key"), - utils.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 - - def test_presigned_url_response_options() -> None: with open(TEST_EDDSA_PRIVKEY_PATH) as f: secret = SecretKey("test_kid", f.read()) - session = Client("https://example.com/prefix", token=secret).session( - Usecase("testing"), org=1 - ) + session = Client( + "https://example.com/prefix", token=TokenGenerator(secret) + ).session(Usecase("testing"), org=1) with patch("objectstore_client.client.datetime") as clock: clock.now.return_value = datetime(2026, 4, 20, 13, 37, tzinfo=UTC) legacy = session.presigned_object_url("GET", "key") @@ -107,9 +80,9 @@ def test_presigned_url_response_options() -> None: def test_jwt_url_options_roundtrip_without_binding_token() -> None: with open(TEST_EDDSA_PRIVKEY_PATH) as f: secret = SecretKey("test_kid", f.read()) - session = Client("https://example.com/prefix", token=secret).session( - Usecase("testing") - ) + session = Client( + "https://example.com/prefix", token=TokenGenerator(secret) + ).session(Usecase("testing")) with patch.object(session, "mint_token", return_value="same.jwt.token"): legacy = session.object_url("key", token_validity=timedelta(minutes=5)) url = session.object_url(