freedom-config 1.1.0

ATLAS Freedom Configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
#![doc = include_str!("../README.md")]

use std::{fmt::Debug, sync::Arc};

use url::Url;

#[cfg(feature = "serde")]
mod ser;

/// The ATLAS Environment
#[derive(Debug, Clone)]
pub struct Environment(Arc<dyn Env>);

impl std::fmt::Display for Environment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0.as_ref().as_ref())
    }
}

impl Default for Environment {
    fn default() -> Self {
        Self::test()
    }
}

pub trait IntoEnv {
    fn into(self) -> Environment;
}

impl<T: Env> IntoEnv for T {
    fn into(self) -> Environment {
        Environment::new(self)
    }
}

impl IntoEnv for Environment {
    fn into(self) -> Environment {
        self
    }
}

// NOTE: I can't really think of a reason we'd need DerefMut. Once we construct an environment
// It shouldn't change during runtime.
impl std::ops::Deref for Environment {
    type Target = dyn Env;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

impl Environment {
    /// Construct an ATLAS environment
    pub fn new<E: Env>(env: E) -> Self {
        Self(Arc::new(env))
    }

    /// Construct an ATLAS environment object for the test environment
    pub fn test() -> Self {
        Self::new(Test)
    }

    /// Construct an ATLAS environment object for the production environment
    pub fn prod() -> Self {
        Self::new(Prod)
    }
}

/// A wrapper around T which implements debug and display, without showing the underlying value.
///
/// This is intended to wrap sensitive information, and prevent it from being accidentally logged,
/// or otherwise exposed
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(transparent)
)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Secret<T>(pub T);

impl<T> From<T> for Secret<T> {
    fn from(value: T) -> Self {
        Secret(value)
    }
}

impl<T> Secret<T> {
    pub fn expose(&self) -> &T {
        &self.0
    }
}

impl<T> std::fmt::Display for Secret<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <Self as std::fmt::Debug>::fmt(self, f)
    }
}

impl<T> std::fmt::Debug for Secret<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Secret").field(&"*****").finish()
    }
}

/// Shared behavior for atlas environments
pub trait Env: 'static + AsRef<str> + Debug + Send + Sync + Unpin {
    fn from_str(val: &str) -> Option<Self>
    where
        Self: Sized;

    /// The hostname of the FPS for the given environment
    fn fps_host(&self) -> &str;

    /// The entrypoint for the freedom API for the given environment
    ///
    /// # Note
    ///
    /// Each environment contains the path "/api" as all requests initiate from this point
    fn freedom_entrypoint(&self) -> Url;
}

/// Type state for the test environment
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Test;

impl AsRef<str> for Test {
    fn as_ref(&self) -> &str {
        "test"
    }
}

impl Env for Test {
    fn from_str(val: &str) -> Option<Self>
    where
        Self: Sized,
    {
        val.to_ascii_lowercase().eq("test").then_some(Self)
    }

    fn fps_host(&self) -> &str {
        "fps.test.atlasground.com"
    }

    fn freedom_entrypoint(&self) -> Url {
        Url::parse("https://test-api.atlasground.com/api/").unwrap()
    }
}

/// Type state for the production environment
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Prod;

impl AsRef<str> for Prod {
    fn as_ref(&self) -> &str {
        "prod"
    }
}

impl Env for Prod {
    fn from_str(val: &str) -> Option<Self>
    where
        Self: Sized,
    {
        val.to_ascii_lowercase().eq("prod").then_some(Self)
    }

    fn fps_host(&self) -> &str {
        "fps.atlasground.com"
    }

    fn freedom_entrypoint(&self) -> Url {
        Url::parse("https://api.atlasground.com/api/").unwrap()
    }
}

/// The configuration object for Freedom.
///
/// Used when creating a Freedom API client
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Config {
    environment: Environment,
    key: String,
    secret: Secret<String>,
}

impl PartialEq for Config {
    fn eq(&self, other: &Self) -> bool {
        self.environment_str() == other.environment_str()
            && self.key == other.key
            && self.secret == other.secret
    }
}

