refactor(ops/yandex-cloud-rs): allow TokenProvider impls to fail

It's actually quite common that a token provider might fail, for
example when fetching a token from instance metadata.

Change-Id: Ie0126fb92c6c613ad36b5583fd68505fdd97f2c1
Reviewed-on: https://cl.tvl.fyi/c/depot/+/8764
Tested-by: BuildkiteCI
Reviewed-by: tazjin <tazjin@tvl.su>
This commit is contained in:
Vincent Ambo 2023-06-13 22:47:40 +03:00 committed by tazjin
parent ed388f019a
commit 2e893dca1d

View file

@ -52,18 +52,18 @@ pub mod tonic_exports {
/// tokens for Yandex Cloud. /// tokens for Yandex Cloud.
pub trait TokenProvider { pub trait TokenProvider {
/// Fetch a currently valid authentication token for Yandex Cloud. /// Fetch a currently valid authentication token for Yandex Cloud.
fn get_token<'a>(&'a mut self) -> &'a str; fn get_token<'a>(&'a mut self) -> Result<&'a str, tonic::Status>;
} }
impl TokenProvider for String { impl TokenProvider for String {
fn get_token<'a>(&'a mut self) -> &'a str { fn get_token<'a>(&'a mut self) -> Result<&'a str, tonic::Status> {
self.as_str() Ok(self.as_str())
} }
} }
impl TokenProvider for &'static str { impl TokenProvider for &'static str {
fn get_token(&mut self) -> &'static str { fn get_token(&mut self) -> Result<&'static str, tonic::Status> {
*self Ok(*self)
} }
} }
@ -89,7 +89,7 @@ impl<T: TokenProvider> Interceptor for AuthInterceptor<T> {
&mut self, &mut self,
mut request: tonic::Request<()>, mut request: tonic::Request<()>,
) -> Result<tonic::Request<()>, tonic::Status> { ) -> Result<tonic::Request<()>, tonic::Status> {
let token: MetadataValue<Ascii> = format!("Bearer {}", self.token_provider.get_token()) let token: MetadataValue<Ascii> = format!("Bearer {}", self.token_provider.get_token()?)
.try_into() .try_into()
.map_err(|_| { .map_err(|_| {
tonic::Status::invalid_argument("authorization token contained invalid characters") tonic::Status::invalid_argument("authorization token contained invalid characters")