Skip to main content

haste_encryption/providers/
environment.rs

1use haste_fhir_operation_error::OperationOutcomeError;
2use std::{future::Future, pin::Pin};
3
4use crate::{
5    error::EncryptionError,
6    traits::{Secret, SecretsProvider},
7};
8
9/// Reads secrets directly from process environment variables. `name` is
10/// used verbatim as the environment variable name, optionally prefixed.
11pub struct EnvironmentSecretsProvider {
12    prefix: Option<String>,
13}
14
15impl EnvironmentSecretsProvider {
16    pub fn new(prefix: Option<String>) -> Self {
17        Self { prefix }
18    }
19
20    fn env_var_name(&self, name: &str) -> String {
21        match &self.prefix {
22            Some(prefix) => format!("{prefix}{name}"),
23            None => name.to_string(),
24        }
25    }
26}
27
28impl SecretsProvider for EnvironmentSecretsProvider {
29    fn get_secret<'a>(
30        &'a self,
31        name: &'a str,
32    ) -> Pin<Box<dyn Future<Output = Result<Secret, OperationOutcomeError>> + Send + 'a>> {
33        Box::pin(async move {
34            let env_var_name = self.env_var_name(name);
35
36            let value = std::env::var(&env_var_name).map_err(|e| {
37                EncryptionError::SecretRetrievalFailed(name.to_string(), e.to_string())
38            })?;
39
40            Ok(Secret::new(value.into_bytes()))
41        })
42    }
43}