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
#![doc = include_str!("../README.md")]

pub mod args;

use std::{sync::Arc, time::Duration};

use async_trait::async_trait;
use cache_loader_async::{
    backing::{LruCacheBacking, TtlCacheBacking, TtlMeta},
    cache_api::{CacheEntry, LoadingCache, WithMeta},
};
use log::debug;
use metrics::increment_counter;
use reqwest::{Certificate, Client, StatusCode, Url};
use serde::{Deserialize, Serialize};
use tokio::{sync::Mutex, time::Instant};

use streambed::{
    delayer::Delayer,
    secret_store::{
        AppRoleAuthReply, Error, GetSecretReply, SecretData, SecretStore, UserPassAuthReply,
    },
};

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
struct AppRoleAuthRequest {
    pub role_id: String,
    pub secret_id: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
struct UserPassAuthRequest {
    pub password: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
struct UserPassCreateUpdateRequest {
    pub username: String,
    pub password: String,
}

type TtlCache = LoadingCache<
    String,
    Option<GetSecretReply>,
    Error,
    TtlCacheBacking<
        String,
        CacheEntry<Option<GetSecretReply>, Error>,
        LruCacheBacking<String, (CacheEntry<Option<GetSecretReply>, Error>, Instant)>,
    >,
>;

/// A client interface that uses the Hashicorp Vault HTTP API.
#[derive(Clone)]
pub struct VaultSecretStore {
    cache: TtlCache,
    client: Client,
    client_token: Arc<Mutex<Option<String>>>,
    max_secrets_cached: usize,
    server: Url,
    ttl_field: Option<String>,
    unauthorized_timeout: Duration,
}

const APPROLE_AUTH_LABEL: &str = "approle_auth";
const SECRET_PATH_LABEL: &str = "secret_path";
const USERPASS_AUTH_LABEL: &str = "userpass_auth";
const USERPASS_CREATE_UPDATE_LABEL: &str = "userpass_create_update";

impl VaultSecretStore {
    /// Establish a new client to Hashicorp Vault. In the case where TLS is required,
    /// a root certificate may be provided e.g. when using self-signed certificates. TLS
    /// connections are encouraged.
    /// An unauthorized_timeout determines how long the server should wait before being
    /// requested again.
    /// A max_secrets_cached arg limits the number of secrets that can be held at any time.
    ///
    /// Avoid creating many new Vault secret stores and clone them instead so that HTTP
    /// connection pools can be shared.
    pub fn new(
        server: Url,
        server_cert: Option<Certificate>,
        tls_insecure: bool,
        unauthorized_timeout: Duration,
        max_secrets_cached: usize,
        ttl_field: Option<&str>,
    ) -> Self {
        let client = Client::builder().danger_accept_invalid_certs(tls_insecure);
        let client = if let Some(cert) = server_cert {
            client.add_root_certificate(cert)
        } else {
            client
        };

        Self::with_new_cache(
            client.build().unwrap(),
            server,
            unauthorized_timeout,
            max_secrets_cached,
            ttl_field.map(|s| s.to_string()),
        )
    }

