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
45 changes: 37 additions & 8 deletions clients/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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="<private key>"),
token=SecretKey(kid="my-service", secret_key="<private 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="<private 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
Comment thread
lcian marked this conversation as resolved.
Resolved

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.
Expand Down
3 changes: 2 additions & 1 deletion clients/python/src/objectstore_client/__init__.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -29,6 +29,7 @@
"TimeToIdle",
"TimeToLive",
"TokenProvider",
"SecretKey",
"TokenGenerator",
"MetricsBackend",
"NoOpMetricsBackend",
Expand Down
48 changes: 34 additions & 14 deletions clients/python/src/objectstore_client/auth.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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__(
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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}
Expand All @@ -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
85 changes: 73 additions & 12 deletions clients/python/src/objectstore_client/client.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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.
"""
Expand Down Expand Up @@ -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(
Comment thread
lcian marked this conversation as resolved.
Resolved
self._usecase.name,
self._scope,
permissions,
Expand All @@ -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
Expand Down Expand Up @@ -446,6 +447,66 @@ def object_url(self, key: str) -> str:
"""
return self._make_url(key, full=True)

def presigned_object_url(
Comment thread
lcian marked this conversation as resolved.
Resolved
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())
Comment thread
lcian marked this conversation as resolved.
Resolved

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}"
)
Comment thread
lcian marked this conversation as resolved.
Resolved

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.
Expand Down
Loading
Loading