dove-core 0.1.1

The shared library behind dove — client-side-encrypted, expiring file sharing from a cloud you own.
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! CloudFront in front of the gate's API Gateway. It gives the gate a stable
//! `*.cloudfront.net` domain (and, via `dove domain add`, a custom one), a place
//! to attach caching/WAF later, and the perpetual free tier. The origin is the
//! HTTP API — a plain public HTTPS origin, no signing needed.
//!
//! Moved from the `dove` CLI's `src/cloudfront.rs` — logic unchanged; terminal
//! output (`ui::step`) replaced with `Progress` calls so this crate does no
//! terminal I/O of its own.

use crate::progress::Progress;
use anyhow::{anyhow, bail, Context, Result};
use std::process::Command;

// AWS-managed CloudFront policies.
const CACHE_DISABLED: &str = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
const CACHING_OPTIMIZED: &str = "658327ea-f89d-4fab-a63d-7e88639e58f6";
// "AllViewerExceptHostHeader": forward everything except Host, so CloudFront
// sends the origin's own host — required for an API Gateway origin to route.
const ALL_VIEWER_EXCEPT_HOST: &str = "b689b0a8-53d0-40ab-baf2-68738e2966ac";

/// A CloudFront Function that collapses every `/d/*` (and `/r/*`) to one path
/// each, so all share pages — and all request-upload pages — share a single
/// cache entry apiece: the decryptor page is byte-identical for every share, and
/// the upload page is byte-identical for every request (both ids are read
/// client-side), so a flood of `/d/<random>` or `/r/<random>` becomes cache hits
/// instead of Lambda invocations. Rewrites the *origin* path only; the browser
/// URL is unchanged, so the page still reads the real id.
const PAGE_REWRITE_JS: &str = r#"function handler(event) {
    var req = event.request;
    if (req.uri.startsWith('/d/')) { req.uri = '/d/p'; }
    if (req.uri.startsWith('/r/')) { req.uri = '/r/p'; }
    return req;
}
"#;

/// What a fronted gate resolves to.
pub struct Front {
    pub distribution_id: String,
    pub domain: String,
}