    fn with_new_cache(
        client: Client,
        server: Url,
        unauthorized_timeout: Duration,
        max_secrets_cached: usize,
        ttl_field: Option<String>,
    ) -> Self {
        let client_token: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
        let retained_client_token = Arc::clone(&client_token);

        let retained_client = client.clone();
        let retained_server = server.clone();
        let retained_ttl_field = ttl_field.clone();
        let retained_unauthorized_timeout = unauthorized_timeout;

        let cache: TtlCache = LoadingCache::with_meta_loader(
            TtlCacheBacking::with_backing(
                unauthorized_timeout,
                LruCacheBacking::new(max_secrets_cached),
            ),
            move |secret_path| {
                let task_client_token = Arc::clone(&client_token);

                let task_client = client.clone();
                let task_server = server.clone();
                let task_ttl_field = ttl_field.clone();

                async move {
                    let mut delayer = Delayer::default();
                    loop {
                        increment_counter!("ss_get_secret_requests", SECRET_PATH_LABEL => secret_path.clone());

                        let mut builder = task_client.get(
                            task_server
                                .join(&format!("{task_server}v1/secret/data/{secret_path}"))
                                .unwrap(),
                        );
                        if let Some(client_token) = task_client_token.lock().await.as_deref() {
                            builder = builder.header("X-Vault-Token", client_token)
                        }

                        let result = builder.send().await;
                        match result {
                            Ok(response) => {
                                if response.status() == StatusCode::FORBIDDEN {
                                    increment_counter!("ss_unauthorized", SECRET_PATH_LABEL => secret_path.clone());
                                    break Err(Error::Unauthorized);
                                } else {
                                    let secret_reply = if response.status().is_success() {
                                        response.json::<GetSecretReply>().await.ok()
                                    } else {
                                        debug!(
                                            "Secret store failure status while getting secret: {:?}",
                                            response.status()
                                        );
                                        increment_counter!("ss_other_reply_failures");
                                        None
                                    };
                                    let lease_duration = secret_reply.as_ref().map(|sr| {
                                        let mut lease_duration = None;
                                        if let Some(ttl_field) = task_ttl_field.as_ref() {
                                            if let Some(ttl) = sr.data.data.get(ttl_field) {
                                                if let Ok(ttl_duration) =
                                                    ttl.parse::<humantime::Duration>()
                                                {
                                                    lease_duration = Some(ttl_duration.into());
                                                }
                                            }
                                        }
                                        lease_duration.unwrap_or_else(|| {
                                            Duration::from_secs(sr.lease_duration)
                                        })
                                    });
                                    break Ok(secret_reply)
                                        .with_meta(lease_duration.map(TtlMeta::from));
                                }
                            }
                            Err(e) => {
                                debug!(
                                    "Secret store is unavailable while getting secret. Error: {:?}",
                                    e
                                );
                                increment_counter!("ss_unavailables");
                            }
                        }
                        delayer.delay().await;
                    }
                }
            },
        );

        Self {
            cache,
            client: retained_client,
            client_token: retained_client_token,
            max_secrets_cached,
            ttl_field: retained_ttl_field,
            server: retained_server,
            unauthorized_timeout: retained_unauthorized_timeout,
        }
    }

    pub fn with_new_auth_prepared(ss: &Self) -> Self {
        Self::with_new_cache(
            ss.client.clone(),
            ss.server.clone(),
            ss.unauthorized_timeout,
            ss.max_secrets_cached,
            ss.ttl_field.clone(),
        )
    }
}

#[async_trait]
impl SecretStore for VaultSecretStore {
    async fn approle_auth(
        &self,
        role_id: &str,
        secret_id: &str,
    ) -> Result<AppRoleAuthReply, Error> {
        loop {
            let role_id = role_id.to_string();

            increment_counter!("ss_approle_auth_requests", APPROLE_AUTH_LABEL => role_id.clone());

            let task_client_token = Arc::clone(&self.client_token);
            let result = self
                .client
                .post(
                    self.server
                        .join(&format!("{}v1/auth/approle/login", self.server))
                        .unwrap(),
                )
                .json(&AppRoleAuthRequest {
                    role_id: role_id.to_string(),
                    secret_id: secret_id.to_string(),
                })
                .send()
                .await;
            match result {
                Ok(response) => {
                    if response.status() == StatusCode::FORBIDDEN {
                        increment_counter!("ss_unauthorized", APPROLE_AUTH_LABEL => role_id.clone());
                        break Err(Error::Unauthorized);
                    } else {
                        let secret_reply = if response.status().is_success() {
                            let approle_auth_reply = response
                                .json::<AppRoleAuthReply>()
                                .await
                                .map_err(|_| Error::Unauthorized);
                            if let Ok(r) = &approle_auth_reply {
                                let mut client_token = task_client_token.lock().await;
                                *client_token = Some(r.auth.client_token.clone());
                            }
                            approle_auth_reply
                        } else {
                            debug!(
                                "Secret store failure status while authenticating: {:?}",
                                response.status()
                            );
                            increment_counter!("ss_other_reply_failures", APPROLE_AUTH_LABEL => role_id.clone());
                            Err(Error::Unauthorized)
                        };
                        break secret_reply;
                    }
                }
                Err(e) => {
                    debug!(
                        "Secret store is unavailable while authenticating. Error: {:?}",
                        e
                    );
                    increment_counter!("ss_unavailables");
                }
            }
        }
    }

