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
#![warn(missing_docs)]
pub mod approle;
pub mod database;
pub mod kv2;
pub mod token;
use serde::Serialize;
use std::fmt;
use url::Url;
#[derive(Debug)]
pub enum Error {
ParseError(url::ParseError),
ReqwestError(reqwest::Error),
InvalidRequest,
IsSealed,
NotFound,
Unauthorized,
SessionExpired,
Other,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::ParseError(ref cause) => write!(f, "Parse Error: {}", cause),
Error::ReqwestError(ref cause) => write!(f, "Reqwest Error: {}", cause),
Error::InvalidRequest => write!(f, "Invalid Request: Invalid or Missing data"),
Error::IsSealed => write!(
f,
"The Vault instance is still sealed and can't be used at the moment"
),
Error::NotFound => write!(f, "Not Found"),
Error::Unauthorized => write!(f, "Unauthorized"),
Error::SessionExpired => write!(f, "Session has expired, no auto login"),
Error::Other => write!(f, "Unknown error"),
}
}
}
impl From<url::ParseError> for Error {
fn from(cause: url::ParseError) -> Error {
Error::ParseError(cause)
}
}
impl From<reqwest::Error> for Error {
fn from(cause: reqwest::Error) -> Error {
Error::ReqwestError(cause)
}
}
pub trait Auth {
fn is_expired(&self) -> bool;
fn auth(&self, vault_url: &str) -> Result<(), Error>;
fn get_token(&self) -> String;
}
pub enum RenewPolicy {
Reauth,
Nothing,
}
pub struct Config {
pub vault_url: String,
pub renew_policy: RenewPolicy,
}
impl Default for Config {
fn default() -> Config {
Config {
vault_url: "http://localhost:8200".to_string(),
renew_policy: RenewPolicy::Reauth,
}
}
}
pub struct Client<T: Auth> {
config: Config,
auth: T,
reauth_mutex: std::sync::Mutex<()>,
}
impl<T: Auth> Client<T> {
pub fn new(conf: Config, auth_opts: T) -> Result<Client<T>, Error> {
match auth_opts.auth(&conf.vault_url) {
Err(e) => return Err(e),
Ok(()) => {}
};
Ok(Client::<T> {
config: conf,
auth: auth_opts,
reauth_mutex: std::sync::Mutex::new(()),
})
}
pub fn get_token(&self) -> String {
self.auth.get_token()
}
pub async fn check_session(&self) -> Result<(), Error> {
if !self.auth.is_expired() {
return Ok(());
}
let _data = self.reauth_mutex.lock().unwrap();
if !self.auth.is_expired() {
return Ok(());
}
let result = match self.config.renew_policy {
RenewPolicy::Reauth => self.auth.auth(&self.config.vault_url),
RenewPolicy::Nothing => Err(Error::SessionExpired),
};
return result;
}
pub async fn vault_request<P: Serialize>(
&self,
method: reqwest::Method,
path: &str,
body: Option<&P>,
) -> Result<reqwest::Response, Error> {
self.check_session().await?;
let mut url = match Url::parse(&self.config.vault_url) {
Err(e) => {
return Err(Error::from(e));
}
Ok(url) => url,
};
url = match url.join("v1/") {
Err(e) => {
return Err(Error::from(e));
}
Ok(u) => u,
};
url = match url.join(path) {
Err(e) => {
return Err(Error::from(e));
}
Ok(u) => u,
};
let token = self.auth.get_token();
let http_client = reqwest::Client::new();
let mut req = http_client
.request(method, url)
.header("X-Vault-Token", &token)
.header("X-Vault-Request", "true");
if body.is_some() {
req = req.json(body.unwrap());
}
let resp = match req.send().await {
Err(e) => return Err(Error::from(e)),
Ok(resp) => resp,
};
let status_code = resp.status().as_u16();
match status_code {
200 | 204 => Ok(resp),
400 => Err(Error::InvalidRequest),
403 => Err(Error::Unauthorized),
404 => Err(Error::NotFound),
503 => Err(Error::IsSealed),
_ => Err(Error::Other),
}
}
}