braze-sync 0.9.0

GitOps CLI for managing Braze configuration as code
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Configuration loading and environment resolution.
//!
//! Two-step model:
//! 1. [`ConfigFile::load`] reads the YAML, parses it, and runs structural
//!    validation that doesn't need environment variables.
//! 2. [`ConfigFile::resolve`] picks an environment, looks up the API key
//!    via the OS environment, and produces a [`ResolvedConfig`] which is
//!    what the rest of the system consumes.
//!
//! The split exists so tests can drive [`ConfigFile::resolve_with`] with a
//! fake env-lookup closure instead of mutating process-global `std::env`.
//!
//! See IMPLEMENTATION.md §10. The api key is wrapped in
//! [`secrecy::SecretString`] from the moment it leaves the OS so that
//! `Debug`, `tracing`, and panic messages cannot leak it.

pub mod schema;

pub use schema::{
    ConfigFile, Defaults, EnvironmentConfig, NamingConfig, ResourceConfig, ResourcesConfig,
};

use crate::error::{Error, Result};
use crate::resource::ResourceKind;
use regex_lite::Regex;
use secrecy::SecretString;
use std::collections::HashMap;
use std::path::Path;
use url::Url;

/// Fully-resolved config: an environment has been picked and the API key
/// has been pulled out of the OS environment.
#[derive(Debug)]
pub struct ResolvedConfig {
    pub environment_name: String,
    pub api_endpoint: Url,
    /// API key, secrecy-wrapped. Use [`secrecy::ExposeSecret`] at the call
    /// site that needs the plaintext (typically only the BrazeClient
    /// constructor).
    pub api_key: SecretString,
    pub resources: ResourcesConfig,
    pub naming: NamingConfig,
    /// Compiled `exclude_patterns` per resource kind. Populated by
    /// [`ConfigFile::resolve_with`] so callers can look up a `&[Regex]`
    /// without recompiling on every invocation.
    pub excludes: HashMap<ResourceKind, Vec<Regex>>,
}

impl ResolvedConfig {
    /// Compiled exclude patterns for `kind`. Returns an empty slice when
    /// no patterns are configured.
    pub fn excludes_for(&self, kind: ResourceKind) -> &[Regex] {
        self.excludes.get(&kind).map(Vec::as_slice).unwrap_or(&[])
    }
}

