braze-sync 0.14.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
//! Integration tests for the `diff --plan-out` / `apply --plan` plan-lock.
//!
//! These exercise the §3 contract from
//! `docs/local/feat-apply-plan-locking.md`:
//!
//! - `diff --plan-out=<path>` writes a JSON plan file.
//! - `apply --plan=<path>` succeeds when fresh plan matches saved plan.
//! - mismatched ops, environment, or scope exit 7 and fire no writes.

mod common;

use assert_cmd::Command;
use common::{write_config, write_local_schema};
use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn diff_plan_out_writes_plan_file() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    write_local_schema(tmp.path(), "newcat", &[("id", "string")]);
    let plan_path = tmp.path().join("plan.json");

    let plan_arg = format!("--plan-out={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["diff", "--resource", "catalog_schema", &plan_arg])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let bytes = std::fs::read(&plan_path).expect("plan file written");
    let plan: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(plan["version"], 1);
    assert_eq!(plan["scope"]["environment"], "test");
    assert_eq!(plan["scope"]["resource"], "catalog_schema");
    let ops = plan["ops"].as_array().unwrap();
    assert_eq!(ops.len(), 1);
    assert_eq!(ops[0]["kind"], "catalog_schema");
    assert_eq!(ops[0]["name"], "newcat");
    assert_eq!(ops[0]["op"], "add");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_with_matching_plan_succeeds() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(201).set_body_json(json!({"message": "success"})))
        .expect(1)
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    write_local_schema(tmp.path(), "newcat", &[("id", "string")]);
    let plan_path = tmp.path().join("plan.json");

    let plan_out = format!("--plan-out={}", plan_path.display());
    let config_for_diff = config_path.clone();
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_for_diff.to_str().unwrap()])
            .args(["diff", "--resource", "catalog_schema", &plan_out])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let plan_in = format!("--plan={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args([
                "apply",
                "--resource",
                "catalog_schema",
                "--confirm",
                &plan_in,
            ])
            .assert()
            .success();
    })
    .await
    .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_plan_drift_exits_7_and_fires_no_writes() {
    let server = MockServer::start().await;
    // First call (diff): remote is empty → plan has 1 add op.
    // Subsequent calls (apply): remote now has the catalog → fresh plan has 0 ops.
    let initial_state = json!({"catalogs": []});
    let drifted_state = json!({
        "catalogs": [{"name": "newcat", "fields": [{"name": "id", "type": "string"}]}]
    });
    Mock::given(method("GET"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(initial_state))
        .up_to_n_times(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/catalogs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(drifted_state))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("DELETE"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    write_local_schema(tmp.path(), "newcat", &[("id", "string")]);
    let plan_path = tmp.path().join("plan.json");

    let plan_out = format!("--plan-out={}", plan_path.display());
    let config_for_diff = config_path.clone();
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_for_diff.to_str().unwrap()])
            .args(["diff", "--resource", "catalog_schema", &plan_out])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let plan_in = format!("--plan={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args([
                "apply",
                "--resource",
                "catalog_schema",
                "--confirm",
                &plan_in,
            ])
            .assert()
            .failure()
            .code(7);
    })
    .await
    .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_plan_environment_mismatch_exits_7_before_api_call() {
    // No mock for /catalogs — if scope-check runs before the API, the test
    // never needs to satisfy a request, which is the property we want.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("DELETE"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let plan_path = tmp.path().join("plan.json");

    // Hand-craft a plan file with a foreign environment.
    let plan_json = serde_json::json!({
        "version": 1,
        "generated_at": "2026-05-18T00:00:00Z",
        "braze_sync_version": env!("CARGO_PKG_VERSION"),
        "scope": {"environment": "prod"},
        "ops": []
    });
    std::fs::write(&plan_path, serde_json::to_vec_pretty(&plan_json).unwrap()).unwrap();

    let plan_in = format!("--plan={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["apply", "--confirm", &plan_in])
            .assert()
            .failure()
            .code(7);
    })
    .await
    .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_plan_archive_orphans_mismatch_exits_7_before_api_call() {
    // Plan was generated *without* --archive-orphans but apply passes the
    // flag (or vice versa). The frozen op set would imply different
    // writes between the two modes, so the lock must reject before any
    // API call.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("DELETE"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    let plan_path = tmp.path().join("plan.json");

    let plan_json = serde_json::json!({
        "version": 1,
        "generated_at": "2026-05-18T00:00:00Z",
        "braze_sync_version": env!("CARGO_PKG_VERSION"),
        "scope": {"environment": "test", "archive_orphans": false},
        "ops": []
    });
    std::fs::write(&plan_path, serde_json::to_vec_pretty(&plan_json).unwrap()).unwrap();

    let plan_in = format!("--plan={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", config_path.to_str().unwrap()])
            .args(["apply", "--confirm", "--archive-orphans", &plan_in])
            .assert()
            .failure()
            .code(7);
    })
    .await
    .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn plan_lock_aborts_when_consumed_values_change_between_plan_and_apply() {
    // RFC §4 Phase 6: editing values/<env>.yaml after diff --plan-out
    // must abort apply --plan with PlanDrift (exit 7), before any
    // mutation hits Braze.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_blocks": []
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0) // No POST may fire on plan drift.
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    common::write_local_content_block(tmp.path(), "promo", "cta=__BRAZESYNC.lid.cta__\n");
    common::write_values_file(
        tmp.path(),
        "test",
        r#"version: 1
content_block:
  promo:
    lid:
      cta:
        value: oldlidvalue1
        url: https://example.com/cta
"#,
    );

    let plan_path = tmp.path().join("plan.json");
    let plan_out = format!("--plan-out={}", plan_path.display());
    let config_str = config_path.to_str().unwrap().to_string();
    let plan_out_clone = plan_out.clone();
    let config_str_clone = config_str.clone();
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", &config_str_clone])
            .args(["diff", "--resource", "content_block", &plan_out_clone])
            .assert()
            .success();
    })
    .await
    .unwrap();

    // Edit the values file after the plan has been written.
    common::write_values_file(
        tmp.path(),
        "test",
        r#"version: 1
content_block:
  promo:
    lid:
      cta:
        value: tamperedlid
        url: https://example.com/cta
"#,
    );

    let plan_in = format!("--plan={}", plan_path.display());
    let assert = tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", &config_str])
            .args([
                "apply",
                "--resource",
                "content_block",
                "--confirm",
                &plan_in,
            ])
            .assert()
            .failure()
            .code(7)
    })
    .await
    .unwrap();
    let stderr = String::from_utf8_lossy(&assert.get_output().stderr).to_string();
    assert!(
        stderr.contains("plan drift")
            && (stderr.contains("values inputs changed") || stderr.contains("consumed values")),
        "expected plan-drift values message, got:\n{stderr}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn plan_lock_passes_when_unrelated_values_key_changes() {
    // Editing a values key that no resource currently references
    // (orphan in one resource's plan world) must NOT trigger
    // plan-drift abort. The hash is per-resource over its CONSUMED
    // subset.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_blocks": []
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/content_blocks/create"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_block_id": "new-id-1",
            "message": "success"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    common::write_local_content_block(tmp.path(), "promo", "cta=__BRAZESYNC.lid.cta__\n");
    // Two entries; only `cta` is consumed by the placeholder.
    common::write_values_file(
        tmp.path(),
        "test",
        r#"version: 1
content_block:
  promo:
    lid:
      cta:
        value: stableidvalue
        url: https://example.com/cta
      unused:
        value: othervaluexxx
        url: https://example.com/unused
"#,
    );

    let plan_path = tmp.path().join("plan.json");
    let plan_out = format!("--plan-out={}", plan_path.display());
    let config_str = config_path.to_str().unwrap().to_string();
    let plan_out_clone = plan_out.clone();
    let config_str_clone = config_str.clone();
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", &config_str_clone])
            .args(["diff", "--resource", "content_block", &plan_out_clone])
            .assert()
            .success();
    })
    .await
    .unwrap();

    // Edit only the *unused* entry. The plan-lock hash for `promo`
    // must not change because `unused` is not in its consumed set.
    common::write_values_file(
        tmp.path(),
        "test",
        r#"version: 1
content_block:
  promo:
    lid:
      cta:
        value: stableidvalue
        url: https://example.com/cta
      unused:
        value: editedvaluexx
        url: https://example.com/unused
"#,
    );

    let plan_in = format!("--plan={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", &config_str])
            .args([
                "apply",
                "--resource",
                "content_block",
                "--confirm",
                &plan_in,
            ])
            .assert()
            .success();
    })
    .await
    .unwrap();
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn plan_lock_scoped_resource_ignores_other_kind_placeholders() {
    // Regression: when `diff --resource content_block --plan-out` and
    // `apply --resource content_block --plan` run against a repo that
    // also contains a placeholder-bearing email_template on disk, the
    // apply-side hash recomputation must use the same kinds as the
    // saved plan (here: [content_block] only). Otherwise it would hash
    // the out-of-scope email_template and `check_plan_values_hashes`
    // would report it as `extra` → spurious PlanDrift exit 7.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/content_blocks/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_blocks": []
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/content_blocks/create"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "content_block_id": "new-id-1",
            "message": "success"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let tmp = tempfile::tempdir().unwrap();
    let config_path = write_config(tmp.path(), &server.uri());
    common::write_local_content_block(tmp.path(), "promo", "cta=__BRAZESYNC.lid.cta__\n");
    // Out-of-scope email_template with placeholders. Apply must not
    // hash it when --resource content_block restricts the kind set.
    common::write_local_email_template(
        tmp.path(),
        "welcome",
        "subj=__BRAZESYNC.lid.headline__",
        "<p>hi __BRAZESYNC.lid.headline__</p>",
        "hi __BRAZESYNC.lid.headline__",
    );
    common::write_values_file(
        tmp.path(),
        "test",
        r#"version: 1
content_block:
  promo:
    lid:
      cta:
        value: stableidvalue
        url: https://example.com/cta
"#,
    );

    let plan_path = tmp.path().join("plan.json");
    let plan_out = format!("--plan-out={}", plan_path.display());
    let config_str = config_path.to_str().unwrap().to_string();
    let plan_out_clone = plan_out.clone();
    let config_str_clone = config_str.clone();
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", &config_str_clone])
            .args(["diff", "--resource", "content_block", &plan_out_clone])
            .assert()
            .success();
    })
    .await
    .unwrap();

    let plan_in = format!("--plan={}", plan_path.display());
    tokio::task::spawn_blocking(move || {
        Command::cargo_bin("braze-sync")
            .unwrap()
            .env("BRAZE_API_KEY", "test-key")
            .args(["--config", &config_str])
            .args([
                "apply",
                "--resource",
                "content_block",
                "--confirm",
                &plan_in,
            ])
            .assert()
            .success();
    })
    .await
    .unwrap();
}