/// Error enumeration for creating a Freedom Config
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash, PartialOrd, Ord)]
pub enum Error {
    /// Failed to parse the variable from the environment
    ParseEnvironment,
    /// Missing secret from builder
    MissingSecret,
    /// Missing key from builder
    MissingKey,
    /// Missing environment from builder
    MissingEnvironment,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        <Self as std::fmt::Debug>::fmt(self, f)
    }
}

impl std::error::Error for Error {}

/// Builder for the Freedom Config object
#[derive(Default)]
pub struct ConfigBuilder {
    environment: Option<Environment>,
    key: Option<String>,
    secret: Option<Secret<String>>,
}

impl ConfigBuilder {
    /// Construct an empty Config builder
    pub fn new() -> Self {
        Self::default()
    }

    /// Attempt to load the ATLAS environment from the environment
    pub fn environment_from_env(&mut self) -> Result<&mut Self, Error> {
        let var = std::env::var(Config::ATLAS_ENV_VAR).map_err(|_| Error::ParseEnvironment)?;

        if let Some(env) = Test::from_str(&var) {
            return Ok(self.environment(env));
        }
        if let Some(env) = Prod::from_str(&var) {
            return Ok(self.environment(env));
        }

        Err(Error::ParseEnvironment)
    }

    /// Attempt to load the ATLAS secret from the environment
    pub fn secret_from_env(&mut self) -> Result<&mut Self, Error> {
        let var = std::env::var(Config::ATLAS_SECRET_VAR).map_err(|_| Error::ParseEnvironment)?;

        self.secret(var);
        Ok(self)
    }

    /// Attempt to load the ATLAS key from the environment
    pub fn key_from_env(&mut self) -> Result<&mut Self, Error> {
        let var = std::env::var(Config::ATLAS_KEY_VAR).map_err(|_| Error::ParseEnvironment)?;

        self.key(var);
        Ok(self)
    }

    /// Set the environment
    pub fn environment(&mut self, environment: impl IntoEnv) -> &mut Self {
        self.environment = Some(environment.into());
        self
    }

    /// Set the secret
    pub fn secret(&mut self, secret: impl Into<String>) -> &mut Self {
        self.secret = Some(Secret(secret.into()));
        self
    }

    /// Set the key
    pub fn key(&mut self, key: impl Into<String>) -> &mut Self {
        self.key = Some(key.into());
        self
    }

    /// Build the Config from the current builder
    pub fn build(&mut self) -> Result<Config, Error> {
        let Some(environment) = self.environment.take() else {
            return Err(Error::MissingEnvironment);
        };
        let Some(key) = self.key.take() else {
            return Err(Error::MissingKey);
        };
        let Some(secret) = self.secret.take() else {
            return Err(Error::MissingSecret);
        };

        Ok(Config {
            environment,
            key,
            secret,
        })
    }
}

impl Config {
    /// The environment variable name for the atlas environment
    pub const ATLAS_ENV_VAR: &'static str = "ATLAS_ENV";

    /// The environment variable name for the atlas key
    pub const ATLAS_KEY_VAR: &'static str = "ATLAS_KEY";

    /// The environment variable name for the atlas secret
    pub const ATLAS_SECRET_VAR: &'static str = "ATLAS_SECRET";

