Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 16 additions & 15 deletions clients/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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="<private key>")

# Option 1: Internal service with a keypair
client = Client(
"http://localhost:8888",
token=SecretKey(kid="my-service", secret_key="<private 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="<private 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)
```
Expand All @@ -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
Expand All @@ -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.
Expand Down
9 changes: 8 additions & 1 deletion clients/python/src/objectstore_client/__init__.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -35,6 +41,7 @@
"TimeToIdle",
"TimeToLive",
"TokenProvider",
"Token",
"SecretKey",
"TokenGenerator",
"MetricsBackend",
Expand Down
88 changes: 51 additions & 37 deletions clients/python/src/objectstore_client/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -53,30 +84,26 @@ 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.

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": {
Expand All @@ -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
28 changes: 14 additions & 14 deletions clients/python/src/objectstore_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand All @@ -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(
Expand All @@ -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}"
)
Expand All @@ -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()}"
Expand Down
56 changes: 56 additions & 0 deletions clients/python/tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -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:
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
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
Loading
Loading