/// Stand up (or reuse) the CloudFront distribution over the gate's API Gateway
/// origin. Returns the distribution id + its `*.cloudfront.net` domain.
pub fn front_gate(
    profile: Option<&str>,
    account: &str,
    origin_host: &str,
    existing_distribution: Option<&str>,
    progress: &dyn Progress,
) -> Result<Front> {
    if let Some(dist_id) = existing_distribution {
        progress.step("cloudfront (reuse)");
        // A re-provision must apply the request feature's CloudFront changes to
        // an ALREADY-LIVE distribution (default behavior allows POST for the
        // upload finalize; the `/r/*` behavior). These live only in
        // `distribution_config` (the CREATE path), so without this a re-provision
        // never delivers them to an existing distribution.
        //
        // Ensure the page-rewrite function exists (create-or-skip; deterministic
        // ARN). We deliberately do NOT update its code here: the shared `/d/`
        // rewrite fn is left untouched, so an existing distribution's `/r/*` may
        // not yet collapse to a single cache entry — that `/r/` collapse is a
        // deferred optimization, not a correctness requirement.
        let page_fn_arn = ensure_page_function(profile, account)?;

        // Surgical merge, mirroring `add_alias`: fetch the CURRENT config and
        // modify ONLY the default behavior's methods + the `/r/*` behavior,
        // preserving everything else. A wholesale `update-distribution` with
        // `distribution_config` would emit `CloudFrontDefaultCertificate:true`
        // with no aliases and STRIP the custom domain (share.example.com) + ACM cert
        // that `add_alias` attached.
        let out = aws(
            profile,
            &[
                "cloudfront",
                "get-distribution-config",
                "--id",
                dist_id,
                "--output",
                "json",
            ],
        )?;
        if !out.status.success() {
            bail!(
                "get-distribution-config: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        let v: serde_json::Value = serde_json::from_slice(&out.stdout)?;
        let etag = v["ETag"]
            .as_str()
            .ok_or_else(|| anyhow!("no ETag"))?
            .to_string();
        let mut cfg = v["DistributionConfig"].clone();
        merge_request_behaviors(&mut cfg, &page_fn_arn);

        let tmp = std::env::temp_dir().join(format!("dove-dist-{dist_id}.json"));
        std::fs::write(&tmp, cfg.to_string())?;
        let cfg_arg = format!("file://{}", tmp.display());
        let out = aws(
            profile,
            &[
                "cloudfront",
                "update-distribution",
                "--id",
                dist_id,
                "--distribution-config",
                &cfg_arg,
                "--if-match",
                &etag,
                "--output",
                "json",
            ],
        );
        let _ = std::fs::remove_file(&tmp);
        let out = out?;
        if !out.status.success() {
            bail!(
                "update-distribution: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }

        let domain = distribution_domain(profile, dist_id)?;
        progress.done("cloudfront (reuse)");
        return Ok(Front {
            distribution_id: dist_id.to_string(),
            domain,
        });
    }
    // The page cache-key rewrite function must exist before the distribution
    // references it.
    progress.step("page cache function");
    let fn_arn = ensure_page_function(profile, account);
    if fn_arn.is_ok() {
        progress.done("page cache function");
    }
    let fn_arn = fn_arn?;

    progress.step("cloudfront distribution");
    let front = create_distribution(profile, origin_host, &fn_arn);
    if front.is_ok() {
        progress.done("cloudfront distribution");
    }
    front
}

/// Create + publish the page-rewrite CloudFront Function, reusing it by name.
/// Its ARN is deterministic per account.
fn ensure_page_function(profile: Option<&str>, account: &str) -> Result<String> {
    let arn = format!("arn:aws:cloudfront::{account}:function/dove-page-rewrite");
    let tmp = std::env::temp_dir().join("dove-page-rewrite.js");
    std::fs::write(&tmp, PAGE_REWRITE_JS)?;
    let code_arg = format!("fileb://{}", tmp.display());
    let out = aws(
        profile,
        &[
            "cloudfront",
            "create-function",
            "--name",
            "dove-page-rewrite",
            "--function-config",
            "Comment=dove page cache-key rewrite,Runtime=cloudfront-js-2.0",
            "--function-code",
            &code_arg,
            "--output",
            "json",
        ],
    );
    let _ = std::fs::remove_file(&tmp);
    let out = out?;
    if out.status.success() {
        let v: serde_json::Value = serde_json::from_slice(&out.stdout)?;
        let etag = v["ETag"]
            .as_str()
            .ok_or_else(|| anyhow!("no ETag from create-function"))?;
        let pub_out = aws(
            profile,
            &[
                "cloudfront",
                "publish-function",
                "--name",
                "dove-page-rewrite",
                "--if-match",
                etag,
            ],
        )?;
        if !pub_out.status.success() {
            bail!(
                "publish-function: {}",
                String::from_utf8_lossy(&pub_out.stderr).trim()
            );
        }
    } else if !String::from_utf8_lossy(&out.stderr).contains("FunctionAlreadyExists") {
        bail!(
            "create-function: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(arn)
}

fn create_distribution(
    profile: Option<&str>,
    origin_host: &str,
    page_fn_arn: &str,
) -> Result<Front> {
    let caller_ref = format!("dove-{origin_host}");
    let config = distribution_config(&caller_ref, origin_host, page_fn_arn);
    let out = aws(
        profile,
        &[
            "cloudfront",
            "create-distribution",
            "--distribution-config",
            &config,
            "--output",
            "json",
        ],
    )?;
    if !out.status.success() {
        bail!(
            "create-distribution: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let v: serde_json::Value = serde_json::from_slice(&out.stdout)?;
    Ok(Front {
        distribution_id: v["Distribution"]["Id"]
            .as_str()
            .ok_or_else(|| anyhow!("no distribution Id"))?
            .to_string(),
        domain: v["Distribution"]["DomainName"]
            .as_str()
            .ok_or_else(|| anyhow!("no distribution DomainName"))?
            .to_string(),
    })
}

/// Attach a custom domain (`domain`) with its ACM cert to an existing gate
/// distribution: add the alias + viewer certificate, preserving everything else.
pub fn add_alias(
    profile: Option<&str>,
    dist_id: &str,
    domain: &str,
    cert_arn: &str,
) -> Result<String> {
    let out = aws(
        profile,
        &[
            "cloudfront",
            "get-distribution-config",
            "--id",
            dist_id,
            "--output",
            "json",
        ],
    )?;
    if !out.status.success() {
        bail!(
            "get-distribution-config: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let v: serde_json::Value = serde_json::from_slice(&out.stdout)?;
    let etag = v["ETag"]
        .as_str()
        .ok_or_else(|| anyhow!("no ETag"))?
        .to_string();
    let mut cfg = v["DistributionConfig"].clone();
    cfg["Aliases"] = serde_json::json!({"Quantity": 1, "Items": [domain]});
    cfg["ViewerCertificate"] = serde_json::json!({
        "ACMCertificateArn": cert_arn,
        "SSLSupportMethod": "sni-only",
        "MinimumProtocolVersion": "TLSv1.2_2021",
        "CloudFrontDefaultCertificate": false,
    });
    let domain_name = cfg["DomainName"].as_str().unwrap_or_default().to_string();

    let tmp = std::env::temp_dir().join(format!("dove-dist-{dist_id}.json"));
    std::fs::write(&tmp, cfg.to_string())?;
    let cfg_arg = format!("file://{}", tmp.display());
    let out = aws(
        profile,
        &[
            "cloudfront",
            "update-distribution",
            "--id",
            dist_id,
            "--distribution-config",
            &cfg_arg,
            "--if-match",
            &etag,
            "--output",
            "json",
        ],
    );
    let _ = std::fs::remove_file(&tmp);
    if !out?.status.success() {
        bail!("update-distribution failed");
    }
    Ok(domain_name)
}

fn distribution_domain(profile: Option<&str>, dist_id: &str) -> Result<String> {
    let out = aws(
        profile,
        &[
            "cloudfront",
            "get-distribution",
            "--id",
            dist_id,
            "--output",
            "json",
        ],
    )?;
    if !out.status.success() {
        bail!(
            "get-distribution: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    let v: serde_json::Value = serde_json::from_slice(&out.stdout)?;
    v["Distribution"]["DomainName"]
        .as_str()
        .map(str::to_string)
        .ok_or_else(|| anyhow!("no DomainName"))
}

// ── pure helpers ──────────────────────────────────────────────────────────

/// A cache behavior (all fields CloudFront requires) for a path pattern, with an
/// optional viewer-request function.
fn cache_behavior(path: &str, cache_policy: &str, fn_arn: Option<&str>) -> serde_json::Value {
    let fns = match fn_arn {
        Some(arn) => serde_json::json!({
            "Quantity": 1,
            "Items": [{"EventType": "viewer-request", "FunctionARN": arn}]
        }),
        None => serde_json::json!({"Quantity": 0}),
    };
    serde_json::json!({
        "PathPattern": path,
        "TargetOriginId": "gate",
        "ViewerProtocolPolicy": "redirect-to-https",
        "CachePolicyId": cache_policy,
        "Compress": true,
        "AllowedMethods": {
            "Quantity": 2, "Items": ["GET", "HEAD"],
            "CachedMethods": {"Quantity": 2, "Items": ["GET", "HEAD"]}
        },
        "FunctionAssociations": fns,
        "SmoothStreaming": false,
        "FieldLevelEncryptionId": "",
        "LambdaFunctionAssociations": {"Quantity": 0},
        "TrustedSigners": {"Enabled": false, "Quantity": 0},
        "TrustedKeyGroups": {"Enabled": false, "Quantity": 0}
    })
}

/// Apply the request feature's two CloudFront changes to a `DistributionConfig`
/// value, **in place**, preserving everything else (Aliases, ViewerCertificate,
/// Origins, Comment, and any other cache behaviors). PURE — no I/O; the reuse
/// path in `front_gate` feeds it the LIVE fetched config so a re-provision
/// updates an existing distribution without stripping its custom domain/cert.
///
/// 1. The default behavior must allow POST — the request feature's upload
///    finalize, `POST {origin}/done/<id>`, is the only POST on the whole gate,
///    and CloudFront 403s any method outside `AllowedMethods` before it reaches
///    the origin. POST is never cached, though: `CachedMethods` stays GET/HEAD.
/// 2. A `/r/*` cache behavior (the request-agnostic upload page) is ensured,
///    carrying the page-rewrite function.
///
/// Idempotent: a second application adds no behavior and leaves `Quantity`
/// stable (it matches on `PathPattern == "/r/*"`).
fn merge_request_behaviors(config: &mut serde_json::Value, page_fn_arn: &str) {
    config["DefaultCacheBehavior"]["AllowedMethods"] = serde_json::json!({
        "Quantity": 7,
        "Items": ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"],
        "CachedMethods": {"Quantity": 2, "Items": ["GET", "HEAD"]}
    });

    // A distribution with zero cache behaviors can come back as `{"Quantity":0}`
    // with no `Items`; normalize so there's always an array to append to.
    if !config["CacheBehaviors"]["Items"].is_array() {
        config["CacheBehaviors"] = serde_json::json!({"Quantity": 0, "Items": []});
    }
    let items = config["CacheBehaviors"]["Items"]
        .as_array_mut()
        .expect("CacheBehaviors.Items normalized to an array above");
    if !items.iter().any(|b| b["PathPattern"] == "/r/*") {
        items.push(cache_behavior("/r/*", CACHING_OPTIMIZED, Some(page_fn_arn)));
    }
    let len = items.len();
    config["CacheBehaviors"]["Quantity"] = serde_json::json!(len);
}

/// The distribution config JSON. The **default** behavior is the dynamic gate (no
/// caching, API Gateway origin). Three cached behaviors sit in front: `/d/*` (the
/// share-agnostic page) and `/r/*` (the request-agnostic upload page) — each
/// collapsed to one cache entry by the rewrite function — and `/og.png`; all three
/// are served from the edge, never invoking the Lambda. Default cert; a custom
/// domain is added later by `domain add`.
pub fn distribution_config(caller_ref: &str, origin_host: &str, page_fn_arn: &str) -> String {
    serde_json::json!({
        "CallerReference": caller_ref,
        "Comment": "dove gate",
        "Enabled": true,
        "Origins": {"Quantity": 1, "Items": [{
            "Id": "gate",
            "DomainName": origin_host,
            "CustomOriginConfig": {
                "HTTPPort": 80,
                "HTTPSPort": 443,
                "OriginProtocolPolicy": "https-only",
                "OriginSslProtocols": {"Quantity": 1, "Items": ["TLSv1.2"]}
            }
        }]},
        "DefaultCacheBehavior": {
            "TargetOriginId": "gate",
            "ViewerProtocolPolicy": "redirect-to-https",
            // The request feature's ONLY POST is the upload finalize,
            // `POST {origin}/done/<id>` — CloudFront 403s any method not in
            // the default behavior's AllowedMethods before it ever reaches
            // the gate, so POST must be allowed here (never cached, though:
            // CachedMethods stays GET/HEAD).
            "AllowedMethods": {
                "Quantity": 7, "Items": ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"],
                "CachedMethods": {"Quantity": 2, "Items": ["GET", "HEAD"]}
            },
            "CachePolicyId": CACHE_DISABLED,
            "OriginRequestPolicyId": ALL_VIEWER_EXCEPT_HOST,
            "Compress": true
        },
        "CacheBehaviors": {"Quantity": 3, "Items": [
            cache_behavior("/d/*", CACHING_OPTIMIZED, Some(page_fn_arn)),
            cache_behavior("/r/*", CACHING_OPTIMIZED, Some(page_fn_arn)),
            cache_behavior("/og.png", CACHING_OPTIMIZED, None)
        ]},
        "ViewerCertificate": {"CloudFrontDefaultCertificate": true}
    })
    .to_string()
}

fn aws(profile: Option<&str>, args: &[&str]) -> Result<std::process::Output> {
    let mut cmd = Command::new("aws");
    if let Some(p) = profile {
        cmd.args(["--profile", p]);
    }
    cmd.args(args)
        .output()
        .with_context(|| format!("running aws {}", args.join(" ")))
}

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

    #[test]
    fn distribution_config_fronts_the_api_gateway_origin() {
        let c = distribution_config(
            "dove-x",
            "abc.execute-api.us-east-1.amazonaws.com",
            "arn:aws:cloudfront::1:function/dove-page-rewrite",
        );
        assert!(c.contains("\"DomainName\":\"abc.execute-api.us-east-1.amazonaws.com\""));
        assert!(c.contains(CACHE_DISABLED)); // default (dynamic) behavior
        assert!(c.contains(CACHING_OPTIMIZED)); // the cached /d/*, /r/*, and /og.png behaviors
        assert!(c.contains("/d/*") && c.contains("/r/*") && c.contains("/og.png"));
        assert!(c.contains("\"Quantity\":3")); // CacheBehaviors.Quantity bumped for /r/*

        // The /r/* behavior carries the same page-rewrite function as /d/*.
        // Parsed (not substring-searched): serde_json's default object
        // serialization sorts keys, so a plain search from "PathPattern" onward
        // can miss fields that sort before it, like "FunctionAssociations".
        let parsed: serde_json::Value = serde_json::from_str(&c).unwrap();
        let behaviors = parsed["CacheBehaviors"]["Items"].as_array().unwrap();
        let r_behavior = behaviors
            .iter()
            .find(|b| b["PathPattern"] == "/r/*")
            .expect("/r/* behavior present");
        assert_eq!(
            r_behavior["FunctionAssociations"]["Items"][0]["FunctionARN"],
            "arn:aws:cloudfront::1:function/dove-page-rewrite"
        );
        assert_eq!(r_behavior["CachePolicyId"], CACHING_OPTIMIZED);
        assert!(c.contains(ALL_VIEWER_EXCEPT_HOST));
        assert!(!c.contains("OriginAccessControlId")); // no OAC — plain origin

        // The default behavior must allow POST — the request feature's
        // upload finalize, `POST {origin}/done/<id>`, is the only POST on
        // the whole gate, and CloudFront 403s anything outside
        // AllowedMethods before it reaches the origin. It must still never
        // be cached: CachedMethods stays exactly GET/HEAD.
        let default_methods = &parsed["DefaultCacheBehavior"]["AllowedMethods"];
        let allowed: Vec<&str> = default_methods["Items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(
            allowed.contains(&"POST"),
            "default behavior must allow POST for /done"
        );
        assert!(allowed.contains(&"GET") && allowed.contains(&"HEAD"));
        let cached: Vec<&str> = default_methods["CachedMethods"]["Items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(cached, vec!["GET", "HEAD"]);
    }

    // ── reuse-path merge (re-provision of an existing distribution) ──────────
    //
    // A live, custom-domained distribution config as CloudFront returns it: a
    // share.example.com alias + its ACM ViewerCertificate (both added by
    // `add_alias`), a GET/HEAD-only default behavior, and the `/d/*` + `/og.png`
    // cache behaviors. Placeholder account id only. These prove the surgical
    // merge applies the request feature's changes without touching the custom
    // domain/cert (the footgun) and is idempotent.
    const TEST_FN_ARN: &str = "arn:aws:cloudfront::000000000000:function/dove-page-rewrite";

    fn live_config_with_custom_domain() -> serde_json::Value {
        serde_json::json!({
            "CallerReference": "dove-abc.execute-api.us-east-1.amazonaws.com",
            "Comment": "dove gate",
            "Enabled": true,
            "Aliases": {"Quantity": 1, "Items": ["share.example.com"]},
            "Origins": {"Quantity": 1, "Items": [{
                "Id": "gate",
                "DomainName": "abc.execute-api.us-east-1.amazonaws.com"
            }]},
            "DefaultCacheBehavior": {
                "TargetOriginId": "gate",
                "ViewerProtocolPolicy": "redirect-to-https",
                "AllowedMethods": {
                    "Quantity": 2, "Items": ["GET", "HEAD"],
                    "CachedMethods": {"Quantity": 2, "Items": ["GET", "HEAD"]}
                },
                "CachePolicyId": CACHE_DISABLED,
                "OriginRequestPolicyId": ALL_VIEWER_EXCEPT_HOST,
                "Compress": true
            },
            "CacheBehaviors": {"Quantity": 2, "Items": [
                cache_behavior("/d/*", CACHING_OPTIMIZED, Some(TEST_FN_ARN)),
                cache_behavior("/og.png", CACHING_OPTIMIZED, None)
            ]},
            "ViewerCertificate": {
                "ACMCertificateArn": "arn:aws:acm:us-east-1:000000000000:certificate/test",
                "SSLSupportMethod": "sni-only",
                "CloudFrontDefaultCertificate": false
            }
        })
    }

    fn path_patterns(config: &serde_json::Value) -> Vec<String> {
        config["CacheBehaviors"]["Items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|b| b["PathPattern"].as_str().unwrap().to_string())
            .collect()
    }

    // The footgun guard: the surgical merge must NOT strip the custom domain or
    // its ACM certificate. A wholesale update-distribution would.
    #[test]
    fn merge_preserves_alias_and_cert() {
        let mut cfg = live_config_with_custom_domain();
        merge_request_behaviors(&mut cfg, TEST_FN_ARN);

        assert_eq!(
            cfg["Aliases"]["Items"].as_array().unwrap(),
            &vec![serde_json::json!("share.example.com")]
        );
        assert_eq!(
            cfg["ViewerCertificate"]["ACMCertificateArn"],
            "arn:aws:acm:us-east-1:000000000000:certificate/test"
        );
        // Never flips back to the CloudFront default cert.
        assert_eq!(
            cfg["ViewerCertificate"]["CloudFrontDefaultCertificate"],
            false
        );
        assert_eq!(cfg["ViewerCertificate"]["SSLSupportMethod"], "sni-only");
        // Untouched surroundings.
        assert_eq!(cfg["Comment"], "dove gate");
        assert_eq!(cfg["Origins"]["Items"][0]["Id"], "gate");
    }

    // POST must reach the origin (for `POST /done/<id>`) but must NEVER be cached.
    #[test]
    fn merge_allows_post_but_caches_only_get_head() {
        let mut cfg = live_config_with_custom_domain();
        merge_request_behaviors(&mut cfg, TEST_FN_ARN);

        let dm = &cfg["DefaultCacheBehavior"]["AllowedMethods"];
        let allowed: Vec<&str> = dm["Items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(
            allowed.contains(&"POST"),
            "default behavior must allow POST for /done"
        );
        let cached: Vec<&str> = dm["CachedMethods"]["Items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(cached, vec!["GET", "HEAD"]);
    }

    // The `/r/*` behavior is added (with the page fn) and the existing
    // behaviors survive; Quantity tracks the real Items length.
    #[test]
    fn merge_adds_r_behavior() {
        let mut cfg = live_config_with_custom_domain();
        merge_request_behaviors(&mut cfg, TEST_FN_ARN);

        let patterns = path_patterns(&cfg);
        assert!(patterns.contains(&"/r/*".to_string()));
        assert!(patterns.contains(&"/d/*".to_string()));
        assert!(patterns.contains(&"/og.png".to_string()));

        let items = cfg["CacheBehaviors"]["Items"].as_array().unwrap();
        let r = items
            .iter()
            .find(|b| b["PathPattern"] == "/r/*")
            .expect("/r/* behavior present");
        assert_eq!(
            r["FunctionAssociations"]["Items"][0]["FunctionARN"],
            TEST_FN_ARN
        );
        assert_eq!(r["CachePolicyId"], CACHING_OPTIMIZED);
        assert_eq!(
            cfg["CacheBehaviors"]["Quantity"].as_u64().unwrap() as usize,
            items.len()
        );
    }

    // A second re-provision adds nothing and leaves Quantity stable.
    #[test]
    fn merge_is_idempotent() {
        let mut cfg = live_config_with_custom_domain();
        merge_request_behaviors(&mut cfg, TEST_FN_ARN);
        let len_after_first = cfg["CacheBehaviors"]["Items"].as_array().unwrap().len();
        let quantity_after_first = cfg["CacheBehaviors"]["Quantity"].as_u64().unwrap();

        merge_request_behaviors(&mut cfg, TEST_FN_ARN);

        let items = cfg["CacheBehaviors"]["Items"].as_array().unwrap();
        let r_count = items.iter().filter(|b| b["PathPattern"] == "/r/*").count();
        assert_eq!(r_count, 1, "exactly one /r/* behavior after two merges");
        assert_eq!(items.len(), len_after_first);
        assert_eq!(
            cfg["CacheBehaviors"]["Quantity"].as_u64().unwrap(),
            quantity_after_first
        );
        assert_eq!(
            cfg["CacheBehaviors"]["Quantity"].as_u64().unwrap() as usize,
            items.len()
        );
    }
}