    /// Construct a new config builder
    ///
    /// # Example
    ///
    /// ```
    /// # use freedom_config::{Config, Test};
    /// let config_result = Config::builder()
    ///     .environment(Test)
    ///     .key("my_key")
    ///     .secret("my_secret")
    ///     .build();
    ///
    /// assert!(config_result.is_ok());
    /// ```
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }

    /// Build the entire configuration from environment variables
    pub fn from_env() -> Result<Self, Error> {
        Self::builder()
            .environment_from_env()?
            .key_from_env()?
            .secret_from_env()?
            .build()
    }

    /// Construct the Config from the environment, key, and secret
    ///
    /// # Example
    ///
    /// ```
    /// # use freedom_config::{Config, Test};
    /// let config = Config::new(Test, "my_key", "my_secret");
    /// ```
    pub fn new(environment: impl Env, key: impl Into<String>, secret: impl Into<String>) -> Self {
        let environment = Environment::new(environment);

        Self {
            environment,
            key: key.into(),
            secret: Secret(secret.into()),
        }
    }

    /// Set the environment
    ///
    /// # Example
    ///
    /// ```
    /// # let mut config = freedom_config::Config::new(freedom_config::Test, "key", "password");
    /// # use freedom_config::Prod;
    /// config.set_environment(Prod);
    /// assert_eq!(config.environment_str(), "prod");
    /// ```
    pub fn set_environment(&mut self, environment: impl Env) {
        self.environment = Environment::new(environment);
    }

    /// Return the trait object representing an ATLAS environment
    pub fn environment(&self) -> &Environment {
        &self.environment
    }

    /// Return the string representation of the environment
    pub fn environment_str(&self) -> &str {
        self.environment.as_ref()
    }

    /// Exposes the secret as a string slice.
    ///
    /// # Warning
    ///
    /// Use this with extreme care to avoid accidentally leaking your key
    pub fn expose_secret(&self) -> &str {
        self.secret.expose()
    }

    /// Return the ATLAS key
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Set the ATLAS key
    ///
    /// # Example
    ///
    /// ```
    /// # let mut config = freedom_config::Config::new(freedom_config::Test, "key", "password");
    /// config.set_key("top secret");
    /// assert_eq!(config.key(), "top secret");
    /// ```
    pub fn set_key(&mut self, key: impl Into<String>) {
        self.key = key.into();
    }

    /// Set the value of the ATLAS secret
    ///
    /// # Example
    ///
    /// ```
    /// # let mut config = freedom_config::Config::new(freedom_config::Test, "key", "password");
    /// config.set_secret("top secret");
    /// assert_eq!(config.expose_secret(), "top secret");
    /// ```
    pub fn set_secret(&mut self, secret: impl Into<String>) {
        self.secret = Secret(secret.into());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[allow(unused)]
    fn config_is_send() {
        fn is_send<T: Send>(_foo: T) {}

        let config = Config::from_env().unwrap();
        is_send(config);
    }

    #[cfg(feature = "serde")]
    mod serde {
        use super::*;

        #[test]
        fn deserialize_config() {
            let json = r#"{"key": "foo", "secret": "bar", "environment": "tEsT"}"#;
            let config: Config = serde_json::from_str(json).unwrap();
            assert_eq!(config.key(), "foo");
            assert_eq!(config.expose_secret(), "bar");
            assert_eq!(config.environment_str(), "test");
        }

        #[test]
        fn serialize_config() {
            let config = Config::builder()
                .key("foo")
                .secret("bar")
                .environment(Test)
                .build()
                .unwrap();
            let value = serde_json::to_value(&config).unwrap();
            assert_eq!(value.get("key").unwrap().as_str().unwrap(), "foo");
            assert_eq!(value.get("secret").unwrap().as_str().unwrap(), "bar");
            assert_eq!(value.get("environment").unwrap().as_str().unwrap(), "test");
        }

        #[test]
        fn deserialize_config_prod() {
            let json = r#"{"key": "foo", "secret": "bar", "environment": "prod"}"#;
            let config: Config = serde_json::from_str(json).unwrap();
            assert_eq!(config.key(), "foo");
            assert_eq!(config.expose_secret(), "bar");
            assert_eq!(config.environment_str(), "prod");
        }

        #[test]
        fn serialize_config_prod() {
            let config = Config::builder()
                .key("foo")
                .secret("bar")
                .environment(Prod)
                .build()
                .unwrap();
            let value = serde_json::to_value(&config).unwrap();
            assert_eq!(value.get("key").unwrap().as_str().unwrap(), "foo");
            assert_eq!(value.get("secret").unwrap().as_str().unwrap(), "bar");
            assert_eq!(value.get("environment").unwrap().as_str().unwrap(), "prod");
        }
    }
}