Skip to main content

schedr_agent/
secrets.rs

1//! Secret storages on the worker, and the secrets of one attempt (see archive/PROJECT.md, Secret
2//! storage).
3//!
4//! The agent fetches every secret an attempt names or declares before its process starts
5//! ([`AttemptSecrets::fetch`]); a secret under a declared prefix is fetched when the task
6//! reads it. The master never sees a value. Each fetched value is masked in the task's log
7//! and output ([`crate::mask`]).
8
9use std::collections::BTreeMap;
10use std::fmt;
11use std::future::Future;
12use std::path::PathBuf;
13use std::pin::Pin;
14use std::sync::{Arc, Mutex, PoisonError};
15use std::time::{Duration, Instant};
16
17use schedr_model::connection::Registry;
18use schedr_model::{SecretDecl, SecretName};
19use serde_json::Value;
20
21use crate::mask::MaskSet;
22use crate::render::{RenderContext, resolve_value};
23
24#[cfg(test)]
25mod tests;
26
27/// The default `[secret_storage] min_mask_length`: shorter values aren't masked (masking `1`
28/// or `true` would mangle the logs), like Airflow's `min_length_masked_secret`.
29pub const DEFAULT_MIN_MASK_LENGTH: usize = 5;
30
31/// The default `cache_ttl` of a storage: how long a fetched secret is kept in memory.
32pub const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(60);
33
34/// Why a secret can't be read: the attempt's error kind follows from it.
35#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36pub enum SecretError {
37    /// The storage is unreachable, timed out, or failed (usually temporary: retried).
38    #[error("{0}")]
39    Unavailable(String),
40    /// Permission denied (a configuration error: not retried).
41    #[error("{0}")]
42    Denied(String),
43    /// No such path or key (usually a typo or a missing secret: not retried).
44    #[error("{0}")]
45    NotFound(String),
46}
47
48impl SecretError {
49    /// The attempt's error kind (`Finished.error_kind`), which decides the retry.
50    #[must_use]
51    pub const fn kind(&self) -> &'static str {
52        match self {
53            Self::Unavailable(_) => "secret_unavailable",
54            Self::Denied(_) => "secret_denied",
55            Self::NotFound(_) => "secret_not_found",
56        }
57    }
58
59    /// The same error with `name` in front of its message.
60    #[must_use]
61    pub fn about(self, name: &SecretName) -> Self {
62        self.within(&format!("`{name}`"))
63    }
64
65    /// The same error, of the same kind, with `what` in front of its message.
66    #[must_use]
67    pub fn within(self, what: &str) -> Self {
68        let named = |message: String| format!("{what}: {message}");
69        match self {
70            Self::Unavailable(m) => Self::Unavailable(named(m)),
71            Self::Denied(m) => Self::Denied(named(m)),
72            Self::NotFound(m) => Self::NotFound(named(m)),
73        }
74    }
75}
76
77/// A secret as a storage holds it: its keys and their values (a Vault KV v2 secret).
78pub type SecretData = BTreeMap<String, String>;
79
80/// A future a storage's read returns.
81pub type ReadFuture<'a> =
82    Pin<Box<dyn Future<Output = Result<SecretData, SecretError>> + Send + 'a>>;
83
84/// A kind of secret storage (Vault, the `db` storage, values in memory).
85pub trait SecretStorage: Send + Sync + fmt::Debug {
86    /// The whole secret at `path`.
87    ///
88    /// # Errors
89    ///
90    /// A [`SecretError`] when it can't be read.
91    fn read<'a>(&'a self, path: &'a str) -> ReadFuture<'a>;
92}
93
94/// Secrets held in memory: `schedr dags test --secret` and `run_dag(secrets=...)` (tests and
95/// local runs), never a production storage.
96#[derive(Debug, Clone, Default, PartialEq, Eq)]
97pub struct MemoryStorage {
98    secrets: BTreeMap<String, SecretData>,
99}
100
101impl MemoryStorage {
102    /// Values by `path#key`.
103    #[must_use]
104    pub fn new(values: impl IntoIterator<Item = (SecretName, String)>) -> Self {
105        let mut secrets: BTreeMap<String, SecretData> = BTreeMap::new();
106        for (name, value) in values {
107            secrets
108                .entry(name.path)
109                .or_default()
110                .insert(name.key.unwrap_or_default(), value);
111        }
112        Self { secrets }
113    }
114
115    /// Reads `path#key=value` (as `--secret` takes it).
116    ///
117    /// # Errors
118    ///
119    /// Why it isn't one: no `=`, no `#key`, or a bad path or key.
120    pub fn parse(spec: &str) -> Result<(SecretName, String), String> {
121        let (name, value) = spec
122            .split_once('=')
123            // Not quoted back: without its `=` it may be the value alone (B210).
124            .ok_or_else(|| "a secret is `path#key=value`".to_owned())?;
125        let (path, key) = name
126            .split_once('#')
127            // Not quoted either: a value alone may hold `=` (base64's padding).
128            .ok_or_else(|| "name the key: `path#key=value`".to_owned())?;
129        let name = SecretName::new(path, Some(key));
130        name.check()?;
131        Ok((name, value.to_owned()))
132    }
133}
134
135impl SecretStorage for MemoryStorage {
136    fn read<'a>(&'a self, path: &'a str) -> ReadFuture<'a> {
137        Box::pin(async move {
138            self.secrets
139                .get(path)
140                .cloned()
141                .ok_or_else(|| SecretError::NotFound("no such secret".to_owned()))
142        })
143    }
144}
145
146/// The `db` storage (standalone): the `secrets` table of schedr's own database, each value
147/// decrypted under `SCHEDR_SECRET_KEY` (see `schedr_db::secrets`).
148#[derive(Debug, Clone)]
149pub struct DbStorage {
150    db: schedr_db::Database,
151    /// The key, or why there is none (every read then fails, saying so).
152    key: Result<schedr_db::secrets::SecretKey, String>,
153}
154
155impl DbStorage {
156    /// The storage on `db`, with the key from `env`: without one it still starts (a
157    /// deployment that reads no secret needs none), and each read says what is missing.
158    #[must_use]
159    pub fn new(db: schedr_db::Database, env: &BTreeMap<String, String>) -> Self {
160        let key = schedr_db::secrets::SecretKey::from_env(env).map_err(|e| e.to_string());
161        Self { db, key }
162    }
163
164    /// The storage on `db` with `key`, or why there is none.
165    #[must_use]
166    pub const fn with_key(
167        db: schedr_db::Database,
168        key: Result<schedr_db::secrets::SecretKey, String>,
169    ) -> Self {
170        Self { db, key }
171    }
172
173    /// Whether the key is there (for a warning at startup when it isn't).
174    #[must_use]
175    pub fn key_problem(&self) -> Option<&str> {
176        self.key.as_ref().err().map(String::as_str)
177    }
178}
179
180impl SecretStorage for DbStorage {
181    fn read<'a>(&'a self, path: &'a str) -> ReadFuture<'a> {
182        Box::pin(async move {
183            // A configuration problem: retrying won't help.
184            let key = self
185                .key
186                .as_ref()
187                .map_err(|e| SecretError::Denied(e.clone()))?;
188            match self.db.secret(key, path).await {
189                Ok(Some(data)) => Ok(data),
190                Ok(None) => Err(SecretError::NotFound("no such secret".to_owned())),
191                Err(error @ schedr_db::secrets::SecretsError::Decrypt(_)) => {
192                    Err(SecretError::Denied(error.to_string()))
193                }
194                Err(error) => Err(SecretError::Unavailable(format!("the database: {error}"))),
195            }
196        })
197    }
198}
199
200/// One configured storage, with what is said about it.
201#[derive(Debug, Clone)]
202pub struct Storage {
203    /// The storage.
204    pub storage: Arc<dyn SecretStorage>,
205    /// How long a fetched secret is kept in memory; zero: not kept.
206    pub cache_ttl: Duration,
207    /// Paths whose values aren't masked (non-secret configuration, `unmasked_prefixes`).
208    pub unmasked_prefixes: Vec<String>,
209}
210
211impl Storage {
212    /// A storage with the default cache and every value masked.
213    #[must_use]
214    pub fn new(storage: Arc<dyn SecretStorage>) -> Self {
215        Self {
216            storage,
217            cache_ttl: DEFAULT_CACHE_TTL,
218            unmasked_prefixes: Vec::new(),
219        }
220    }
221}
222
223/// The worker's secret storages: each by name, the default one, and a cache of what was
224/// fetched (in memory only, never on disk).
225#[derive(Debug, Default)]
226pub struct SecretStores {
227    storages: BTreeMap<String, Storage>,
228    default: Option<String>,
229    /// For a test run: these storages answer for every name a DAG uses (`--secret` values
230    /// are named by `path#key`, whatever storage the DAG reads them from).
231    any_name: bool,
232    /// `[secret_storage] min_mask_length`.
233    pub min_mask_length: usize,
234    /// For a test run: connections' values given in place of rendering them (`dags test
235    /// --connection`, `run_dag(connections=...)`), by connection and parameter, stored JSON.
236    test_connections: BTreeMap<String, BTreeMap<String, Value>>,
237    /// What was fetched, by storage and path, with when it expires; an entry is dropped when
238    /// it expires, whether or not anything reads again.
239    cache: Arc<Mutex<Cache>>,
240}
241
242/// The fetched secrets by storage and path, each with when it expires.
243type Cache = BTreeMap<(String, String), (Instant, SecretData)>;
244
245impl SecretStores {
246    /// No storages: every secret is "not found".
247    #[must_use]
248    pub fn none() -> Self {
249        Self {
250            min_mask_length: DEFAULT_MIN_MASK_LENGTH,
251            ..Self::default()
252        }
253    }
254
255    /// The storages by name, `default` the one an unnamed secret comes from.
256    ///
257    /// # Errors
258    ///
259    /// When `default` isn't one of them.
260    pub fn new(
261        storages: BTreeMap<String, Storage>,
262        default: Option<String>,
263        min_mask_length: usize,
264    ) -> Result<Self, String> {
265        if let Some(name) = &default
266            && !storages.contains_key(name)
267        {
268            return Err(format!(
269                "[secret_storage] default = \"{name}\" isn't a configured storage"
270            ));
271        }
272        Ok(Self {
273            storages,
274            default,
275            any_name: false,
276            min_mask_length,
277            test_connections: BTreeMap::new(),
278            cache: Arc::default(),
279        })
280    }
281
282    /// The same storages, read without the cache (`schedr connections check` / `test`): a
283    /// secret just fixed is what they see, not the value cached for the tasks.
284    #[must_use]
285    pub fn uncached(&self) -> Self {
286        Self {
287            storages: self
288                .storages
289                .iter()
290                .map(|(name, storage)| {
291                    let mut storage = storage.clone();
292                    storage.cache_ttl = Duration::ZERO;
293                    (name.clone(), storage)
294                })
295                .collect(),
296            default: self.default.clone(),
297            any_name: self.any_name,
298            min_mask_length: self.min_mask_length,
299            test_connections: self.test_connections.clone(),
300            cache: Arc::default(),
301        }
302    }
303
304    /// Values in memory standing for every storage (a test run: `dags test --secret`).
305    #[must_use]
306    pub fn for_test(values: impl SecretStorage + 'static) -> Self {
307        let mut storage = Storage::new(Arc::new(values));
308        storage.cache_ttl = Duration::ZERO;
309        Self {
310            storages: BTreeMap::from([("test".to_owned(), storage)]),
311            default: Some("test".to_owned()),
312            any_name: true,
313            min_mask_length: DEFAULT_MIN_MASK_LENGTH,
314            test_connections: BTreeMap::new(),
315            cache: Arc::default(),
316        }
317    }
318
319    /// The same stores, with connections' values for a test run, given instead of rendered.
320    #[must_use]
321    pub fn with_test_connections(
322        mut self,
323        connections: BTreeMap<String, BTreeMap<String, Value>>,
324    ) -> Self {
325        self.test_connections = connections;
326        self
327    }
328
329    /// The configured storages' names (reported in `Register`; the master checks DAGs
330    /// against them). A test run reports none: it answers for any.
331    #[must_use]
332    pub fn names(&self) -> Vec<String> {
333        if self.any_name {
334            return Vec::new();
335        }
336        self.storages.keys().cloned().collect()
337    }
338
339    /// The storage `name` comes from, with its configured name.
340    pub(crate) fn storage_of(&self, name: &SecretName) -> Result<(&str, &Storage), SecretError> {
341        let wanted = match (&name.storage, self.any_name) {
342            (Some(storage), false) => storage.as_str(),
343            (None, false) | (_, true) => self.default.as_deref().ok_or_else(|| {
344                SecretError::NotFound(
345                    "this worker has no default secret storage (`[secret_storage] default`)"
346                        .to_owned(),
347                )
348            })?,
349        };
350        self.storages
351            .get_key_value(wanted)
352            .map(|(name, storage)| (name.as_str(), storage))
353            .ok_or_else(|| {
354                SecretError::NotFound(format!(
355                    "no secret storage `{wanted}` on this worker (`[secret_storage.{wanted}]`)"
356                ))
357            })
358    }
359
360    /// Whether `name`'s value is masked (not under its storage's `unmasked_prefixes`).
361    #[must_use]
362    pub fn masked(&self, name: &SecretName) -> bool {
363        self.storage_of(name).is_ok_and(|(_, storage)| {
364            !storage
365                .unmasked_prefixes
366                .iter()
367                .any(|prefix| name.path.starts_with(prefix.as_str()))
368        })
369    }
370
371    /// The value `name` stands for: a key's value as a string, a whole secret as an object.
372    ///
373    /// # Errors
374    ///
375    /// A [`SecretError`] naming the secret.
376    pub async fn fetch(&self, name: &SecretName) -> Result<Value, SecretError> {
377        let data = self.read(name).await.map_err(|e| e.about(name))?;
378        match &name.key {
379            None => Ok(Value::Object(
380                data.into_iter()
381                    .map(|(k, v)| (k, Value::String(v)))
382                    .collect(),
383            )),
384            Some(key) => data.get(key).cloned().map(Value::String).ok_or_else(|| {
385                SecretError::NotFound(format!("`{name}`: the secret has no key `{key}`"))
386            }),
387        }
388    }
389
390    async fn read(&self, name: &SecretName) -> Result<SecretData, SecretError> {
391        let (storage_name, storage) = self.storage_of(name)?;
392        let key = (storage_name.to_owned(), name.path.clone());
393        let ttl = storage.cache_ttl;
394        if !ttl.is_zero() {
395            let cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
396            if let Some((expires, data)) = cache.get(&key)
397                && Instant::now() < *expires
398            {
399                return Ok(data.clone());
400            }
401        }
402        let data = storage.storage.read(&name.path).await?;
403        if !ttl.is_zero() {
404            let expires = Instant::now() + ttl;
405            let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
406            cache.retain(|_, (at, _)| Instant::now() < *at);
407            cache.insert(key, (expires, data.clone()));
408            // Dropped when it expires, not at the next fetch: a value isn't kept in memory
409            // longer than `cache_ttl` (a weak handle: the stores may be gone by then).
410            let cache = Arc::downgrade(&self.cache);
411            tokio::spawn(async move {
412                tokio::time::sleep_until(expires.into()).await;
413                if let Some(cache) = cache.upgrade() {
414                    let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
415                    cache.retain(|_, (at, _)| Instant::now() < *at);
416                }
417            });
418        }
419        Ok(data)
420    }
421}
422
423/// Why a connection can't be opened (decision 174): the attempt's error kind follows.
424#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
425pub enum ConnectionError {
426    /// Not in the root's registry: not defined, defined twice, or invalid.
427    #[error("{0}")]
428    NotFound(String),
429    /// Not in the task's `connections=` (decision 179).
430    #[error("{0}")]
431    Denied(String),
432    /// A secret it names can't be read.
433    #[error("{0}")]
434    Secret(SecretError),
435    /// A value can't be rendered (a whole secret in a t-string).
436    #[error("{0}")]
437    Render(String),
438}
439
440impl ConnectionError {
441    /// The attempt's error kind (`Finished.error_kind`), which decides the retry.
442    #[must_use]
443    pub const fn kind(&self) -> &'static str {
444        match self {
445            Self::NotFound(_) => schedr_model::runner::CONNECTION_NOT_FOUND,
446            Self::Denied(_) => schedr_model::runner::CONNECTION_DENIED,
447            Self::Secret(error) => error.kind(),
448            Self::Render(_) => crate::attempt::RENDER_FAILED,
449        }
450    }
451}
452
453/// The secrets of one attempt: what was fetched before it started, what it declares, and
454/// the values masked in its log and output.
455#[derive(Debug)]
456pub struct AttemptSecrets {
457    stores: Arc<SecretStores>,
458    declared: Vec<SecretDecl>,
459    /// Its root's connections (decision 174), from which those it declares are rendered.
460    connections: Arc<Registry>,
461    /// The connections it declares (`connections=`, decision 179): the only ones it opens.
462    declared_connections: Vec<String>,
463    /// The attempt's folder for its connections' files (decision 190); `None`: none given
464    /// to a command as variables.
465    connection_dir: Option<PathBuf>,
466    fetched: Mutex<BTreeMap<SecretName, Value>>,
467    /// The values masked in the task's log and output (grows with on-demand reads).
468    pub mask: Arc<MaskSet>,
469    /// The error kind of the last on-demand read that failed (decision 168): a failed
470    /// attempt gets it.
471    failed: Mutex<Option<&'static str>>,
472    /// Secrets too short to be masked, for the log's warning.
473    pub too_short: Mutex<Vec<SecretName>>,
474}
475
476impl AttemptSecrets {
477    /// No secrets (a task that names none).
478    #[must_use]
479    pub fn none(stores: Arc<SecretStores>) -> Self {
480        let min = stores.min_mask_length;
481        Self {
482            stores,
483            declared: Vec::new(),
484            connections: Arc::default(),
485            declared_connections: Vec::new(),
486            connection_dir: None,
487            fetched: Mutex::default(),
488            mask: Arc::new(MaskSet::new(min)),
489            failed: Mutex::default(),
490            too_short: Mutex::default(),
491        }
492    }
493
494    /// Fetches every secret `needed` (named in the task's references or declared) before the
495    /// task starts.
496    ///
497    /// # Errors
498    ///
499    /// The first [`SecretError`]: nothing runs with a missing secret.
500    pub async fn fetch(
501        stores: Arc<SecretStores>,
502        needed: &[SecretName],
503        declared: Vec<SecretDecl>,
504    ) -> Result<Self, SecretError> {
505        let mut secrets = Self::none(stores);
506        secrets.declared = declared;
507        for name in needed {
508            secrets.fetch_one(name).await?;
509        }
510        Ok(secrets)
511    }
512
513    /// The same secrets, with the root's connections and those the task declares.
514    #[must_use]
515    pub fn with_connections(mut self, connections: Arc<Registry>, declared: Vec<String>) -> Self {
516        self.connections = connections;
517        self.declared_connections = declared;
518        self
519    }
520
521    /// The same secrets, with the attempt's folder for its connections' files.
522    #[must_use]
523    pub fn with_connection_dir(mut self, dir: PathBuf) -> Self {
524        self.connection_dir = Some(dir);
525        self
526    }
527
528    /// The connection `name` as a command gets it (decisions 184, 190-192): its files written
529    /// in the attempt's folder, and its variables, named `PREFIX_...`.
530    ///
531    /// # Errors
532    ///
533    /// As [`AttemptSecrets::connection`]; a prefix that isn't a variable name's start, a
534    /// value its tool's file can't hold, or a file that can't be written (`render_failed`).
535    pub async fn connection_env(
536        &self,
537        name: &str,
538        prefix: &str,
539    ) -> Result<BTreeMap<String, String>, ConnectionError> {
540        // The prefix and the name are folders: only letters, digits and `_` (`.-` in a name,
541        // never an empty part) get through, whatever sent them.
542        schedr_model::connection::check_prefix(prefix).map_err(ConnectionError::Render)?;
543        schedr_model::TaskId::new(name)
544            .map_err(|e| ConnectionError::Denied(format!("connection `{name}`: {e}")))?;
545        let values = self.connection(name).await?;
546        let Some(attempt_dir) = &self.connection_dir else {
547            return Err(ConnectionError::Render(format!(
548                "connection `{name}`: this attempt has no folder for connection files"
549            )));
550        };
551        let kind = self.connections.get(name).ok().and_then(|def| def.kind);
552        let shown = schedr_model::params::shown(&Value::Object(values.into_iter().collect()));
553        let Value::Object(shown) = shown else {
554            // Parameters are identifiers, never a tag (`$datetime`): kept an error all the same.
555            return Err(ConnectionError::Render(format!(
556                "connection `{name}`: its values aren't an object of parameters"
557            )));
558        };
559        // By connection, then prefix: one connection given twice, or two under one prefix
560        // (the dict form's and `--env`'s), never write over each other's files.
561        let dir = crate::connection_env::folder(&attempt_dir.join(name), prefix);
562        let render =
563            |e: String| ConnectionError::Render(format!("connection `{name}` as {prefix}: {e}"));
564        let view = crate::connection_env::view(kind, &shown, &dir).map_err(render)?;
565        // A password taken out of a secret URL, one escaped for a tool's file: masked as what
566        // it came from is, before anything can print it.
567        for (source, form) in &view.derived {
568            if self.mask.mask_text(source) != *source {
569                self.mask.add(&format!("connection `{name}`"), form);
570            }
571        }
572        crate::connection_env::write(&view, prefix, &dir).map_err(render)
573    }
574
575    /// Whether the task declares connections (their secrets fetched and masked).
576    #[must_use]
577    pub fn has_connections(&self) -> bool {
578        !self.declared_connections.is_empty()
579    }
580
581    /// Renders every connection the task declares, before it starts (decision 179): a
582    /// connection missing from the folder or a secret it can't read fails the attempt before
583    /// any of its code runs, and their secrets are masked from the start.
584    ///
585    /// # Errors
586    ///
587    /// The first [`ConnectionError`].
588    pub async fn open_declared(&self) -> Result<(), ConnectionError> {
589        for name in &self.declared_connections {
590            self.connection(name).await?;
591        }
592        Ok(())
593    }
594
595    /// The values of the connection `name` a running task opens, rendered as stored JSON by
596    /// parameter: its secrets read (masked from then on; a default stands in for a missing
597    /// one, decision 176), its t-strings filled in.
598    ///
599    /// # Errors
600    ///
601    /// [`ConnectionError`]; remembered for the attempt's error kind (decision 168).
602    pub async fn connection(&self, name: &str) -> Result<BTreeMap<String, Value>, ConnectionError> {
603        let result = self.connection_inner(name).await;
604        if let Err(error) = &result {
605            *self.failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(error.kind());
606        }
607        result
608    }
609
610    async fn connection_inner(
611        &self,
612        name: &str,
613    ) -> Result<BTreeMap<String, Value>, ConnectionError> {
614        if !self
615            .declared_connections
616            .iter()
617            .any(|declared| declared == name)
618        {
619            return Err(ConnectionError::Denied(format!(
620                "connection `{name}` isn't declared in the task's `connections=`"
621            )));
622        }
623        // A test run's own values: what the test gives is what the function gets.
624        if let Some(values) = self.stores.test_connections.get(name) {
625            return Ok(values.clone());
626        }
627        let def = self
628            .connections
629            .get(name)
630            .map_err(ConnectionError::NotFound)?;
631        let mut ctx = RenderContext::default();
632        for secret in def.secrets() {
633            let value = self
634                .fetch_one(secret)
635                .await
636                // Its message names the secret already.
637                .map_err(|e| ConnectionError::Secret(e.within(&format!("connection `{name}`"))))?;
638            ctx.secrets.insert(secret.clone(), value);
639        }
640        def.params
641            .iter()
642            .map(|(param, value)| {
643                resolve_value(value, &ctx)
644                    .map(|rendered| (param.clone(), rendered))
645                    .map_err(|e| {
646                        ConnectionError::Render(format!("connection `{name}`, `{param}`: {e}"))
647                    })
648            })
649            .collect()
650    }
651
652    /// A secret the attempt names (in its arguments, or a connection's): fetched already,
653    /// else fetched now and masked. A default stands in for a missing secret or key (decision
654    /// 176): written in the DAG, so not masked.
655    async fn fetch_one(&self, name: &SecretName) -> Result<Value, SecretError> {
656        let known = self
657            .fetched
658            .lock()
659            .unwrap_or_else(PoisonError::into_inner)
660            .get(name)
661            .cloned();
662        if let Some(value) = known {
663            return Ok(value);
664        }
665        let value = match (self.stores.fetch(name).await, &name.default) {
666            // Not for a storage this worker lacks: a configuration error stays one.
667            (Err(SecretError::NotFound(_)), Some(default))
668                if self.stores.storage_of(name).is_ok() =>
669            {
670                Value::String(default.clone())
671            }
672            (value, _) => {
673                let value = value?;
674                self.add_mask(name, &value);
675                value
676            }
677        };
678        self.fetched
679            .lock()
680            .unwrap_or_else(PoisonError::into_inner)
681            .insert(name.clone(), value.clone());
682        Ok(value)
683    }
684
685    /// The values fetched before the start, by name.
686    #[must_use]
687    pub fn fetched(&self) -> BTreeMap<SecretName, Value> {
688        self.fetched
689            .lock()
690            .unwrap_or_else(PoisonError::into_inner)
691            .clone()
692    }
693
694    /// A secret the running task reads (`task-ctx secret get`, `task_ctx.secret(...)`): one
695    /// it declares, fetched before the start, or one under a declared prefix, fetched now.
696    ///
697    /// # Errors
698    ///
699    /// [`SecretError::Denied`] for a secret it doesn't declare; a fetch's error otherwise.
700    /// A failure is remembered for the attempt's error kind (decision 168).
701    pub async fn read(&self, name: &SecretName) -> Result<Value, SecretError> {
702        let result = self.read_inner(name).await;
703        if let Err(error) = &result {
704            *self.failed.lock().unwrap_or_else(PoisonError::into_inner) = Some(error.kind());
705        }
706        result
707    }
708
709    async fn read_inner(&self, name: &SecretName) -> Result<Value, SecretError> {
710        if !self.declared.iter().any(|d| d.covers(name)) {
711            return Err(SecretError::Denied(format!(
712                "`{name}` isn't declared in the task's `secrets=`"
713            )));
714        }
715        let known = self
716            .fetched
717            .lock()
718            .unwrap_or_else(PoisonError::into_inner)
719            .get(name)
720            .cloned();
721        if let Some(value) = known {
722            return Ok(value);
723        }
724        // A key of a whole secret fetched already, whichever declaration covers it.
725        let whole = SecretName {
726            key: None,
727            ..name.clone()
728        };
729        {
730            let fetched = self.fetched.lock().unwrap_or_else(PoisonError::into_inner);
731            if let (Some(Value::Object(keys)), Some(key)) = (fetched.get(&whole), &name.key) {
732                return keys.get(key).cloned().ok_or_else(|| {
733                    SecretError::NotFound(format!("`{name}`: the secret has no key `{key}`"))
734                });
735            }
736        }
737        let value = self.stores.fetch(name).await?;
738        self.add_mask(name, &value);
739        self.fetched
740            .lock()
741            .unwrap_or_else(PoisonError::into_inner)
742            .insert(name.clone(), value.clone());
743        Ok(value)
744    }
745
746    /// The error kind of the last on-demand read that failed, if any.
747    #[must_use]
748    pub fn failed_kind(&self) -> Option<&'static str> {
749        *self.failed.lock().unwrap_or_else(PoisonError::into_inner)
750    }
751
752    /// Masks `value` from now on, unless its storage leaves it unmasked; a value too short
753    /// to mask is noted for the log's warning.
754    fn add_mask(&self, name: &SecretName, value: &Value) {
755        if !self.stores.masked(name) {
756            return;
757        }
758        let values: Vec<&str> = match value {
759            Value::String(text) => vec![text.as_str()],
760            Value::Object(keys) => keys.values().filter_map(Value::as_str).collect(),
761            _ => Vec::new(),
762        };
763        for text in values {
764            if !self.mask.add(&name.to_string(), text) {
765                let mut short = self
766                    .too_short
767                    .lock()
768                    .unwrap_or_else(PoisonError::into_inner);
769                if !short.contains(name) {
770                    short.push(name.clone());
771                }
772            }
773        }
774    }
775}