    async fn create_secret(
        &self,
        _secret_path: &str,
        _secret_data: SecretData,
    ) -> Result<(), Error> {
        todo!()
    }

    async fn get_secret(&self, secret_path: &str) -> Result<Option<GetSecretReply>, Error> {
        self.cache
            .get(secret_path.to_owned())
            .await
            .map_err(|e| e.as_loading_error().unwrap().clone()) // Unsure how we can deal with caching issues
    }

    async fn userpass_auth(
        &self,
        username: &str,
        password: &str,
    ) -> Result<UserPassAuthReply, Error> {
        let username = username.to_string();

        increment_counter!("ss_userpass_auth_requests", USERPASS_AUTH_LABEL => username.clone());

        let task_client_token = Arc::clone(&self.client_token);
        let result = self
            .client
            .post(
                self.server
                    .join(&format!(
                        "{}v1/auth/userpass/login/{}",
                        self.server, username
                    ))
                    .unwrap(),
            )
            .json(&UserPassAuthRequest {
                password: password.to_string(),
            })
            .send()
            .await;
        match result {
            Ok(response) => {
                if response.status() == StatusCode::FORBIDDEN {
                    increment_counter!("ss_unauthorized", USERPASS_AUTH_LABEL => username.clone());
                    Err(Error::Unauthorized)
                } else if response.status().is_success() {
                    let userpass_auth_reply = response
                        .json::<UserPassAuthReply>()
                        .await
                        .map_err(|_| Error::Unauthorized);
                    if let Ok(r) = &userpass_auth_reply {
                        let mut client_token = task_client_token.lock().await;
                        *client_token = Some(r.auth.client_token.clone());
                    }
                    userpass_auth_reply
                } else {
                    debug!(
                        "Secret store failure status while authenticating: {:?}",
                        response.status()
                    );
                    increment_counter!("ss_other_reply_failures", USERPASS_AUTH_LABEL => username.clone());
                    Err(Error::Unauthorized)
                }
            }
            Err(e) => {
                debug!(
                    "Secret store is unavailable while authenticating. Error: {:?}",
                    e
                );
                increment_counter!("ss_unavailables");
                Err(Error::Unauthorized)
            }
        }
    }

    async fn token_auth(&self, _token: &str) -> Result<(), Error> {
        todo!()
    }

    async fn userpass_create_update_user(
        &self,
        current_username: &str,
        username: &str,
        password: &str,
    ) -> Result<(), Error> {
        let username = username.to_string();

        increment_counter!("ss_userpass_create_updates", USERPASS_CREATE_UPDATE_LABEL => username.clone());

        let mut builder = self
            .client
            .post(
                self.server
                    .join(&format!(
                        "{}v1/auth/userpass/users/{}",
                        self.server, current_username
                    ))
                    .unwrap(),
            )
            .json(&UserPassCreateUpdateRequest {
                username: username.to_string(),
                password: password.to_string(),
            });
        if let Some(client_token) = self.client_token.lock().await.as_deref() {
            builder = builder.header("X-Vault-Token", client_token)
        }

        let result = builder.send().await;
        match result {
            Ok(response) => {
                if response.status() == StatusCode::FORBIDDEN {
                    increment_counter!("ss_unauthorized", USERPASS_CREATE_UPDATE_LABEL => username.clone());
                    Err(Error::Unauthorized)
                } else if response.status().is_success() {
                    let _ = response.json::<()>().await.map_err(|_| Error::Unauthorized);
                    Ok(())
                } else {
                    debug!(
                        "Secret store failure status while creating/updating userpass: {:?}",
                        response.status()
                    );
                    increment_counter!("ss_other_reply_failures", USERPASS_CREATE_UPDATE_LABEL => username.clone());
                    Err(Error::Unauthorized)
                }
            }
            Err(e) => {
                debug!(
                    "Secret store is unavailable while creating/updating userpass. Error: {:?}",
                    e
                );
                increment_counter!("ss_unavailables");
                Err(Error::Unauthorized)
            }
        }
    }
}