1use 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
27pub const DEFAULT_MIN_MASK_LENGTH: usize = 5;
30
31pub const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(60);
33
34#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
36pub enum SecretError {
37 #[error("{0}")]
39 Unavailable(String),
40 #[error("{0}")]
42 Denied(String),
43 #[error("{0}")]
45 NotFound(String),
46}
47
48impl SecretError {
49 #[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 #[must_use]
61 pub fn about(self, name: &SecretName) -> Self {
62 self.within(&format!("`{name}`"))
63 }
64
65 #[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
77pub type SecretData = BTreeMap<String, String>;
79
80pub type ReadFuture<'a> =
82 Pin<Box<dyn Future<Output = Result<SecretData, SecretError>> + Send + 'a>>;
83
84pub trait SecretStorage: Send + Sync + fmt::Debug {
86 fn read<'a>(&'a self, path: &'a str) -> ReadFuture<'a>;
92}
93
94#[derive(Debug, Clone, Default, PartialEq, Eq)]
97pub struct MemoryStorage {
98 secrets: BTreeMap<String, SecretData>,
99}
100
101impl MemoryStorage {
102 #[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 pub fn parse(spec: &str) -> Result<(SecretName, String), String> {
121 let (name, value) = spec
122 .split_once('=')
123 .ok_or_else(|| "a secret is `path#key=value`".to_owned())?;
125 let (path, key) = name
126 .split_once('#')
127 .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#[derive(Debug, Clone)]
149pub struct DbStorage {
150 db: schedr_db::Database,
151 key: Result<schedr_db::secrets::SecretKey, String>,
153}
154
155impl DbStorage {
156 #[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 #[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 #[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 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#[derive(Debug, Clone)]
202pub struct Storage {
203 pub storage: Arc<dyn SecretStorage>,
205 pub cache_ttl: Duration,
207 pub unmasked_prefixes: Vec<String>,
209}
210
211impl Storage {
212 #[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#[derive(Debug, Default)]
226pub struct SecretStores {
227 storages: BTreeMap<String, Storage>,
228 default: Option<String>,
229 any_name: bool,
232 pub min_mask_length: usize,
234 test_connections: BTreeMap<String, BTreeMap<String, Value>>,
237 cache: Arc<Mutex<Cache>>,
240}
241
242type Cache = BTreeMap<(String, String), (Instant, SecretData)>;
244
245impl SecretStores {
246 #[must_use]
248 pub fn none() -> Self {
249 Self {
250 min_mask_length: DEFAULT_MIN_MASK_LENGTH,
251 ..Self::default()
252 }
253 }
254
255 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 #[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 #[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 #[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 #[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 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 #[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 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 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
425pub enum ConnectionError {
426 #[error("{0}")]
428 NotFound(String),
429 #[error("{0}")]
431 Denied(String),
432 #[error("{0}")]
434 Secret(SecretError),
435 #[error("{0}")]
437 Render(String),
438}
439
440impl ConnectionError {
441 #[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#[derive(Debug)]
456pub struct AttemptSecrets {
457 stores: Arc<SecretStores>,
458 declared: Vec<SecretDecl>,
459 connections: Arc<Registry>,
461 declared_connections: Vec<String>,
463 connection_dir: Option<PathBuf>,
466 fetched: Mutex<BTreeMap<SecretName, Value>>,
467 pub mask: Arc<MaskSet>,
469 failed: Mutex<Option<&'static str>>,
472 pub too_short: Mutex<Vec<SecretName>>,
474}
475
476impl AttemptSecrets {
477 #[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 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 #[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 #[must_use]
523 pub fn with_connection_dir(mut self, dir: PathBuf) -> Self {
524 self.connection_dir = Some(dir);
525 self
526 }
527
528 pub async fn connection_env(
536 &self,
537 name: &str,
538 prefix: &str,
539 ) -> Result<BTreeMap<String, String>, ConnectionError> {
540 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 return Err(ConnectionError::Render(format!(
556 "connection `{name}`: its values aren't an object of parameters"
557 )));
558 };
559 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 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 #[must_use]
577 pub fn has_connections(&self) -> bool {
578 !self.declared_connections.is_empty()
579 }
580
581 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 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 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 .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 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 (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 #[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 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 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 #[must_use]
748 pub fn failed_kind(&self) -> Option<&'static str> {
749 *self.failed.lock().unwrap_or_else(PoisonError::into_inner)
750 }
751
752 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}