impl ConfigFile {
    /// Load and structurally validate a config file.
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let bytes = std::fs::read_to_string(path)?;
        let cfg: ConfigFile =
            serde_norway::from_str(&bytes).map_err(|source| Error::YamlParse {
                path: path.to_path_buf(),
                source,
            })?;
        cfg.validate_static()?;
        Ok(cfg)
    }

    fn validate_static(&self) -> Result<()> {
        if self.version != 1 {
            return Err(Error::Config(format!(
                "unsupported config version {} (this binary supports version 1; \
                 see IMPLEMENTATION.md §2.5 for the forward-compat policy)",
                self.version
            )));
        }
        if !self.environments.contains_key(&self.default_environment) {
            return Err(Error::Config(format!(
                "default_environment '{}' is not declared in the environments map",
                self.default_environment
            )));
        }
        // Validate that all endpoint URLs use http or https. Non-hierarchical
        // schemes (mailto:, data:, etc.) would panic in BrazeClient::url_for
        // when calling path_segments_mut().
        for (name, env) in &self.environments {
            if env.api_key_env.trim().is_empty() {
                return Err(Error::Config(format!(
                    "environment '{name}': api_key_env must not be empty"
                )));
            }
            match env.api_endpoint.scheme() {
                "http" | "https" => {}
                scheme => {
                    return Err(Error::Config(format!(
                        "environment '{name}': api_endpoint must use http or https \
                         (got '{scheme}')"
                    )));
                }
            }
        }
        // Compile every resource's exclude_patterns at load time so
        // malformed regexes fail fast instead of at first use.
        for kind in ResourceKind::all() {
            let rc = self.resources.for_kind(*kind);
            compile_exclude_patterns(&rc.exclude_patterns, kind.as_str())?;
        }
        Ok(())
    }

    /// Resolve to a [`ResolvedConfig`] using the real process environment.
    pub fn resolve(self, env_override: Option<&str>) -> Result<ResolvedConfig> {
        self.resolve_with(env_override, |k| std::env::var(k).ok())
    }

    /// Resolve using a caller-supplied env-var lookup closure. Used by
    /// tests so they don't have to touch process-global `std::env`.
    pub fn resolve_with(
        mut self,
        env_override: Option<&str>,
        env_lookup: impl Fn(&str) -> Option<String>,
    ) -> Result<ResolvedConfig> {
        let env_name = env_override
            .map(str::to_string)
            .unwrap_or_else(|| self.default_environment.clone());

        if !self.environments.contains_key(&env_name) {
            let known: Vec<&str> = self.environments.keys().map(String::as_str).collect();
            return Err(Error::Config(format!(
                "unknown environment '{}'; declared: [{}]",
                env_name,
                known.join(", ")
            )));
        }
        let env_cfg = self
            .environments
            .remove(&env_name)
            .expect("presence checked immediately above");

        let api_key_str = env_lookup(&env_cfg.api_key_env)
            .ok_or_else(|| Error::MissingEnv(env_cfg.api_key_env.clone()))?;
        if api_key_str.is_empty() {
            return Err(Error::Config(format!(
                "environment variable '{}' is set but empty",
                env_cfg.api_key_env
            )));
        }

        let mut excludes: HashMap<ResourceKind, Vec<Regex>> = HashMap::new();
        for kind in ResourceKind::all() {
            let rc = self.resources.for_kind(*kind);
            excludes.insert(
                *kind,
                compile_exclude_patterns(&rc.exclude_patterns, kind.as_str())?,
            );
        }

        Ok(ResolvedConfig {
            environment_name: env_name,
            api_endpoint: env_cfg.api_endpoint,
            api_key: SecretString::from(api_key_str),
            resources: self.resources,
            naming: self.naming,
            excludes,
        })
    }
}

/// Compile a list of raw regex patterns from a resource's
/// `exclude_patterns` into `Regex` values. The `context` label is used
/// in error messages (e.g. `"custom_attribute"`).
pub fn compile_exclude_patterns(patterns: &[String], context: &str) -> Result<Vec<Regex>> {
    patterns
        .iter()
        .enumerate()
        .map(|(i, p)| {
            Regex::new(p).map_err(|e| {
                Error::Config(format!(
                    "{context}.exclude_patterns[{i}]: invalid regex {p:?}: {e}"
                ))
            })
        })
        .collect()
}

/// Return `true` if `name` matches any of the compiled patterns.
pub fn is_excluded(name: &str, patterns: &[Regex]) -> bool {
    patterns.iter().any(|r| r.is_match(name))
}

