use std::{
future::{Future, IntoFuture},
pin::Pin,
task::{Context, Poll},
};
use crate::{Client, ResponseHeader, client::ClientInner, pb::etcdserverpb};
impl Client {
pub fn auth_enable(&self) -> AuthEnable<Self> {
AuthEnable::new().with_client(self.clone())
}
pub fn auth_disable(&self) -> AuthDisable<Self> {
AuthDisable::new().with_client(self.clone())
}
pub fn auth_status(&self) -> AuthStatus<Self> {
AuthStatus::new().with_client(self.clone())
}
pub fn authenticate(&self) -> Authenticate<Self> {
Authenticate::new().with_client(self.clone())
}
}
#[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: () })
}
}
#[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: () })
}
}
#[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: () })
}
}
#[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)
}
}
#[derive(Clone, Copy, Debug)]
pub struct AuthEnableResponse {
header: ResponseHeader,
}
impl AuthEnableResponse {
pub(crate) fn new(header: ResponseHeader) -> Self {
Self { header }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
}
#[derive(Clone, Copy, Debug)]
pub struct AuthDisableResponse {
header: ResponseHeader,
}
impl AuthDisableResponse {
pub(crate) fn new(header: ResponseHeader) -> Self {
Self { header }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
}
#[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,
}
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
pub fn enabled(&self) -> bool {
self.enabled
}
pub fn auth_revision(&self) -> u64 {
self.auth_revision
}
}
#[derive(Clone, Debug)]
pub struct AuthenticateResponse {
header: ResponseHeader,
token: String,
}
impl AuthenticateResponse {
pub(crate) fn new(header: ResponseHeader, token: String) -> Self {
Self { header, token }
}
pub fn header(&self) -> &ResponseHeader {
&self.header
}
pub fn token(&self) -> &str {
&self.token
}
pub fn into_token(self) -> String {
self.token
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AuthErrorKind {
AlreadyEnabled,
NotEnabled,
RootUserRequired,
InvalidCredentials,
Exhausted,
Unavailable,
Timeout,
Unknown,
}
define_op_error! {
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))
}
}
impl ClientInner {
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())
}
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
}
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"))?;
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(())
}
}