Skip to main content

schedr_bin/
secret_storage.rs

1//! `[secret_storage]` made into the agent's storages, per role (see archive/PROJECT.md, Secret
2//! storage): standalone always has the `db` storage (its default when nothing else is
3//! configured); a worker in a distributed deployment has only what is configured (Vault), and
4//! never `db` (it has no database connection, and a secret never passes through the master).
5
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9use schedr_agent::secrets::{DbStorage, SecretStores, Storage};
10use schedr_config::config::{SecretStorageSection, SecretStorageType};
11use schedr_config::loader::DB_STORAGE;
12use schedr_db::Database;
13use schedr_db::secrets::SecretKey;
14
15use crate::app::AppError;
16
17#[cfg(test)]
18mod tests;
19
20/// The storages to make once the role knows whether it has a database: the configuration and
21/// `SCHEDR_SECRET_KEY`, or why there is none.
22#[derive(Debug, Clone)]
23pub struct SecretPlan {
24    section: SecretStorageSection,
25    renewal: schedr_agent::vault::VaultRenewal,
26    key: Result<SecretKey, String>,
27    /// Storages given whole instead (`dags test --secret`: values in memory).
28    given: Option<Arc<SecretStores>>,
29}
30
31impl SecretPlan {
32    /// The plan from the configuration and the environment (the key read now: the environment
33    /// isn't kept).
34    #[must_use]
35    pub fn new(section: &SecretStorageSection, env: &BTreeMap<String, String>) -> Self {
36        Self {
37            section: section.clone(),
38            renewal: schedr_agent::vault::VaultRenewal::default(),
39            key: SecretKey::from_env(env).map_err(|e| e.to_string()),
40            given: None,
41        }
42    }
43
44    /// The plan, Vault tokens renewed as `timings` say.
45    #[must_use]
46    pub const fn renewing(mut self, timings: &schedr_config::config::Timings) -> Self {
47        self.renewal = schedr_agent::vault::VaultRenewal {
48            min_wait: timings.vault_min_renew_wait,
49            check: timings.vault_renew_check,
50            retry: timings.vault_renew_retry,
51        };
52        self
53    }
54
55    /// These storages, whatever is configured (a test run's values in memory).
56    #[must_use]
57    pub fn given(mut self, stores: SecretStores) -> Self {
58        self.given = Some(Arc::new(stores));
59        self
60    }
61
62    /// The storages a role runs with: the given ones, else [`Self::stores`]'s.
63    ///
64    /// # Errors
65    ///
66    /// As [`Self::stores`].
67    pub fn for_role(&self, db: Option<&Database>) -> Result<Arc<SecretStores>, AppError> {
68        match &self.given {
69            Some(stores) => Ok(stores.clone()),
70            None => self.stores(db).map(Arc::new),
71        }
72    }
73
74    /// The storages: with `db` (the standalone's own database) when there is one, else a
75    /// worker's.
76    ///
77    /// # Errors
78    ///
79    /// [`AppError::BadArgument`] for a `db` storage, or `default = "db"`, without a database
80    /// (a worker in a distributed deployment).
81    pub fn stores(&self, db: Option<&Database>) -> Result<SecretStores, AppError> {
82        let mut storages = BTreeMap::new();
83        for (name, configured) in &self.section.storages {
84            let storage: Arc<dyn schedr_agent::secrets::SecretStorage> = match configured.kind {
85                SecretStorageType::Db => {
86                    let db =
87                        db.ok_or_else(|| standalone_only(&format!("[secret_storage.{name}]")))?;
88                    Arc::new(DbStorage::with_key(db.clone(), self.key.clone()))
89                }
90                SecretStorageType::Vault => vault(name, configured, self.renewal)?,
91            };
92            storages.insert(
93                name.clone(),
94                Storage {
95                    storage,
96                    cache_ttl: configured.cache_ttl,
97                    unmasked_prefixes: configured.unmasked_prefixes.clone(),
98                },
99            );
100        }
101        let configured = storages.len();
102        if let Some(db) = db
103            && !storages.contains_key(DB_STORAGE)
104        {
105            let storage = DbStorage::with_key(db.clone(), self.key.clone());
106            storages.insert(DB_STORAGE.to_owned(), Storage::new(Arc::new(storage)));
107        }
108        let default = match &self.section.default {
109            Some(default) if default == DB_STORAGE && db.is_none() => {
110                return Err(standalone_only("[secret_storage] default = \"db\""));
111            }
112            Some(default) => Some(default.clone()),
113            // The only one configured; else standalone's own (several without a default are
114            // refused when the configuration loads, decision 172).
115            None if configured == 1 => self.section.storages.keys().next().cloned(),
116            None if db.is_some() => Some(DB_STORAGE.to_owned()),
117            None => None,
118        };
119        SecretStores::new(storages, default, self.section.min_mask_length)
120            .map_err(AppError::BadArgument)
121    }
122}
123
124/// The service account's token file, where Kubernetes mounts it.
125const SERVICE_ACCOUNT_TOKEN: &str = "/var/run/secrets/kubernetes.io/serviceaccount/token";
126
127/// A Vault storage from its table (the loader checked its fields; nothing is sent to Vault
128/// until a read).
129fn vault(
130    name: &str,
131    configured: &schedr_config::config::SecretStorageConfig,
132    renewal: schedr_agent::vault::VaultRenewal,
133) -> Result<Arc<dyn schedr_agent::secrets::SecretStorage>, AppError> {
134    use schedr_agent::vault::{VaultAuth, VaultSettings, VaultStorage};
135    use schedr_config::config::VaultAuthMethod;
136    let bad = |what: String| AppError::BadArgument(format!("[secret_storage.{name}] {what}"));
137    let address = configured
138        .address
139        .clone()
140        .ok_or_else(|| bad("needs `address`".to_owned()))?;
141    let auth = configured
142        .auth
143        .as_ref()
144        .ok_or_else(|| bad("needs `auth`".to_owned()))?;
145    let auth = match auth.method {
146        VaultAuthMethod::Token => VaultAuth::Token(configured.token.clone().unwrap_or_default()),
147        VaultAuthMethod::Kubernetes => VaultAuth::Kubernetes {
148            role: auth.role.clone().unwrap_or_default(),
149            mount: auth
150                .mount
151                .clone()
152                .unwrap_or_else(|| "kubernetes".to_owned()),
153            jwt_file: auth
154                .token_file
155                .clone()
156                .unwrap_or_else(|| SERVICE_ACCOUNT_TOKEN.into()),
157        },
158    };
159    let ca_cert = match &configured.ca_cert {
160        Some(path) => Some(
161            std::fs::read(path)
162                .map_err(|e| bad(format!("ca_cert: can't read {}: {e}", path.display())))?,
163        ),
164        None => None,
165    };
166    let settings = VaultSettings {
167        address,
168        mount: configured
169            .mount
170            .clone()
171            .unwrap_or_else(|| "secret".to_owned()),
172        namespace: configured.namespace.clone(),
173        ca_cert,
174        auth,
175        request_timeout: configured.request_timeout,
176        connect_timeout: configured.connect_timeout,
177        renewal,
178    };
179    let storage = VaultStorage::new(settings).map_err(bad)?;
180    Ok(storage)
181}
182
183fn standalone_only(what: &str) -> AppError {
184    AppError::BadArgument(format!(
185        "{what}: the `db` secret storage is standalone's only (a worker has no database \
186         connection, and secrets never pass through the master); use Vault, and move the \
187         secrets there with `schedr secrets export`"
188    ))
189}