From 333608c6827b5f9aa88a4b2fca502664ba48698b Mon Sep 17 00:00:00 2001 From: Gyubong Date: Wed, 11 Nov 2026 11:27:40 +0900 Subject: [PATCH] feat: Add ConnectOptions.with_auto_token_refresh() etcd drops an authentication token that has not been used for `--auth-token-ttl` (300 seconds by default). The Rust client gets a token once at connect and keeps sending it, so once it expires every request fails with `invalid auth token` until the client reconnects. Expose `etcd-client`'s `with_auto_token_refresh()`, which authenticates again and resends the request when the token is rejected. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +++++++ etcd_client.pyi | 1 + src/client.rs | 4 +++ tests/test_auth.py | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 90 insertions(+) create mode 100644 tests/test_auth.py diff --git a/README.md b/README.md index e6d805c..f6528bc 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/etcd_client.pyi b/etcd_client.pyi index c537477..d09a470 100644 --- a/etcd_client.pyi +++ b/etcd_client.pyi @@ -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": ... diff --git a/src/client.rs b/src/client.rs index 84ddee9..ca7f68b 100644 --- a/src/client.rs +++ b/src/client.rs @@ -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), diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..8674a71 --- /dev/null +++ b/tests/test_auth.py @@ -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")