Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(authentication_service): support doppler secrets sync (#3796)

Will Hutchinsonde905304c183
diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yaml
index 07e8989dcb..e29aab885d 100644
--- a/infra/stacks/authentication-service/Pulumi.dev.yaml
+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml
@@ -27,3 +27,4 @@ config:
authentication-service:posthog_host: https://us.i.posthog.com
authentication-service:posthog_api_key: posthog-api-key
authentication-service:doppler_token_key: doppler-token-authentication-service-dev
+ authentication-service:doppler_secret_sync_key: /doppler/authentication-service/dev
diff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yaml
index 8d314fd194..7666ca0315 100644
--- a/infra/stacks/authentication-service/Pulumi.prod.yaml
+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml
@@ -26,3 +26,5 @@ config:
authentication-service:meta_access_token: meta-access-token
authentication-service:posthog_host: https://us.i.posthog.com
authentication-service:posthog_api_key: posthog-api-key
+ authentication-service:doppler_token_key: doppler-token-authentication-service-prod
+ authentication-service:doppler_secret_sync_key: /doppler/authentication-service/prod
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.ts
index 84476456a1..ef3bb0ccdc 100644
--- a/infra/stacks/authentication-service/index.ts
+++ b/infra/stacks/authentication-service/index.ts
@@ -23,6 +23,12 @@ const dopplerTokenArn: pulumi.Output<string> = aws.secretsmanager
.getSecretVersionOutput({ secretId: config.require('doppler_token_key') })
.apply((secret) => secret.arn);
+const dopplerSecretSyncArn: pulumi.Output<string> = aws.secretsmanager
+ .getSecretVersionOutput({
+ secretId: config.require('doppler_secret_sync_key'),
+ })
+ .apply((secret) => secret.arn);
+
const DATABASE_URL = aws.secretsmanager
.getSecretVersionOutput({
secretId: config.require(`macro_db_secret_key`),
@@ -158,6 +164,10 @@ const service = new AuthenticationService('authentication-service', {
name: 'DOPPLER_TOKEN',
valueFrom: pulumi.interpolate`${dopplerTokenArn}`,
},
+ {
+ name: 'APP_SECRETS_JSON',
+ valueFrom: pulumi.interpolate`${dopplerSecretSyncArn}`,
+ },
],
});
diff --git a/infra/stacks/authentication-service/service.ts b/infra/stacks/authentication-service/service.ts
index fb99a3a448..622e530264 100644
--- a/infra/stacks/authentication-service/service.ts
+++ b/infra/stacks/authentication-service/service.ts
@@ -45,6 +45,7 @@ type Args = {
export class AuthenticationService extends pulumi.ComponentResource {
public role: aws.iam.Role;
+ public executionRole: aws.iam.Role;
public ecr: awsx.ecr.Repository;
public serviceAlbSg: aws.ec2.SecurityGroup;
public serviceSg: aws.ec2.SecurityGroup;
@@ -121,6 +122,24 @@ export class AuthenticationService extends pulumi.ComponentResource {
{ parent: this }
);
+ const executionSecretsPolicy = new aws.iam.Policy(
+ `${BASE_NAME}-execution-secrets-policy`,
+ {
+ policy: {
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Action: ['secretsmanager:GetSecretValue'],
+ Resource: containerSecrets.map((s) => s.valueFrom),
+ Effect: 'Allow',
+ },
+ ],
+ },
+ tags: this.tags,
+ },
+ { parent: this }
+ );
+
const sesPolicy = new aws.iam.Policy(
`${BASE_NAME}-ses-policy`,
{
@@ -146,29 +165,35 @@ export class AuthenticationService extends pulumi.ComponentResource {
{ parent: this }
);
+ const ecsTaskAssumeRolePolicy = aws.iam.assumeRolePolicyForPrincipal({
+ Service: 'ecs-tasks.amazonaws.com',
+ });
+
this.role = new aws.iam.Role(
`${BASE_NAME}-role`,
{
name: `${BASE_NAME}-role-${stack}`,
- assumeRolePolicy: {
- Version: '2012-10-17',
- Statement: [
- {
- Action: 'sts:AssumeRole',
- Principal: {
- Service: 'ecs-tasks.amazonaws.com',
- },
- Effect: 'Allow',
- Sid: '',
- },
- ],
- },
+ assumeRolePolicy: ecsTaskAssumeRolePolicy,
tags: this.tags,
managedPolicyArns: [secretsPolicy.arn, sesPolicy.arn, queuePolicy.arn],
},
{ parent: this }
);
+ this.executionRole = new aws.iam.Role(
+ `${BASE_NAME}-execution-role`,
+ {
+ name: `${BASE_NAME}-execution-role-${stack}`,
+ assumeRolePolicy: ecsTaskAssumeRolePolicy,
+ tags: this.tags,
+ managedPolicyArns: [
+ 'arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy',
+ executionSecretsPolicy.arn,
+ ],
+ },
+ { parent: this }
+ );
+
// ecr image
const image = new EcrImage(
`${BASE_NAME}-ecr-image-${stack}`,
@@ -228,6 +253,9 @@ export class AuthenticationService extends pulumi.ComponentResource {
taskRole: {
roleArn: this.role.arn,
},
+ executionRole: {
+ roleArn: this.executionRole.arn,
+ },
containers: {
log_router: fargateLogRouterSidecarContainer,
datadog_agent: datadogAgentContainer,
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 6c3f97f0bf..427890ae4f 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -6542,6 +6542,7 @@ name = "macro_env_var"
version = "0.1.0"
dependencies = [
"paste",
+ "serde_json",
"thiserror 2.0.18",
"tracing",
]
diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rs
index 211bc368e4..3276580824 100644
--- a/rust/cloud-storage/authentication_service/src/config.rs
+++ b/rust/cloud-storage/authentication_service/src/config.rs
@@ -1,6 +1,8 @@
use std::sync::LazyLock;
+use anyhow::Context;
pub use macro_env::Environment;
+use macro_service_urls::DocumentStorageServiceUrl;
// BASE_URL env var. This is validated when creating the config in main.rs
pub static BASE_URL: LazyLock<String> = LazyLock::new(|| std::env::var("BASE_URL").unwrap());
@@ -12,8 +14,6 @@ pub static BASE_URL: LazyLock<String> = LazyLock::new(|| std::env::var("BASE_URL
/// populate the Docker container
///
/// See `.env.sample` in document-storage-service root for details.
-#[derive(serde::Deserialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
#[allow(dead_code)]
pub base_url: String,
@@ -51,6 +51,9 @@ pub struct Config {
/// The internal auth key used by other services
pub service_internal_auth_key: String,
+ /// The document storage service url
+ pub document_storage_service_url: String,
+
/// The notification queue
pub notification_queue: String,
@@ -92,3 +95,122 @@ pub struct Config {
/// The stripe price id
pub stripe_price_id: String,
}
+
+/// Grab the stripe product price id using the environment
+fn get_stripe_price_id_from_environment(environment: Environment) -> String {
+ // SAFETY: stripe price ids are not sensitive information so hard coding them here is simpler
+ match environment {
+ Environment::Production => "price_1TZY5FJaD7zvQeOBMldBpUHg".to_string(),
+ Environment::Develop | Environment::Local => "price_1TZY5uJaD7zvQeOBRu9a5v8P".to_string(),
+ }
+}
+
+impl Config {
+ pub fn from_env() -> anyhow::Result<Self> {
+ let base_url = std::env::var("BASE_URL").context("BASE_URL must be provided")?;
+ let database_url =
+ std::env::var("DATABASE_URL").context("DATABASE_URL must be provided")?;
+
+ let redis_uri = std::env::var("REDIS_URI").context("REDIS_URI must be provided")?;
+
+ let fusionauth_tenant_id = std::env::var("FUSIONAUTH_TENANT_ID")
+ .context("FUSIONAUTH_TENANT_ID must be provided")?;
+ let fusionauth_api_key_secret_key = std::env::var("FUSIONAUTH_API_KEY_SECRET_KEY")
+ .context("FUSIONAUTH_API_KEY_SECRET_KEY must be provided")?;
+ let fusionauth_client_id = std::env::var("FUSIONAUTH_CLIENT_ID")
+ .context("FUSIONAUTH_CLIENT_ID must be provided")?;
+ let fusionauth_client_secret_key = std::env::var("FUSIONAUTH_CLIENT_SECRET_KEY")
+ .context("FUSIONAUTH_CLIENT_SECRET_KEY must be provided")?;
+ let fusionauth_base_url =
+ std::env::var("FUSIONAUTH_BASE_URL").context("FUSIONAUTH_BASE_URL must be provided")?;
+ let fusionauth_oauth_redirect_uri = std::env::var("FUSIONAUTH_OAUTH_REDIRECT_URI")
+ .context("FUSIONAUTH_OAUTH_REDIRECT_URI must be provided")?;
+ let google_client_id =
+ std::env::var("GOOGLE_CLIENT_ID").context("GOOGLE_CLIENT_ID must be provided")?;
+ let google_client_secret_key = std::env::var("GOOGLE_CLIENT_SECRET_KEY")
+ .context("GOOGLE_CLIENT_SECRET_KEY must be provided")?;
+
+ let stripe_secret_key =
+ std::env::var("STRIPE_SECRET_KEY").context("STRIPE_SECRET_KEY must be provided")?;
+
+ let service_internal_auth_key = std::env::var("SERVICE_INTERNAL_AUTH_KEY")
+ .context("SERVICE_INTERNAL_AUTH_KEY environment variable not set")?;
+
+ let port: usize = std::env::var("PORT")
+ .unwrap_or("8080".to_string())
+ .parse::<usize>()
+ .context("should be valid port number")?;
+
+ let environment = Environment::new_or_prod();
+
+ let document_storage_service_url = DocumentStorageServiceUrl::new()?.to_string();
+
+ let notification_queue =
+ std::env::var("NOTIFICATION_QUEUE").context("NOTIFICATION_QUEUE must be provided")?;
+
+ let search_event_queue =
+ std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
+
+ let link_manager_queue =
+ std::env::var("LINK_MANAGER_QUEUE").context("LINK_MANAGER_QUEUE must be provided")?;
+
+ let email_backfill_queue = std::env::var("EMAIL_BACKFILL_QUEUE")
+ .context("EMAIL_BACKFILL_QUEUE must be provided")?;
+
+ let github_client_id =
+ std::env::var("GITHUB_CLIENT_ID").context("GITHUB_CLIENT_ID must be provided")?;
+ let github_client_secret = std::env::var("GITHUB_CLIENT_SECRET")
+ .context("GITHUB_CLIENT_SECRET must be provided")?;
+ let github_idp_id =
+ std::env::var("GITHUB_IDP_ID").context("GITHUB_IDP_ID must be provided")?;
+
+ // Google Analytics configuration
+ let ga_measurement_id = std::env::var("GA_MEASUREMENT_ID").ok();
+ let ga_api_secret = std::env::var("GA_API_SECRET").ok();
+
+ // Meta Conversions API configuration
+ let meta_pixel_id = std::env::var("META_PIXEL_ID").ok();
+ let meta_access_token = std::env::var("META_ACCESS_TOKEN").ok();
+ let meta_test_event_code = std::env::var("META_TEST_EVENT_CODE").ok();
+
+ // PostHog configuration
+ let posthog_api_key = std::env::var("POSTHOG_API_KEY").ok();
+ let posthog_host = std::env::var("POSTHOG_HOST").ok();
+
+ let stripe_price_id = get_stripe_price_id_from_environment(environment);
+
+ Ok(Config {
+ base_url,
+ database_url,
+ redis_uri,
+ fusionauth_tenant_id,
+ fusionauth_api_key_secret_key,
+ fusionauth_client_id,
+ fusionauth_client_secret_key,
+ fusionauth_base_url,
+ fusionauth_oauth_redirect_uri,
+ google_client_id,
+ google_client_secret_key,
+ stripe_secret_key,
+ port,
+ service_internal_auth_key,
+ document_storage_service_url,
+ notification_queue,
+ search_event_queue,
+ link_manager_queue,
+ email_backfill_queue,
+ environment,
+ github_client_id,
+ github_client_secret,
+ github_idp_id,
+ ga_measurement_id,
+ ga_api_secret,
+ meta_pixel_id,
+ meta_access_token,
+ meta_test_event_code,
+ posthog_api_key,
+ posthog_host,
+ stripe_price_id,
+ })
+ }
+}
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 43896f596d..22ba2c4d4e 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -20,7 +20,7 @@ use github::{
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
-use macro_service_urls::{AppServiceUrl, DocumentStorageServiceUrl};
+use macro_service_urls::AppServiceUrl;
use native_app_service::{
domain::{models::PlatformData, service::NativeAppServiceImpl},
outbound::DefaultBundleFetcher,
@@ -61,25 +61,9 @@ mod rate_limit_config;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
- // Load in basic env vars
MacroEntrypoint::default().init();
let env = Environment::new_or_prod();
- let doppler = doppler_config::DopplerConfig::builder()
- .prefer_doppler_run_env() // if doppler run command is used, use that
- .fallback_to_env_on_missing_token()
- .project(
- std::env::var("DOPPLER_PROJECT")
- .ok()
- .unwrap_or("authentication_service".to_string()),
- )
- .config(env.to_doppler_slug())
- .token_from_env("DOPPLER_TOKEN")
- .build()?;
-
- let config: Config = doppler.load().await?;
- tracing::trace!("initialized config");
-
let secretsmanager_client = secretsmanager_client::SecretsManager::new(
aws_sdk_secretsmanager::Client::new(&macro_aws_config::get_macro_aws_config().await),
);
@@ -92,6 +76,11 @@ async fn main() -> anyhow::Result<()> {
.get_maybe_secret_value(env, StripeWebhookSecretKey::new()?)
.await?;
+ // Parse our configuration from the environment.
+ let config = Config::from_env().context("expected to be able to generate config")?;
+
+ tracing::trace!("initialized config");
+
let (min_connections, max_connections): (u32, u32) = match config.environment {
Environment::Production => (5, 25),
Environment::Develop => (1, 25),
@@ -166,7 +155,7 @@ async fn main() -> anyhow::Result<()> {
let document_storage_service_client = DocumentStorageServiceClient::new(
config.service_internal_auth_key.clone(),
- DocumentStorageServiceUrl::new()?.to_string(),
+ config.document_storage_service_url.clone(),
);
tracing::trace!("initialized document storage service client");
diff --git a/rust/cloud-storage/macro_env_var/Cargo.toml b/rust/cloud-storage/macro_env_var/Cargo.toml
index 40e8e1e108..644dd01593 100644
--- a/rust/cloud-storage/macro_env_var/Cargo.toml
+++ b/rust/cloud-storage/macro_env_var/Cargo.toml
@@ -9,6 +9,7 @@ test-comptime = []
[dependencies]
paste = { workspace = true }
+serde_json = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
diff --git a/rust/cloud-storage/macro_env_var/src/lib.rs b/rust/cloud-storage/macro_env_var/src/lib.rs
index eff7311c9e..2cb5f29369 100644
--- a/rust/cloud-storage/macro_env_var/src/lib.rs
+++ b/rust/cloud-storage/macro_env_var/src/lib.rs
@@ -2,12 +2,54 @@
pub use paste;
use thiserror::Error;
+const APP_SECRETS_JSON_ENV: &str = "APP_SECRETS_JSON";
+
+fn read_std_env(s: &'static str) -> Result<String, std::env::VarError> {
+ std::env::var(s)
+}
+
+fn read_from_app_secrets_json_with<F>(key: &'static str, read_var: F) -> Option<String>
+where
+ F: Fn(&'static str) -> Result<String, std::env::VarError>,
+{
+ let secrets_json = read_var(APP_SECRETS_JSON_ENV).ok()?;
+ let secrets = serde_json::from_str::<serde_json::Value>(&secrets_json).ok()?;
+ let value = secrets.get(key)?;
+
+ match value {
+ serde_json::Value::String(value) => Some(value.clone()),
+ value => Some(value.to_string()),
+ }
+}
+
+/// Read a value from `APP_SECRETS_JSON` without mutating the process environment.
+pub fn read_from_app_secrets_json(key: &'static str) -> Option<String> {
+ read_from_app_secrets_json_with(key, read_std_env)
+}
+
+fn read_env_with<F>(s: &'static str, read_var: F) -> Result<String, VarNameErr>
+where
+ F: Fn(&'static str) -> Result<String, std::env::VarError>,
+{
+ match read_from_app_secrets_json_with(s, &read_var) {
+ Some(value) => Ok(value),
+ None => read_var(s).map_err(|err| VarNameErr { var_name: s, err }),
+ }
+}
+
+fn maybe_read_env_with<F>(s: &'static str, read_var: F) -> Option<String>
+where
+ F: Fn(&'static str) -> Result<String, std::env::VarError>,
+{
+ read_from_app_secrets_json_with(s, &read_var).or_else(|| read_var(s).ok())
+}
+
#[cfg(test)]
mod tests;
#[cfg(test)]
mod testing_harness {
- use super::VarNameErr;
+ use super::{VarNameErr, maybe_read_env_with, read_env_with};
use std::cell::Cell;
type MockValue = Cell<Option<Box<dyn Fn(&'static str) -> Result<String, std::env::VarError>>>>;
@@ -15,7 +57,15 @@ mod testing_harness {
static MOCK_VAR_GETTER: MockValue = const { Cell::new(None) };
}
- pub fn read_env(s: &'static str) -> Result<String, VarNameErr> {
+ struct MockEnvGuard;
+
+ impl Drop for MockEnvGuard {
+ fn drop(&mut self) {
+ MOCK_VAR_GETTER.replace(None);
+ }
+ }
+
+ fn get_env(s: &'static str) -> Result<String, std::env::VarError> {
let cur_getter = MOCK_VAR_GETTER.replace(None);
match cur_getter {
Some(mock) => {
@@ -25,19 +75,14 @@ mod testing_harness {
}
None => std::env::var(s),
}
- .map_err(|err| VarNameErr { var_name: s, err })
+ }
+
+ pub fn read_env(s: &'static str) -> Result<String, VarNameErr> {
+ read_env_with(s, get_env)
}
pub fn maybe_read_env(s: &'static str) -> Option<String> {
- let cur_getter = MOCK_VAR_GETTER.replace(None);
- match cur_getter {
- Some(mock) => {
- let out = mock(s).ok();
- MOCK_VAR_GETTER.replace(Some(mock));
- out
- }
- None => std::env::var(s).ok(),
- }
+ maybe_read_env_with(s, get_env)
}
pub(crate) fn with_mock_env<F, Cb, U>(f: F, cb: Cb) -> U
@@ -46,9 +91,8 @@ mod testing_harness {
Cb: FnOnce() -> U,
{
MOCK_VAR_GETTER.replace(Some(Box::new(f)));
- let output = cb();
- MOCK_VAR_GETTER.replace(None);
- output
+ let _guard = MockEnvGuard;
+ cb()
}
}
@@ -59,13 +103,13 @@ pub use testing_harness::read_env;
#[cfg(not(test))]
pub fn read_env(s: &'static str) -> Result<String, VarNameErr> {
- std::env::var(s).map_err(|err| VarNameErr { var_name: s, err })
+ read_env_with(s, read_std_env)
}
/// Read an environment variable, returning `None` if it is not present.
#[cfg(not(test))]
pub fn maybe_read_env(s: &'static str) -> Option<String> {
- std::env::var(s).ok()
+ maybe_read_env_with(s, read_std_env)
}
/// The type of error that is produced by this crate
@@ -246,12 +290,14 @@ macro_rules! env_var {
/// # Example
///
/// ```
+/// use macro_env_var::maybe_env_var;
+///
/// maybe_env_var! {
/// pub struct OptionalApiKey;
/// }
///
/// // Returns None if OPTIONAL_API_KEY is not set
-/// let key: Option<OptionalApiKey> = OptionalApiKey::new();
+/// let _key: Option<OptionalApiKey> = OptionalApiKey::new();
/// ```
#[macro_export]
macro_rules! maybe_env_var {
diff --git a/rust/cloud-storage/macro_env_var/src/tests.rs b/rust/cloud-storage/macro_env_var/src/tests.rs
index c87e274cc7..c20a73e51a 100644
--- a/rust/cloud-storage/macro_env_var/src/tests.rs
+++ b/rust/cloud-storage/macro_env_var/src/tests.rs
@@ -3,6 +3,10 @@ use std::sync::Arc;
use super::*;
+fn mock_no_env(_: &'static str) -> Result<String, std::env::VarError> {
+ Err(std::env::VarError::NotPresent)
+}
+
env_var! {
#[derive(Debug, Clone)]
pub struct TestVar;
@@ -11,15 +15,15 @@ env_var! {
#[test]
fn test_macro_expands_correctly() {
// This test checks that the macro expands without compilation errors
- // The actual environment variable won't exist, so we expect an error
- let result = TestVar::new();
+ // The mocked environment variable won't exist, so we expect an error
+ let result = with_mock_env(mock_no_env, TestVar::new);
assert!(result.is_err());
}
#[test]
#[should_panic(expected = "Failed to find the TEST_VAR variable in environment")]
fn unwrap_does_panic() {
- TestVar::unwrap_new();
+ with_mock_env(mock_no_env, TestVar::unwrap_new);
}
fn mock_test_var(k: &'static str) -> Result<String, std::env::VarError> {
@@ -42,6 +46,86 @@ fn it_should_be_arced() {
assert_eq!(Arc::strong_count(&third), 3);
}
+#[test]
+fn required_env_reads_from_app_secrets_json_when_key_exists() {
+ let value = with_mock_env(
+ |k| match k {
+ "APP_SECRETS_JSON" => Ok(r#"{"FOO":"from-json"}"#.to_string()),
+ "FOO" => Ok("from-env".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || read_env("FOO"),
+ )
+ .unwrap();
+
+ assert_eq!(value, "from-json");
+}
+
+#[test]
+fn required_env_falls_back_to_env_when_json_is_missing() {
+ let value = with_mock_env(
+ |k| match k {
+ "FOO" => Ok("from-env".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || read_env("FOO"),
+ )
+ .unwrap();
+
+ assert_eq!(value, "from-env");
+}
+
+#[test]
+fn required_env_falls_back_to_env_when_json_is_invalid() {
+ let value = with_mock_env(
+ |k| match k {
+ "APP_SECRETS_JSON" => Ok("not json".to_string()),
+ "FOO" => Ok("from-env".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || read_env("FOO"),
+ )
+ .unwrap();
+
+ assert_eq!(value, "from-env");
+}
+
+#[test]
+fn required_env_falls_back_to_env_when_key_is_missing_from_json() {
+ let value = with_mock_env(
+ |k| match k {
+ "APP_SECRETS_JSON" => Ok(r#"{"BAR":"from-json"}"#.to_string()),
+ "FOO" => Ok("from-env".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || read_env("FOO"),
+ )
+ .unwrap();
+
+ assert_eq!(value, "from-env");
+}
+
+#[test]
+fn required_env_returns_error_when_neither_source_contains_key() {
+ let result = with_mock_env(mock_no_env, || read_env("FOO"));
+
+ assert!(result.is_err());
+}
+
+#[test]
+fn required_env_converts_non_string_app_secrets_json_values() {
+ let (count, enabled) = with_mock_env(
+ |k| match k {
+ "APP_SECRETS_JSON" => Ok(r#"{"COUNT":1,"ENABLED":true}"#.to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || (read_env("COUNT").unwrap(), read_env("ENABLED").unwrap()),
+ );
+
+ assert_eq!(count, "1");
+ assert_eq!(enabled, "true");
+}
+
env_var! {
#[derive(Debug, Clone)]
pub struct Config {
@@ -55,8 +139,8 @@ env_var! {
#[test]
fn test_struct_with_fields() {
// This test verifies that structs with fields that implement EnvVar work correctly
- // The environment variables won't exist, so we expect an error
- let result = Config::new();
+ // The mocked environment variables won't exist, so we expect an error
+ let result = with_mock_env(mock_no_env, Config::new);
assert!(result.is_err());
}
@@ -80,7 +164,7 @@ fn test_struct_with_fields_mock() {
#[test]
#[should_panic]
fn it_should_panic() {
- Config::unwrap_new();
+ with_mock_env(mock_no_env, Config::unwrap_new);
}
// Tests for maybe_env_var! macro
@@ -92,7 +176,7 @@ maybe_env_var! {
#[test]
fn maybe_env_var_returns_none_when_not_set() {
- let result = MaybeTestVar::new();
+ let result = with_mock_env(mock_no_env, MaybeTestVar::new);
assert!(result.is_none());
}
@@ -117,6 +201,40 @@ fn maybe_env_var_can_be_arced() {
assert_eq!(Arc::strong_count(&third), 3);
}
+#[test]
+fn optional_env_returns_some_from_app_secrets_json_when_key_exists() {
+ let value = with_mock_env(
+ |k| match k {
+ "APP_SECRETS_JSON" => Ok(r#"{"FOO":"from-json"}"#.to_string()),
+ "FOO" => Ok("from-env".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || maybe_read_env("FOO"),
+ );
+
+ assert_eq!(value.as_deref(), Some("from-json"));
+}
+
+#[test]
+fn optional_env_falls_back_to_env_when_json_is_missing() {
+ let value = with_mock_env(
+ |k| match k {
+ "FOO" => Ok("from-env".to_string()),
+ _ => Err(std::env::VarError::NotPresent),
+ },
+ || maybe_read_env("FOO"),
+ );
+
+ assert_eq!(value.as_deref(), Some("from-env"));
+}
+
+#[test]
+fn optional_env_returns_none_when_neither_source_contains_key() {
+ let value = with_mock_env(mock_no_env, || maybe_read_env("FOO"));
+
+ assert_eq!(value, None);
+}
+
maybe_env_var! {
#[derive(Debug, Clone)]
pub struct MaybeConfig {
@@ -129,7 +247,7 @@ maybe_env_var! {
#[test]
fn maybe_struct_with_fields_all_none() {
- let config = MaybeConfig::new();
+ let config = with_mock_env(mock_no_env, MaybeConfig::new);
assert!(config.maybe_db_url.is_none());
assert!(config.maybe_api_secret.is_none());
}