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
pub use compute_metadata::get_project_id;
use futures::{future::TryFutureExt, try_join};
pub use secretmanager_grpc::google::cloud::secretmanager::v1::*;
use secretmanager_grpc::tonic::{
metadata::errors::InvalidMetadataValue,
metadata::MetadataValue,
transport::{Channel, ClientTlsConfig},
Request,
};
use std::env;
use thiserror::Error;
pub mod compute_metadata;
pub use secret_manager_service_client::SecretManagerServiceClient;
const URL: &'static str = "https://secretmanager.googleapis.com";
const DOMAIN: &'static str = "secretmanager.googleapis.com";
#[derive(Error, Debug)]
pub enum SmClientError {
#[error("empty error")]
EmptyError,
#[error(transparent)]
OtherError(#[from] std::io::Error),
#[error(transparent)]
SmError(#[from] secretmanager_grpc::tonic::Status),
#[error(transparent)]
TpError(#[from] secretmanager_grpc::tonic::transport::Error),
#[error(transparent)]
Tp2Error(#[from] InvalidMetadataValue),
#[error(transparent)]
SerdeError(#[from] serde_json::Error),
#[error(transparent)]
HyperHttpError(#[from] hyper::http::Error),
#[error(transparent)]
HyperError(#[from] hyper::Error),
#[error(transparent)]
FooError(#[from] std::string::FromUtf8Error),
#[error(transparent)]
InvalidUriError(#[from] http::uri::InvalidUri),
}
pub async fn get_client() -> Result<SecretManagerServiceClient<Channel>, SmClientError> {
match env::var("SECRETMANAGER_EMULATOR_HOST") {
Ok(addr) => {
let endpoint = Channel::from_shared(addr.clone())?;
let channel = endpoint.connect().await?;
let service = SecretManagerServiceClient::with_interceptor(
channel,
move |mut req: Request<()>| {
req.metadata_mut();
Ok(req)
},
);
Ok(service)
}
Err(_e) => {
let endpoint = Channel::from_static(URL)
.tls_config(ClientTlsConfig::new().domain_name(DOMAIN))
.expect("TODO - handle the connect error");
let (channel, token) = try_join!(
endpoint.connect().map_err(|e| SmClientError::from(e)),
compute_metadata::get_token()
)?;
let bearer_token = format!("Bearer {}", token);
let header_value = MetadataValue::from_str(&bearer_token)?;
let service = SecretManagerServiceClient::with_interceptor(
channel,
move |mut req: Request<()>| {
req.metadata_mut()
.insert("authorization", header_value.clone());
Ok(req)
},
);
Ok(service)
}
}
}