Skip to main content

schedr_agent/
vault.rs

1//! The Vault secret storage (see archive/PROJECT.md, Secret storage): KV v2 reads of a mount, with
2//! a token from the environment or Vault's Kubernetes auth (the pod's service-account token). The
3//! agent's own token is renewed before it expires; with Kubernetes auth, an expired or refused one
4//! is replaced by logging in again, once per read. Values that aren't strings are read as their
5//! JSON text (decision 171).
6//!
7//! A token never reaches a log, an error or a `Debug` print.
8
9use std::fmt::{self, Write as _};
10use std::path::PathBuf;
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12use std::sync::{Arc, Mutex as StdMutex, Weak};
13use std::time::{Duration, Instant};
14
15use reqwest::{Client, StatusCode};
16use serde_json::Value;
17use tokio::sync::Mutex;
18
19use crate::secrets::{ReadFuture, SecretData, SecretError, SecretStorage};
20
21#[cfg(test)]
22mod tests;
23
24/// A token is renewed when this part of its time to live has passed.
25const RENEW_AT: f64 = 2.0 / 3.0;
26
27/// The shortest wait between two renewals (a token with a very short time to live).
28const MIN_RENEW_WAIT: Duration = Duration::from_secs(1);
29
30/// How the agent logs in to Vault.
31#[derive(Clone, PartialEq, Eq)]
32pub enum VaultAuth {
33    /// A token given to the agent (`SCHEDR_CONFIG__SECRET_STORAGE__<NAME>__TOKEN`).
34    Token(String),
35    /// Vault's Kubernetes auth method: the pod's service-account token for a Vault token.
36    Kubernetes {
37        /// The Vault role.
38        role: String,
39        /// The auth method's mount (`kubernetes`).
40        mount: String,
41        /// The service-account token's file.
42        jwt_file: PathBuf,
43    },
44}
45
46impl fmt::Debug for VaultAuth {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Self::Token(_) => f.write_str("Token(****)"),
50            Self::Kubernetes {
51                role,
52                mount,
53                jwt_file,
54            } => f
55                .debug_struct("Kubernetes")
56                .field("role", role)
57                .field("mount", mount)
58                .field("jwt_file", jwt_file)
59                .finish(),
60        }
61    }
62}
63
64/// How a Vault token is kept renewed.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct VaultRenewal {
67    /// A renewal never comes sooner than this (`vault_min_renew_wait`).
68    pub min_wait: Duration,
69    /// How often a session with nothing to renew is looked at again (`vault_renew_check`).
70    pub check: Duration,
71    /// How soon a failed renewal is tried again (`vault_renew_retry`).
72    pub retry: Duration,
73}
74
75impl Default for VaultRenewal {
76    /// 1 s, a minute and 10 s.
77    fn default() -> Self {
78        Self {
79            min_wait: MIN_RENEW_WAIT,
80            check: Duration::from_mins(1),
81            retry: Duration::from_secs(10),
82        }
83    }
84}
85
86/// One Vault storage's settings.
87#[derive(Debug, Clone)]
88pub struct VaultSettings {
89    /// Vault's address, `https://vault.example.com:8200`.
90    pub address: String,
91    /// The KV v2 mount (`secret`).
92    pub mount: String,
93    /// The Vault Enterprise namespace, if any.
94    pub namespace: Option<String>,
95    /// The CA certificates (PEM) Vault's certificate is checked against, instead of the
96    /// system's.
97    pub ca_cert: Option<Vec<u8>>,
98    /// How the agent logs in.
99    pub auth: VaultAuth,
100    /// How long one request may take.
101    pub request_timeout: Duration,
102    /// How long connecting may take.
103    pub connect_timeout: Duration,
104    /// How a token is kept renewed.
105    pub renewal: VaultRenewal,
106}
107
108/// The agent's Vault token and when to renew it.
109struct Session {
110    token: String,
111    /// When to renew it; `None`: it doesn't expire, or can't be renewed.
112    renew_at: Option<Instant>,
113    /// When it expires; `None`: never.
114    expires: Option<Instant>,
115}
116
117impl fmt::Debug for Session {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.debug_struct("Session")
120            .field("token", &"****")
121            .field("renew_at", &self.renew_at)
122            .field("expires", &self.expires)
123            .finish()
124    }
125}
126
127/// The last login's failure, for the reads that waited on it.
128#[derive(Debug, Default)]
129struct Logins {
130    failed: Option<SecretError>,
131}
132
133/// A Vault KV v2 mount, read with the agent's own token.
134///
135/// The session is held only to copy or replace it, never across a call to Vault: a read
136/// doesn't wait for a renewal while the token is still good. Logins go one at a time
137/// (`logins`); the reads waiting on one that fails get its error, not a login each.
138#[derive(Debug)]
139pub struct VaultStorage {
140    client: Client,
141    settings: VaultSettings,
142    session: StdMutex<Option<Session>>,
143    logins: Mutex<Logins>,
144    /// How many logins were tried (succeeded or not).
145    tried: AtomicU64,
146    /// Itself, for the renewal task (which ends once the storage is dropped).
147    me: Weak<Self>,
148    /// Whether the renewal task runs.
149    renewing: AtomicBool,
150}
151
152impl VaultStorage {
153    /// The storage; nothing is sent to Vault until the first read.
154    ///
155    /// # Errors
156    ///
157    /// When the CA certificate doesn't read or the HTTP client can't be made.
158    pub fn new(settings: VaultSettings) -> Result<Arc<Self>, String> {
159        let mut builder = Client::builder()
160            .timeout(settings.request_timeout)
161            .connect_timeout(settings.connect_timeout)
162            // A redirect would carry the token or the login's JWT elsewhere; Vault's own
163            // clients follow none either. A 3xx is an answer like any other (unavailable).
164            .redirect(reqwest::redirect::Policy::none());
165        if let Some(pem) = &settings.ca_cert {
166            let certs = reqwest::Certificate::from_pem_bundle(pem)
167                .map_err(|e| format!("the Vault CA certificate doesn't read: {e}"))?;
168            builder = builder.tls_certs_only(certs);
169        }
170        let client = builder
171            .build()
172            .map_err(|e| format!("no HTTP client for Vault: {e}"))?;
173        Ok(Arc::new_cyclic(|me| Self {
174            client,
175            settings,
176            session: StdMutex::new(None),
177            logins: Mutex::new(Logins::default()),
178            tried: AtomicU64::new(0),
179            me: me.clone(),
180            renewing: AtomicBool::new(false),
181        }))
182    }
183
184    fn url(&self, path: &str) -> String {
185        format!("{}/v1/{path}", self.settings.address.trim_end_matches('/'))
186    }
187
188    fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder {
189        let request = self.client.request(method, self.url(path));
190        match &self.settings.namespace {
191            Some(namespace) => request.header("X-Vault-Namespace", namespace),
192            None => request,
193        }
194    }
195
196    fn session(&self) -> std::sync::MutexGuard<'_, Option<Session>> {
197        // A panic while holding it left a whole value: nothing to repair.
198        self.session
199            .lock()
200            .unwrap_or_else(std::sync::PoisonError::into_inner)
201    }
202
203    /// The current token, while it lasts.
204    fn current(&self) -> Option<String> {
205        self.session()
206            .as_ref()
207            .filter(|s| s.expires.is_none_or(|at| Instant::now() < at))
208            .map(|s| s.token.clone())
209    }
210
211    /// The token to read with: the current one, or a new one.
212    async fn token(&self) -> Result<String, SecretError> {
213        if let Some(token) = self.current() {
214            return Ok(token);
215        }
216        let tried = self.tried.load(Ordering::SeqCst);
217        let mut logins = self.logins.lock().await;
218        // Another read logged in meanwhile, or failed to: its outcome is this one's.
219        if let Some(token) = self.current() {
220            return Ok(token);
221        }
222        if self.tried.load(Ordering::SeqCst) != tried
223            && let Some(error) = &logins.failed
224        {
225            return Err(error.clone());
226        }
227        let token = self.log_in_now(&mut logins).await?;
228        drop(logins);
229        self.start_renewing();
230        Ok(token)
231    }
232
233    /// Logs in (the caller holds `logins`) and keeps the new session.
234    async fn log_in_now(&self, logins: &mut Logins) -> Result<String, SecretError> {
235        let outcome = self.log_in().await;
236        self.tried.fetch_add(1, Ordering::SeqCst);
237        match outcome {
238            Ok(fresh) => {
239                logins.failed = None;
240                let token = fresh.token.clone();
241                *self.session() = Some(fresh);
242                Ok(token)
243            }
244            Err(error) => {
245                logins.failed = Some(error.clone());
246                Err(error)
247            }
248        }
249    }
250
251    /// A new session: the given token looked up, or a Kubernetes login.
252    async fn log_in(&self) -> Result<Session, SecretError> {
253        match &self.settings.auth {
254            VaultAuth::Token(token) => {
255                let response = self
256                    .request(reqwest::Method::GET, "auth/token/lookup-self")
257                    .header("X-Vault-Token", token)
258                    .send()
259                    .await
260                    .map_err(unreachable)?;
261                let body = answer(response, "the token's lookup").await?;
262                let ttl = body["data"]["ttl"].as_u64().unwrap_or(0);
263                let renewable = body["data"]["renewable"].as_bool().unwrap_or(false);
264                Ok(self::session(
265                    token.clone(),
266                    ttl,
267                    renewable,
268                    self.settings.renewal,
269                ))
270            }
271            VaultAuth::Kubernetes {
272                role,
273                mount,
274                jwt_file,
275            } => {
276                let jwt = tokio::fs::read_to_string(jwt_file).await.map_err(|e| {
277                    SecretError::Denied(format!(
278                        "Vault's Kubernetes login: can't read the service-account token {}: {e}",
279                        jwt_file.display()
280                    ))
281                })?;
282                let response = self
283                    .request(reqwest::Method::POST, &format!("auth/{mount}/login"))
284                    .json(&serde_json::json!({"role": role, "jwt": jwt.trim()}))
285                    .send()
286                    .await
287                    .map_err(unreachable)?;
288                let body = answer(response, "the Kubernetes login").await?;
289                let auth = &body["auth"];
290                let token = auth["client_token"].as_str().ok_or_else(|| {
291                    SecretError::Unavailable(
292                        "Vault's Kubernetes login answered without a token".to_owned(),
293                    )
294                })?;
295                let ttl = auth["lease_duration"].as_u64().unwrap_or(0);
296                let renewable = auth["renewable"].as_bool().unwrap_or(false);
297                Ok(self::session(
298                    token.to_owned(),
299                    ttl,
300                    renewable,
301                    self.settings.renewal,
302                ))
303            }
304        }
305    }
306
307    /// Starts the task renewing the token, once.
308    fn start_renewing(&self) {
309        if self.renewing.swap(true, Ordering::SeqCst) {
310            return;
311        }
312        let me = self.me.clone();
313        let check = self.settings.renewal.check;
314        tokio::spawn(async move {
315            loop {
316                let Some(storage) = me.upgrade() else { return };
317                let renew_at = storage.session().as_ref().and_then(|s| s.renew_at);
318                drop(storage);
319                let Some(renew_at) = renew_at else {
320                    // Nothing to renew until a new session: checked again later.
321                    tokio::time::sleep(check).await;
322                    continue;
323                };
324                tokio::time::sleep_until(renew_at.into()).await;
325                let Some(storage) = me.upgrade() else { return };
326                storage.renew().await;
327            }
328        });
329    }
330
331    /// Renews the token; on failure, logs in again (Kubernetes auth) or keeps it until it
332    /// expires (a given token).
333    async fn renew(&self) {
334        let Some(token) = self.session().as_ref().map(|s| s.token.clone()) else {
335            return;
336        };
337        let renewed = self
338            .request(reqwest::Method::POST, "auth/token/renew-self")
339            .header("X-Vault-Token", &token)
340            .json(&serde_json::json!({}))
341            .send()
342            .await
343            .map_err(unreachable);
344        let renewed = match renewed {
345            Ok(response) => answer(response, "the token's renewal").await,
346            Err(error) => Err(error),
347        };
348        match renewed {
349            Ok(body) => {
350                let auth = &body["auth"];
351                let ttl = auth["lease_duration"].as_u64().unwrap_or(0);
352                let renewable = auth["renewable"].as_bool().unwrap_or(false);
353                let mut session = self.session();
354                // Replaced meanwhile (a login after a refused read): that one stays.
355                if session.as_ref().is_some_and(|s| s.token == token) {
356                    *session = Some(self::session(token, ttl, renewable, self.settings.renewal));
357                }
358            }
359            Err(error) => {
360                if let VaultAuth::Kubernetes { .. } = self.settings.auth {
361                    let mut logins = self.logins.lock().await;
362                    match self.log_in_now(&mut logins).await {
363                        Ok(_) => return,
364                        Err(again) => {
365                            tracing::warn!(error = %again, "Vault: no new token");
366                        }
367                    }
368                } else {
369                    tracing::warn!(%error, "Vault: the token wasn't renewed");
370                }
371                // Tried again shortly, while the token lasts.
372                if let Some(current) = self.session().as_mut() {
373                    current.renew_at = Some(Instant::now() + self.settings.renewal.retry);
374                    if current.expires.is_some_and(|at| at <= Instant::now()) {
375                        current.renew_at = None;
376                    }
377                }
378            }
379        }
380    }
381
382    /// Forgets the session (a refused token), so the next read logs in again.
383    fn forget(&self, token: &str) {
384        let mut session = self.session();
385        if session.as_ref().is_some_and(|s| s.token == token) {
386            *session = None;
387        }
388    }
389
390    async fn read_once(&self, path: &str, token: &str) -> Result<SecretData, SecretError> {
391        let mount = &self.settings.mount;
392        let response = self
393            .request(
394                reqwest::Method::GET,
395                &format!("{mount}/data/{}", encode_path(path)),
396            )
397            .header("X-Vault-Token", token)
398            .send()
399            .await
400            .map_err(unreachable)?;
401        let body = answer(response, READ).await?;
402        let data = match &body["data"]["data"] {
403            Value::Object(data) => data,
404            // A deleted or destroyed latest version (Vault answers those with a 404 too).
405            Value::Null if body["data"]["metadata"].is_object() => {
406                return Err(SecretError::NotFound(
407                    "no such secret in Vault (its latest version is deleted)".to_owned(),
408                ));
409            }
410            // Not KV v2's shape (a KV v1 mount, a proxy's JSON): not "no such secret".
411            _ => {
412                return Err(SecretError::Unavailable(format!(
413                    "Vault's answer to the read isn't a KV v2 secret (is `{mount}` a KV v2 mount?)"
414                )));
415            }
416        };
417        Ok(data
418            .iter()
419            .map(|(key, value)| (key.clone(), text(value)))
420            .collect())
421    }
422}
423
424impl SecretStorage for VaultStorage {
425    fn read<'a>(&'a self, path: &'a str) -> ReadFuture<'a> {
426        Box::pin(async move {
427            if path.split('/').any(|part| part == "." || part == "..") {
428                return Err(SecretError::NotFound(
429                    "a Vault path has no `.` or `..` part".to_owned(),
430                ));
431            }
432            let token = self.token().await?;
433            match self.read_once(path, &token).await {
434                // A token revoked or expired early: with Kubernetes auth, a login again.
435                Err(SecretError::Denied(_))
436                    if matches!(self.settings.auth, VaultAuth::Kubernetes { .. }) =>
437                {
438                    self.forget(&token);
439                    let token = self.token().await?;
440                    self.read_once(path, &token).await
441                }
442                result => result,
443            }
444        })
445    }
446}
447
448/// A session for `token`, renewed at [`RENEW_AT`] of `ttl` seconds if `renewable`.
449fn session(token: String, ttl: u64, renewable: bool, renewal: VaultRenewal) -> Session {
450    let now = Instant::now();
451    if ttl == 0 {
452        return Session {
453            token,
454            renew_at: None,
455            expires: None,
456        };
457    }
458    let ttl = Duration::from_secs(ttl);
459    let renew_at = renewable.then(|| now + ttl.mul_f64(RENEW_AT).max(renewal.min_wait));
460    Session {
461        token,
462        renew_at,
463        expires: Some(now + ttl),
464    }
465}
466
467/// A value as text: a string as it is, anything else as its JSON (decision 171).
468fn text(value: &Value) -> String {
469    match value {
470        Value::String(text) => text.clone(),
471        other => other.to_string(),
472    }
473}
474
475/// Each part of a secret path percent-encoded (a part is never `.` or `..`).
476fn encode_path(path: &str) -> String {
477    path.split('/')
478        .map(|part| {
479            let mut out = String::with_capacity(part.len());
480            for byte in part.bytes() {
481                if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
482                    out.push(char::from(byte));
483                } else {
484                    let _ = write!(out, "%{byte:02X}");
485                }
486            }
487            out
488        })
489        .collect::<Vec<_>>()
490        .join("/")
491}
492
493fn unreachable(error: reqwest::Error) -> SecretError {
494    // Without the URL: it holds the path, which is fine, but the error says enough.
495    SecretError::Unavailable(format!("Vault is unreachable: {}", error.without_url()))
496}
497
498/// What a secret's read is called in messages (and how `answer` knows one).
499const READ: &str = "the read";
500
501/// The JSON body of a success; otherwise the error its status means, with Vault's messages.
502async fn answer(response: reqwest::Response, what: &str) -> Result<Value, SecretError> {
503    let status = response.status();
504    let body = response.json::<Value>().await;
505    if status.is_success() {
506        // Not JSON (a proxy's page, a cut answer): Vault isn't answering, which isn't "no
507        // such secret".
508        return body.map_err(|e| {
509            SecretError::Unavailable(format!(
510                "Vault answered {what} ({status}) with no JSON: {}",
511                e.without_url()
512            ))
513        });
514    }
515    // Vault's own refusals are JSON (`{"errors": [...]}`); anything else came from elsewhere.
516    let from_vault = body.as_ref().is_ok_and(Value::is_object);
517    let body = body.unwrap_or(Value::Null);
518    let errors: Vec<&str> = body["errors"]
519        .as_array()
520        .map(|list| list.iter().filter_map(Value::as_str).collect())
521        .unwrap_or_default();
522    let detail = if errors.is_empty() {
523        String::new()
524    } else {
525        format!(": {}", errors.join("; "))
526    };
527    let message = format!("Vault refused {what} ({status}){detail}");
528    Err(match status {
529        // Only Vault's own: a proxy's 404 page isn't "no such secret" (a fallback would
530        // stand in for a secret that may well be there).
531        StatusCode::NOT_FOUND if what == READ && from_vault => {
532            SecretError::NotFound(format!("no such secret in Vault ({status})"))
533        }
534        // Not a secret's path: a login's or a lookup's (a wrong auth mount), which no retry
535        // mends.
536        StatusCode::NOT_FOUND if what == READ => SecretError::Unavailable(message),
537        StatusCode::NOT_FOUND
538        | StatusCode::FORBIDDEN
539        | StatusCode::UNAUTHORIZED
540        | StatusCode::BAD_REQUEST => SecretError::Denied(message),
541        _ => SecretError::Unavailable(message),
542    })
543}