etcdrs 0.1.2

An async etcd v3 client built on tonic and tokio, with composable operation builders and type-safe responses
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use std::{
    future::{Future, IntoFuture},
    pin::Pin,
    task::{Context, Poll},
};

use crate::{Client, ResponseHeader, client::ClientInner, pb::etcdserverpb};

/// # Authentication
impl Client {
    /// Enable authentication on the cluster.
    ///
    /// A root user must exist before authentication can be enabled. Create one with
    /// [`user_add`][Client::user_add], then assign the `root` role with
    /// [`user_grant_role`][Client::user_grant_role].
    pub fn auth_enable(&self) -> AuthEnable<Self> {
        AuthEnable::new().with_client(self.clone())
    }

    /// Disable authentication on the cluster.
    pub fn auth_disable(&self) -> AuthDisable<Self> {
        AuthDisable::new().with_client(self.clone())
    }

    /// Query whether authentication is enabled on the cluster.
    ///
    /// ```no_run
    /// # async {
    /// let client: etcdrs::Client = todo!();
    /// let status = client.auth_status().await.unwrap();
    /// println!("auth enabled: {}", status.enabled());
    /// # };
    /// ```
    pub fn auth_status(&self) -> AuthStatus<Self> {
        AuthStatus::new().with_client(self.clone())
    }

    /// Authenticate with the cluster using the credentials provided to
    /// [`ClientBuilder::credentials`][crate::client::ClientBuilder::credentials], returning a
    /// token.
    ///
    /// This method is useful for checking if the credentials you provided are valid. Other methods
    /// can still fail with authentication errors (especially if configuration changes), but usage
    /// of those might be deep in some other code path.
    ///
    /// Returns [`AuthErrorKind::InvalidCredentials`] if no credentials were configured on the
    /// client.
    pub fn authenticate(&self) -> Authenticate<Self> {
        Authenticate::new().with_client(self.clone())
    }
}

/// A [`Client::auth_enable`] operation.
#[derive(Clone)]
#[must_use = "AuthEnable does nothing unless you `await` it"]
pub struct AuthEnable<C> {
    client: C,
}

impl AuthEnable<()> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self { client: () }
    }
}

impl<C> AuthEnable<C> {
    pub fn with_client<C2>(self, client: C2) -> AuthEnable<C2> {
        AuthEnable { client }
    }

    pub(crate) fn into_parts(self) -> (C, AuthEnable<()>) {
        (self.client, AuthEnable { client: () })
    }
}

/// A [`Client::auth_disable`] operation.
#[derive(Clone)]
#[must_use = "AuthDisable does nothing unless you `await` it"]
pub struct AuthDisable<C> {
    client: C,
}

impl AuthDisable<()> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self { client: () }
    }
}

impl<C> AuthDisable<C> {
    pub fn with_client<C2>(self, client: C2) -> AuthDisable<C2> {
        AuthDisable { client }
    }

    pub(crate) fn into_parts(self) -> (C, AuthDisable<()>) {
        (self.client, AuthDisable { client: () })
    }
}

/// A [`Client::auth_status`] operation.
#[derive(Clone)]
#[must_use = "AuthStatus does nothing unless you `await` it"]
pub struct AuthStatus<C> {
    client: C,
}

impl AuthStatus<()> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self { client: () }
    }
}

impl<C> AuthStatus<C> {
    pub fn with_client<C2>(self, client: C2) -> AuthStatus<C2> {
        AuthStatus { client }
    }

    pub(crate) fn into_parts(self) -> (C, AuthStatus<()>) {
        (self.client, AuthStatus { client: () })
    }
}

/// A [`Client::authenticate`] operation.
#[derive(Clone)]
#[must_use = "Authenticate does nothing unless you `await` it"]
pub struct Authenticate<C> {
    client: C,
}

impl Authenticate<()> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self { client: () }
    }
}