/// Load `.env` from the current working directory only — no parent
/// traversal — to populate `std::env` before config resolution. A missing
/// file is the common dev case and is not an error.
///
/// IMPLEMENTATION.md §10: via dotenvy, CWD only, no parent traversal.
pub fn load_dotenv() -> Result<()> {
    match dotenvy::from_path(".env") {
        Ok(()) => Ok(()),
        Err(e) if e.not_found() => Ok(()),
        Err(e) => Err(Error::Config(format!(".env load error: {e}"))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use secrecy::ExposeSecret;
    use std::io::Write;

    fn write_config(content: &str) -> tempfile::NamedTempFile {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    const MINIMAL: &str = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
"#;

    #[test]
    fn loads_minimal_config_with_all_defaults() {
        let f = write_config(MINIMAL);
        let cfg = ConfigFile::load(f.path()).unwrap();
        assert_eq!(cfg.version, 1);
        assert_eq!(cfg.default_environment, "dev");
        assert_eq!(cfg.environments.len(), 1);
        // resources defaulted in full
        assert!(cfg.resources.catalog_schema.enabled);
        assert_eq!(
            cfg.resources.catalog_schema.path,
            std::path::PathBuf::from("catalogs/")
        );
        assert_eq!(
            cfg.resources.custom_attribute.path,
            std::path::PathBuf::from("custom_attributes/registry.yaml")
        );
    }

    #[test]
    fn loads_full_config_from_section_10() {
        const FULL: &str = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
  prod:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_PROD_API_KEY
resources:
  catalog_schema:
    enabled: true
    path: catalogs/
  content_block:
    enabled: true
    path: content_blocks/
  email_template:
    enabled: false
    path: email_templates/
  custom_attribute:
    enabled: true
    path: custom_attributes/registry.yaml
naming:
  catalog_name_pattern: "^[a-z][a-z0-9_]*$"
"#;
        let f = write_config(FULL);
        let cfg = ConfigFile::load(f.path()).unwrap();
        assert_eq!(cfg.environments.len(), 2);
        assert!(!cfg.resources.email_template.enabled);
        assert_eq!(
            cfg.naming.catalog_name_pattern.as_deref(),
            Some("^[a-z][a-z0-9_]*$")
        );
    }

    #[test]
    fn rejects_wrong_version() {
        let yaml = r#"
version: 2
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::Config(_)));
        assert!(err.to_string().contains("version 2"));
    }

    #[test]
    fn rejects_unknown_top_level_field() {
        let yaml = r#"
version: 1
default_environment: dev
mystery_key: 1
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::YamlParse { .. }), "got: {err:?}");
    }

    #[test]
    fn rejects_legacy_catalog_items_resource_section() {
        let yaml = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
resources:
  catalog_items:
    enabled: true
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::YamlParse { .. }), "got: {err:?}");
    }

    #[test]
    fn rejects_legacy_defaults_rate_limit_per_minute() {
        // v0.8.0: client-side rate limiter was removed. Leftover
        // `rate_limit_per_minute` keys must hard-error so users notice
        // they need to delete them, rather than silently ignoring.
        let yaml = r#"
version: 1
default_environment: dev
defaults:
  rate_limit_per_minute: 40
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::YamlParse { .. }), "got: {err:?}");
    }

    #[test]
    fn rejects_legacy_environment_rate_limit_per_minute() {
        let yaml = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
    rate_limit_per_minute: 30
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::YamlParse { .. }), "got: {err:?}");
    }

    #[test]
    fn accepts_exclude_patterns_on_resource_config() {
        let yaml = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
resources:
  custom_attribute:
    path: custom_attributes/registry.yaml
    exclude_patterns:
      - "^_"
      - "^(hoge|hack)$"
"#;
        let f = write_config(yaml);
        let cfg = ConfigFile::load(f.path()).unwrap();
        assert_eq!(
            cfg.resources.custom_attribute.exclude_patterns,
            vec!["^_".to_string(), "^(hoge|hack)$".to_string()]
        );
    }

    #[test]
    fn rejects_invalid_exclude_pattern_at_load_time() {
        // Unbalanced paren — invalid regex should hard-error at load,
        // not at first use.
        let yaml = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
resources:
  custom_attribute:
    path: custom_attributes/registry.yaml
    exclude_patterns:
      - "("
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        match err {
            Error::Config(msg) => {
                assert!(msg.contains("custom_attribute"), "msg: {msg}");
                assert!(msg.contains("exclude_patterns[0]"), "msg: {msg}");
            }
            other => panic!("expected Config error, got {other:?}"),
        }
    }

    #[test]
    fn is_excluded_matches_any_pattern() {
        let patterns =
            compile_exclude_patterns(&["^_".to_string(), "^test_".to_string()], "test").unwrap();
        assert!(is_excluded("_unset", &patterns));
        assert!(is_excluded("test_foo", &patterns));
        assert!(!is_excluded("regular_attr", &patterns));
    }

    #[test]
    fn rejects_non_http_endpoint_scheme() {
        let yaml = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: ftp://rest.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::Config(_)));
        let msg = err.to_string();
        assert!(msg.contains("http"), "expected http scheme hint: {msg}");
        assert!(msg.contains("ftp"), "expected actual scheme: {msg}");
    }

    #[test]
    fn rejects_default_environment_not_in_map() {
        let yaml = r#"
version: 1
default_environment: missing
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::Config(_)));
        assert!(err.to_string().contains("missing"));
    }

    #[test]
    fn resolve_uses_default_environment_when_no_override() {
        let f = write_config(MINIMAL);
        let cfg = ConfigFile::load(f.path()).unwrap();
        let resolved = cfg
            .resolve_with(None, |k| {
                assert_eq!(k, "BRAZE_DEV_API_KEY");
                Some("token-abc".into())
            })
            .unwrap();
        assert_eq!(resolved.environment_name, "dev");
        assert_eq!(resolved.api_key.expose_secret(), "token-abc");
    }

    #[test]
    fn resolve_uses_override_when_provided() {
        const TWO_ENVS: &str = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_DEV_API_KEY
  prod:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: BRAZE_PROD_API_KEY
"#;
        let f = write_config(TWO_ENVS);
        let cfg = ConfigFile::load(f.path()).unwrap();
        let resolved = cfg
            .resolve_with(Some("prod"), |k| {
                assert_eq!(k, "BRAZE_PROD_API_KEY");
                Some("prod-token".into())
            })
            .unwrap();
        assert_eq!(resolved.environment_name, "prod");
    }

    #[test]
    fn resolve_unknown_env_lists_known_envs() {
        let f = write_config(MINIMAL);
        let cfg = ConfigFile::load(f.path()).unwrap();
        let err = cfg
            .resolve_with(Some("staging"), |_| Some("x".into()))
            .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("staging"));
        assert!(msg.contains("dev"));
    }

    #[test]
    fn resolve_missing_env_var_is_typed_error() {
        let f = write_config(MINIMAL);
        let cfg = ConfigFile::load(f.path()).unwrap();
        let err = cfg.resolve_with(None, |_| None).unwrap_err();
        match err {
            Error::MissingEnv(name) => assert_eq!(name, "BRAZE_DEV_API_KEY"),
            other => panic!("expected MissingEnv, got {other:?}"),
        }
    }

    #[test]
    fn resolve_empty_env_var_is_rejected() {
        let f = write_config(MINIMAL);
        let cfg = ConfigFile::load(f.path()).unwrap();
        let err = cfg.resolve_with(None, |_| Some(String::new())).unwrap_err();
        assert!(matches!(err, Error::Config(_)));
        assert!(err.to_string().contains("empty"));
    }

    #[test]
    fn debug_format_does_not_leak_api_key() {
        let f = write_config(MINIMAL);
        let resolved = ConfigFile::load(f.path())
            .unwrap()
            .resolve_with(None, |_| Some("super-secret-token-abc-123".into()))
            .unwrap();
        let dbg = format!("{resolved:?}");
        assert!(
            !dbg.contains("super-secret-token-abc-123"),
            "Debug output leaked api key: {dbg}"
        );
    }

    #[test]
    fn rejects_empty_api_key_env() {
        let yaml = r#"
version: 1
default_environment: dev
environments:
  dev:
    api_endpoint: https://rest.fra-02.braze.eu
    api_key_env: ""
"#;
        let f = write_config(yaml);
        let err = ConfigFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::Config(_)), "got: {err:?}");
        assert!(err.to_string().contains("api_key_env"));
    }

    #[test]
    fn load_io_error_for_missing_file() {
        let err = ConfigFile::load("/nonexistent/braze-sync.config.yaml").unwrap_err();
        assert!(matches!(err, Error::Io(_)), "got: {err:?}");
    }
}