Skip to main content

nautilus_core/
env.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Cross-platform environment variable utilities.
17//!
18//! This module provides functions for safely accessing environment variables
19//! with proper error handling.
20
21/// Returns the value of the environment variable for the given `key`.
22///
23/// # Errors
24///
25/// Returns an error if the environment variable is not set or is not valid Unicode.
26pub fn get_env_var(key: &str) -> anyhow::Result<String> {
27    match std::env::var(key) {
28        Ok(var) => Ok(var),
29        Err(std::env::VarError::NotPresent) => {
30            anyhow::bail!("environment variable '{key}' must be set")
31        }
32        Err(std::env::VarError::NotUnicode(_)) => {
33            anyhow::bail!("environment variable '{key}' is not valid Unicode")
34        }
35    }
36}
37
38/// Returns the provided `value` if `Some`, otherwise falls back to reading
39/// the environment variable for the given `key`.
40///
41/// Only attempts to read the environment variable when `value` is `None`,
42/// avoiding unnecessary environment variable lookups and errors.
43///
44/// # Errors
45///
46/// Returns an error if `value` is `None` and the environment variable is not set.
47pub fn get_or_env_var(value: Option<String>, key: &str) -> anyhow::Result<String> {
48    match value {
49        Some(v) => Ok(v),
50        None => get_env_var(key),
51    }
52}
53
54/// Returns the provided `value` if `Some`, otherwise falls back to reading
55/// the environment variable for the given `key`.
56///
57/// Unlike [`get_or_env_var`], this function returns `None` instead of an error
58/// when the environment variable is not set. Use this for optional credentials
59/// where missing values are acceptable (e.g., public-only API clients).
60#[must_use]
61pub fn get_or_env_var_opt(value: Option<String>, key: &str) -> Option<String> {
62    value.or_else(|| std::env::var(key).ok())
63}
64
65/// Resolves a key/secret pair from provided values or environment variables.
66///
67/// Returns `Some((key, secret))` when both are available,
68/// `None` otherwise.
69#[must_use]
70pub fn resolve_env_var_pair(
71    key: Option<String>,
72    secret: Option<String>,
73    key_var: &str,
74    secret_var: &str,
75) -> Option<(String, String)> {
76    let key = get_or_env_var_opt(key, key_var)?;
77    let secret = get_or_env_var_opt(secret, secret_var)?;
78    Some((key, secret))
79}
80
81#[cfg(test)]
82mod tests {
83    use rstest::*;
84
85    use super::*;
86
87    #[rstest]
88    fn test_get_env_var_success() {
89        // Test with a commonly available environment variable
90        if let Ok(path) = std::env::var("PATH") {
91            let result = get_env_var("PATH");
92            assert!(result.is_ok());
93            assert_eq!(result.unwrap(), path);
94        }
95    }
96
97    #[rstest]
98    fn test_get_env_var_not_set() {
99        // Use a highly unlikely environment variable name
100        let result = get_env_var("NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_12345");
101        assert!(result.is_err());
102        assert!(result.unwrap_err().to_string().contains(
103            "environment variable 'NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_12345' must be set"
104        ));
105    }
106
107    #[rstest]
108    fn test_get_env_var_error_message_format() {
109        let var_name = "DEFINITELY_NONEXISTENT_VAR_123456789";
110        let result = get_env_var(var_name);
111        assert!(result.is_err());
112        let error_msg = result.unwrap_err().to_string();
113        assert!(error_msg.contains(var_name));
114        assert!(error_msg.contains("must be set"));
115    }
116
117    #[rstest]
118    fn test_get_or_env_var_with_some_value() {
119        let provided_value = Some("provided_value".to_string());
120        let result = get_or_env_var(provided_value, "PATH");
121        assert!(result.is_ok());
122        assert_eq!(result.unwrap(), "provided_value");
123    }
124
125    #[rstest]
126    fn test_get_or_env_var_with_none_and_env_var_set() {
127        // Test with a commonly available environment variable
128        if let Ok(path) = std::env::var("PATH") {
129            let result = get_or_env_var(None, "PATH");
130            assert!(result.is_ok());
131            assert_eq!(result.unwrap(), path);
132        }
133    }
134
135    #[rstest]
136    fn test_get_or_env_var_with_none_and_env_var_not_set() {
137        let result = get_or_env_var(None, "NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_67890");
138        assert!(result.is_err());
139        assert!(result.unwrap_err().to_string().contains(
140            "environment variable 'NONEXISTENT_ENV_VAR_THAT_SHOULD_NOT_EXIST_67890' must be set"
141        ));
142    }
143
144    #[rstest]
145    fn test_get_or_env_var_empty_string_value() {
146        // Empty string is still a valid value that should be returned
147        let provided_value = Some(String::new());
148        let result = get_or_env_var(provided_value, "PATH");
149        assert!(result.is_ok());
150        assert_eq!(result.unwrap(), "");
151    }
152
153    #[rstest]
154    fn test_get_or_env_var_priority() {
155        // When both value and env var are available, value takes precedence
156        // Using PATH as it should be available in most environments
157        if std::env::var("PATH").is_ok() {
158            let provided = Some("custom_value_takes_priority".to_string());
159            let result = get_or_env_var(provided, "PATH");
160            assert!(result.is_ok());
161            assert_eq!(result.unwrap(), "custom_value_takes_priority");
162        }
163    }
164
165    #[rstest]
166    fn test_get_or_env_var_opt_with_some_value() {
167        let provided_value = Some("provided_value".to_string());
168        let result = get_or_env_var_opt(provided_value, "PATH");
169        assert_eq!(result, Some("provided_value".to_string()));
170    }
171
172    #[rstest]
173    fn test_get_or_env_var_opt_with_none_and_env_var_set() {
174        if let Ok(path) = std::env::var("PATH") {
175            let result = get_or_env_var_opt(None, "PATH");
176            assert_eq!(result, Some(path));
177        }
178    }
179
180    #[rstest]
181    fn test_get_or_env_var_opt_with_none_and_env_var_not_set() {
182        let result = get_or_env_var_opt(None, "NONEXISTENT_ENV_VAR_OPT_12345");
183        assert_eq!(result, None);
184    }
185
186    #[rstest]
187    fn test_get_or_env_var_opt_priority() {
188        // When both value and env var are available, value takes precedence
189        if std::env::var("PATH").is_ok() {
190            let provided = Some("custom_value".to_string());
191            let result = get_or_env_var_opt(provided, "PATH");
192            assert_eq!(result, Some("custom_value".to_string()));
193        }
194    }
195
196    #[rstest]
197    fn test_resolve_env_var_pair_both_provided() {
198        let result = resolve_env_var_pair(
199            Some("my_key".to_string()),
200            Some("my_secret".to_string()),
201            "NONEXISTENT_KEY_VAR",
202            "NONEXISTENT_SECRET_VAR",
203        );
204        assert_eq!(
205            result,
206            Some(("my_key".to_string(), "my_secret".to_string()))
207        );
208    }
209
210    #[rstest]
211    fn test_resolve_env_var_pair_key_missing_returns_none() {
212        let result = resolve_env_var_pair(
213            None,
214            Some("my_secret".to_string()),
215            "NONEXISTENT_PAIR_KEY_12345",
216            "NONEXISTENT_PAIR_SECRET_12345",
217        );
218        assert_eq!(result, None);
219    }
220
221    #[rstest]
222    fn test_resolve_env_var_pair_secret_missing_returns_none() {
223        let result = resolve_env_var_pair(
224            Some("my_key".to_string()),
225            None,
226            "NONEXISTENT_PAIR_KEY_12345",
227            "NONEXISTENT_PAIR_SECRET_12345",
228        );
229        assert_eq!(result, None);
230    }
231
232    #[rstest]
233    fn test_resolve_env_var_pair_both_missing_returns_none() {
234        let result = resolve_env_var_pair(
235            None,
236            None,
237            "NONEXISTENT_PAIR_KEY_12345",
238            "NONEXISTENT_PAIR_SECRET_12345",
239        );
240        assert_eq!(result, None);
241    }
242}