Skip to main content

secrets_rs/
source.rs

1use std::collections::HashMap;
2
3use crate::error::SourceError;
4
5/// A source from which secret values can be retrieved.
6///
7/// Implementations are responsible for looking up a secret by `name` and
8/// returning its raw bytes. Case sensitivity of `name` is source-specific.
9pub trait Source: Send + Sync {
10    /// Retrieve the raw bytes for the secret identified by `name`.
11    fn get(&self, name: &str) -> Result<Vec<u8>, SourceError>;
12}
13
14/// A registry that maps source IDs to their [`Source`] implementations.
15///
16/// Pass a populated registry to [`Secret::bind`](crate::Secret::bind) or
17/// [`bind_all`](crate::bind_all) to resolve secrets.
18pub struct SourceRegistry {
19    sources: HashMap<String, Box<dyn Source>>,
20}
21
22impl SourceRegistry {
23    /// Creates an empty registry.
24    pub fn new() -> Self {
25        Self {
26            sources: HashMap::new(),
27        }
28    }
29
30    /// Registers a source under the given `id`.
31    ///
32    /// The `id` must match the `source_id` component of the secret URN.
33    pub fn register(&mut self, id: impl Into<String>, source: impl Source + 'static) {
34        self.sources.insert(id.into(), Box::new(source));
35    }
36
37    /// Returns the source registered under `source_id`, if any.
38    pub fn get(&self, source_id: &str) -> Option<&dyn Source> {
39        self.sources.get(source_id).map(|s| s.as_ref())
40    }
41}
42
43impl Default for SourceRegistry {
44    fn default() -> Self {
45        Self::new()
46    }
47}