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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ tls = (
etcd = Client(["https://127.0.0.1:2379"], connect_options=ConnectOptions().with_tls(tls))
```

### Connecting with a user

etcd expires an authentication token that is not used for a while (5 minutes by default, `--auth-token-ttl`). Set `with_auto_token_refresh(True)` so that a request rejected with an expired token authenticates again and is resent. Without it, every request fails with `invalid auth token` once the token expires.

```python
from etcd_client import Client, ConnectOptions

connect_options = ConnectOptions().with_user("root", "password").with_auto_token_refresh(True)
etcd = Client(["http://127.0.0.1:2379"], connect_options=connect_options)
```

### Working with key prefixes

`EtcdCommunicator.get_prefix(prefix)` returns a list of key-value pairs matching the given prefix.
Expand Down
1 change: 1 addition & 0 deletions etcd_client.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ class ConnectOptions:
def __init__(self) -> None: ...
def with_tls(self, tls: TlsOptions) -> "ConnectOptions": ...
def with_user(self, user: str, password: str) -> "ConnectOptions": ...
def with_auto_token_refresh(self, enabled: bool) -> "ConnectOptions": ...
def with_keep_alive(self, interval: float, timeout: float) -> "ConnectOptions": ...
def with_keep_alive_while_idle(self, enabled: bool) -> "ConnectOptions": ...
def with_connect_timeout(self, connect_timeout: float) -> "ConnectOptions": ...
Expand Down
4 changes: 4 additions & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ impl PyConnectOptions {
PyConnectOptions(self.0.clone().with_user(name, password))
}

fn with_auto_token_refresh(&self, enabled: bool) -> Self {
PyConnectOptions(self.0.clone().with_auto_token_refresh(enabled))
}

fn with_keep_alive(&self, interval: f64, timeout: f64) -> Self {
PyConnectOptions(self.0.clone().with_keep_alive(
Duration::from_secs_f64(interval),
Expand Down
74 changes: 74 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import asyncio
from collections.abc import Iterator

import pytest
from etcd_client import Client, ConnectOptions, GRPCStatusError
from testcontainers.core.container import DockerContainer
from testcontainers.core.wait_strategies import LogMessageWaitStrategy

from .conftest import ETCD_VER

_ROOT_PASSWORD = "root-password"
_AUTH_TOKEN_TTL_SECONDS = 1
_WAIT_FOR_TOKEN_EXPIRY_SECONDS = 3.0

_etcd_command_with_short_token_ttl = f"""/usr/local/bin/etcd
--name s1
--data-dir /etcd-data
--listen-client-urls http://0.0.0.0:2379
--advertise-client-urls http://0.0.0.0:2379
--auth-token simple
--auth-token-ttl {_AUTH_TOKEN_TTL_SECONDS}
--log-level info
--logger zap
--log-outputs stderr
"""


@pytest.fixture(scope="module")
def auth_enabled_etcd_endpoint() -> Iterator[str]:
container = (
DockerContainer(
f"gcr.io/etcd-development/etcd:{ETCD_VER}",
command=_etcd_command_with_short_token_ttl,
)
.with_exposed_ports(2379)
.waiting_for(LogMessageWaitStrategy("ready to serve client requests"))
)
with container:
container.exec(["etcdctl", "user", "add", "root", "--new-user-password", _ROOT_PASSWORD])
container.exec(["etcdctl", "auth", "enable"])
yield f"http://127.0.0.1:{container.get_exposed_port(2379)}"


@pytest.mark.asyncio
async def test_request_after_token_expiry_succeeds_with_auto_token_refresh(
auth_enabled_etcd_endpoint: str,
) -> None:
client = Client(
[auth_enabled_etcd_endpoint],
connect_options=ConnectOptions()
.with_user("root", _ROOT_PASSWORD)
.with_auto_token_refresh(True),
)
async with client.connect() as communicator:
await communicator.put(b"auth-key", b"auth-value")
await asyncio.sleep(_WAIT_FOR_TOKEN_EXPIRY_SECONDS)

assert bytes(await communicator.get(b"auth-key")) == b"auth-value"


@pytest.mark.asyncio
async def test_request_after_token_expiry_fails_without_auto_token_refresh(
auth_enabled_etcd_endpoint: str,
) -> None:
client = Client(
[auth_enabled_etcd_endpoint],
connect_options=ConnectOptions().with_user("root", _ROOT_PASSWORD),
)
async with client.connect() as communicator:
await communicator.put(b"auth-key", b"auth-value")
await asyncio.sleep(_WAIT_FOR_TOKEN_EXPIRY_SECONDS)

with pytest.raises(GRPCStatusError, match="invalid auth token"):
await communicator.get(b"auth-key")
Loading