impl<C> Authenticate<C> {
    pub fn with_client<C2>(self, client: C2) -> Authenticate<C2> {
        Authenticate { client }
    }

    pub(crate) fn into_parts(self) -> (C, Authenticate<()>) {
        (self.client, Authenticate { client: () })
    }
}

pub struct AuthEnableFuture(Pin<Box<dyn Future<Output = Result<AuthEnableResponse, AuthError>> + Send>>);

impl AuthEnableFuture {
    pub(crate) fn new(future: impl Future<Output = Result<AuthEnableResponse, AuthError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for AuthEnableFuture {
    type Output = Result<AuthEnableResponse, AuthError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

pub struct AuthDisableFuture(Pin<Box<dyn Future<Output = Result<AuthDisableResponse, AuthError>> + Send>>);

impl AuthDisableFuture {
    pub(crate) fn new(future: impl Future<Output = Result<AuthDisableResponse, AuthError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for AuthDisableFuture {
    type Output = Result<AuthDisableResponse, AuthError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

pub struct AuthStatusFuture(Pin<Box<dyn Future<Output = Result<AuthStatusResponse, AuthError>> + Send>>);

impl AuthStatusFuture {
    pub(crate) fn new(future: impl Future<Output = Result<AuthStatusResponse, AuthError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for AuthStatusFuture {
    type Output = Result<AuthStatusResponse, AuthError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

pub struct AuthenticateFuture(Pin<Box<dyn Future<Output = Result<AuthenticateResponse, AuthError>> + Send>>);

impl AuthenticateFuture {
    pub(crate) fn new(future: impl Future<Output = Result<AuthenticateResponse, AuthError>> + Send + 'static) -> Self {
        Self(Box::pin(future))
    }
}

impl Future for AuthenticateFuture {
    type Output = Result<AuthenticateResponse, AuthError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.as_mut().poll(cx)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for AuthEnable<C> {
    type Output = Result<AuthEnableResponse, AuthError>;
    type IntoFuture = C::AuthEnableFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_auth_enable(detached)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for AuthDisable<C> {
    type Output = Result<AuthDisableResponse, AuthError>;
    type IntoFuture = C::AuthDisableFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_auth_disable(detached)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for AuthStatus<C> {
    type Output = Result<AuthStatusResponse, AuthError>;
    type IntoFuture = C::AuthStatusFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_auth_status(detached)
    }
}

impl<C: crate::driver::AuthDriver> IntoFuture for Authenticate<C> {
    type Output = Result<AuthenticateResponse, AuthError>;
    type IntoFuture = C::AuthenticateFuture;

    fn into_future(self) -> Self::IntoFuture {
        let (client, detached) = self.into_parts();
        client.execute_authenticate(detached)
    }
}

/// The response from an [`auth_enable`][Client::auth_enable] operation.
#[derive(Clone, Copy, Debug)]
pub struct AuthEnableResponse {
    header: ResponseHeader,
}

impl AuthEnableResponse {
    pub(crate) fn new(header: ResponseHeader) -> Self {
        Self { header }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }
}

/// The response from an [`auth_disable`][Client::auth_disable] operation.
#[derive(Clone, Copy, Debug)]
pub struct AuthDisableResponse {
    header: ResponseHeader,
}

impl AuthDisableResponse {
    pub(crate) fn new(header: ResponseHeader) -> Self {
        Self { header }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }
}

/// The response from an [`auth_status`][Client::auth_status] operation.
#[derive(Clone, Copy, Debug)]
pub struct AuthStatusResponse {
    header: ResponseHeader,
    enabled: bool,
    auth_revision: u64,
}

impl AuthStatusResponse {
    pub(crate) fn new(header: ResponseHeader, enabled: bool, auth_revision: u64) -> Self {
        Self {
            header,
            enabled,
            auth_revision,
        }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// Whether authentication is enabled on the cluster.
    pub fn enabled(&self) -> bool {
        self.enabled
    }

    /// The revision of the auth store.
    ///
    /// This increments with each authentication-related mutation (user, role, or permission
    /// change), independently of the key-value store revision.
    pub fn auth_revision(&self) -> u64 {
        self.auth_revision
    }
}

/// The response from an [`authenticate`][Client::authenticate] operation.
#[derive(Clone, Debug)]
pub struct AuthenticateResponse {
    header: ResponseHeader,
    token: String,
}

impl AuthenticateResponse {
    pub(crate) fn new(header: ResponseHeader, token: String) -> Self {
        Self { header, token }
    }

    /// The response header containing cluster metadata and the store revision.
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// The auth token that can be used for authenticated requests.
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Consume the response and return the auth token.
    pub fn into_token(self) -> String {
        self.token
    }
}

/// An enumeration of the [`kind`][AuthError::kind]s of errors that can occur from auth control
/// operations ([`auth_enable`][Client::auth_enable], [`auth_disable`][Client::auth_disable],
/// [`auth_status`][Client::auth_status], [`authenticate`][Client::authenticate]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AuthErrorKind {
    /// Authentication is already enabled.
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "already enabled".
    AlreadyEnabled,
    /// Authentication is not enabled.
    ///
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "not enabled".
    NotEnabled,
    /// The root user is missing, or it has not been granted the `root` role.
    ///
    /// Authentication can be enabled only when a user named `root` exists and has the `root` role.
    /// This comes from the gRPC API as `FAILED_PRECONDITION` with "etcdserver: root user does not
    /// exist" or "etcdserver: root user does not have root role".
    RootUserRequired,
    /// The provided credentials are invalid.
    ///
    /// This comes from the gRPC API as `UNAUTHENTICATED`, `PERMISSION_DENIED`, or
    /// `INVALID_ARGUMENT` when the argument describes an authentication error.
    InvalidCredentials,
    /// The server or transport is resource-exhausted.
    ///
    /// This comes from the gRPC API as `RESOURCE_EXHAUSTED`.
    Exhausted,
    /// The server is not ready to serve that request.
    ///
    /// This comes from the gRPC API as `UNAVAILABLE`.
    Unavailable,
    /// The request timed out.
    ///
    /// This comes from the gRPC API as `CANCELLED` or `DEADLINE_EXCEEDED`. We do not distinguish
    /// between the two, as the source of the timeout is usually not important.
    Timeout,
    /// An error that is not covered by any other error kind.
    ///
    /// All uncovered gRPC errors are mapped to this kind of error. They should not happen unless
    /// the etcd server has changed its error codes.
    Unknown,
}

define_op_error! {
    /// An error from an auth control operation ([`auth_enable`][Client::auth_enable],
    /// [`auth_disable`][Client::auth_disable], [`auth_status`][Client::auth_status],
    /// [`authenticate`][Client::authenticate]).
    pub struct AuthError(AuthErrorKind);
}

impl AuthError {
    pub(crate) fn from_status(status: tonic::Status) -> Self {
        let kind = match status.code() {
            tonic::Code::FailedPrecondition => {
                let msg = status.message();
                if msg.contains("already enabled") {
                    AuthErrorKind::AlreadyEnabled
                } else if msg.contains("not enabled") {
                    AuthErrorKind::NotEnabled
                } else if msg.contains("root user") {
                    AuthErrorKind::RootUserRequired
                } else {
                    AuthErrorKind::Unknown
                }
            }
            tonic::Code::Unauthenticated => AuthErrorKind::InvalidCredentials,
            tonic::Code::PermissionDenied => AuthErrorKind::InvalidCredentials,
            tonic::Code::InvalidArgument => AuthErrorKind::InvalidCredentials,
            tonic::Code::ResourceExhausted => AuthErrorKind::Exhausted,
            tonic::Code::Unavailable => AuthErrorKind::Unavailable,
            tonic::Code::Cancelled | tonic::Code::DeadlineExceeded => AuthErrorKind::Timeout,
            _ => AuthErrorKind::Unknown,
        };
        Self::new(kind, "", Some(status))
    }
}

// === Authentication Handling ===

impl ClientInner {
    /// Execute the `Authenticate` RPC, returning the raw protobuf response.
    ///
    /// This bypasses [`wrap_unary_call`][Self::wrap_unary_call] to avoid circular token refresh. It
    /// is used by both the public [`Client::authenticate`] method and the internal token refresh
    /// path.
    ///
    /// `timeout` is the deadline to send with the request. The refresh path passes what is left of
    /// the calling request's budget, so a stalled `Authenticate` cannot outlive it.
    pub(crate) async fn authenticate(
        &self,
        name: &str,
        password: &str,
        timeout: Option<std::time::Duration>,
    ) -> Result<etcdserverpb::AuthenticateResponse, tonic::Status> {
        let mut client = self.service_client(etcdserverpb::auth_client::AuthClient::new);
        let mut request = tonic::Request::new(etcdserverpb::AuthenticateRequest {
            name: name.into(),
            password: password.into(),
        });
        if let Some(timeout) = timeout {
            request.set_timeout(timeout);
        }
        client.authenticate(request).await.map(|r| r.into_inner())
    }

    /// Refresh the cached auth token using stored credentials.
    ///
    /// `stale_generation` is the generation observed when the caller read the token that turned out
    /// to be stale. If another caller has already refreshed (advancing the generation), this call
    /// returns `Ok(())` without making a redundant `Authenticate` RPC.
    ///
    /// `deadline` bounds the `Authenticate` RPC. It is an instant rather than a duration because
    /// waiting on `refresh` can take arbitrarily long: a refresher that fails without advancing the
    /// generation leaves the next caller to authenticate itself, by which point a duration computed
    /// before the wait would be stale. The remainder is recomputed once the wait is over.
    pub(crate) async fn refresh_auth_token(
        &self,
        stale_generation: u64,
        deadline: Option<std::time::Instant>,
    ) -> Result<(), tonic::Status> {
        let auth = self
            .auth
            .as_ref()
            .ok_or_else(|| tonic::Status::unauthenticated("no auth configured"))?;
        let _guard = auth.refresh.lock().await;
        self.refresh_auth_token_unserialized(stale_generation, deadline).await
    }

    /// [`refresh_auth_token`][Self::refresh_auth_token] without waiting for other refreshes, which
    /// can then run alongside it.
    ///
    /// Streams refresh this way. A stream's consumer can stop polling it at any `.await` without
    /// dropping it, and a stream stopped while it held or was being handed `refresh` would stall
    /// every other refresh on the client until it was polled again.
    pub(crate) async fn refresh_auth_token_unserialized(
        &self,
        stale_generation: u64,
        deadline: Option<std::time::Instant>,
    ) -> Result<(), tonic::Status> {
        let auth = self
            .auth
            .as_ref()
            .ok_or_else(|| tonic::Status::unauthenticated("no auth configured"))?;
        // Another caller may have refreshed already.
        if auth.token.read().unwrap().0 != stale_generation {
            return Ok(());
        }
        let creds = auth.credentials.as_ref().ok_or_else(|| {
            tonic::Status::unauthenticated("auth token expired and no credentials available for re-authentication")
        })?;
        let timeout = deadline.map(|d| d.saturating_duration_since(std::time::Instant::now()));
        let resp = self.authenticate(&creds.username, &creds.password, timeout).await?;
        let token_value = resp
            .token
            .parse::<tonic::metadata::AsciiMetadataValue>()
            .map_err(|_| tonic::Status::internal("server returned an invalid auth token"))?;
        let mut token = auth.token.write().unwrap();
        if token.0 == stale_generation {
            *token = (stale_generation + 1, Some(token_value));
        }
        Ok(())
    }
}