zc2 0.0.25

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
//! VPN-join: connect zc to the zakuro WireGuard mesh.
//!
//! Public surface used by the rest of zc:
//!   - `connect(Preference) -> Result<ConnectionInfo, NetError>`
//!   - `status() -> Result<Option<ConnectionInfo>, NetError>`
//!   - `disconnect() -> Result<(), NetError>`
//!   - `run_cli(&[String])` — handler for `zc vpn …`
//!
//! Backends (native wg-quick / Docker sidecar) live behind the `Connector`
//! trait so each is testable in isolation.

#![allow(dead_code)]

pub mod connector;
pub mod docker;
pub mod native;
pub mod profile;
pub mod state;

use connector::{select_connector, Connector, Preference};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};

/// Verbose diagnostics toggle for `zc vpn` (`--verbose`/`-v`). When on, the mesh
/// steps print backend selection, wg-quick output, and `wg show` so a failed
/// connect can be diagnosed without guessing.
static VERBOSE: AtomicBool = AtomicBool::new(false);
pub fn set_verbose(v: bool) {
    VERBOSE.store(v, Ordering::Relaxed);
}
pub fn verbose() -> bool {
    VERBOSE.load(Ordering::Relaxed)
}
/// Print a `[vpn]` diagnostic line to stderr, but only in verbose mode.
pub fn vlog(msg: &str) {
    if verbose() {
        eprintln!("  [vpn] {msg}");
    }
}

/// Which transport carried the tunnel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Backend {
    Native,
    Docker,
}

impl Backend {
    pub fn label(&self) -> &'static str {
        match self {
            Backend::Native => "native",
            Backend::Docker => "docker",
        }
    }
}

/// Liveness of a single mesh peer, as seen from this node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PeerStatus {
    pub ip: String,
    pub last_handshake_secs: Option<u64>,
    pub reachable: bool,
}

/// The result of a successful connect / the current link state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionInfo {
    pub backend: Backend,
    pub address: String, // e.g. "10.13.13.6/24"
    pub link: String,    // iface name (native) or container name (docker)
    pub peers: Vec<PeerStatus>,
    pub host_routable: bool,
    #[serde(default)]
    pub proxy: Option<String>, // "127.0.0.1:18888" when backend=Docker exposes a CONNECT proxy
}

/// How zc reaches the mesh subnet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MeshAccess {
    Host,
    Proxy(String), // host:port of the sidecar's HTTP CONNECT proxy
}

/// Errors surfaced by the vpn module.
#[derive(Debug)]
pub enum NetError {
    NoApiKey,
    Fetch(String),
    NoBackend,
    Backend(String),
    Profile(String),
}

impl std::fmt::Display for NetError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NetError::NoApiKey => write!(f, "p2p requires ZAKURO_API_KEY (set it and retry)"),
            NetError::Fetch(e) => write!(f, "failed to fetch WireGuard profile: {}", e),
            NetError::NoBackend => {
                let hint = if cfg!(target_os = "macos") {
                    "install WireGuard (`brew install wireguard-tools wireguard-go`) then re-run with `sudo`, or start Docker Desktop"
                } else {
                    "install WireGuard (`sudo apt install wireguard-tools`) and run as root, or install Docker"
                };
                write!(f, "no usable backend: {hint}")
            }
            NetError::Backend(e) => write!(f, "tunnel backend error: {}", e),
            NetError::Profile(e) => write!(f, "invalid WireGuard profile: {}", e),
        }
    }
}

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

/// Which access mode a live connection provides.
fn access_of(info: &ConnectionInfo) -> Result<MeshAccess, NetError> {
    match (&info.proxy, info.host_routable) {
        (_, true) => Ok(MeshAccess::Host),
        (Some(p), false) => Ok(MeshAccess::Proxy(p.clone())),
        (None, false) => Err(NetError::Backend(
            "tunnel up but host cannot route and no proxy available".into(),
        )),
    }
}

/// True when the tunnel has a recent WireGuard handshake with the mesh server —
/// the authoritative "am I on the mesh" signal. The wg server exposes no TCP
/// service on its mesh IP, so a port probe is meaningless; the handshake is not.
/// Runs `wg show <iface> latest-handshakes` on the host (native) or inside the
/// sidecar (docker), retrying to give a just-started tunnel time to handshake.
fn mesh_handshake_ok(info: &ConnectionInfo) -> bool {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    for attempt in 0..5 {
        if attempt > 0 {
            std::thread::sleep(Duration::from_millis(1200));
        }
        let out = match info.backend {
            Backend::Native => std::process::Command::new("wg")
                .args(["show", "zakuro0", "latest-handshakes"])
                .output()
                .ok(),
            Backend::Docker => std::process::Command::new("docker")
                .args([
                    "exec",
                    &info.link,
                    "wg",
                    "show",
                    "zakuro0",
                    "latest-handshakes",
                ])
                .output()
                .ok(),
        };
        let text = match out {
            Some(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(),
            _ => continue,
        };
        // any peer with a handshake in the last 5 min counts as reachable
        let fresh = text
            .lines()
            .filter_map(|l| l.split_whitespace().nth(1))
            .filter_map(|s| s.parse::<u64>().ok())
            .any(|hs| hs > 0 && now.saturating_sub(hs) < 300);
        if fresh {
            return true;
        }
    }
    false
}

/// Testable core of `ensure`: the verify + connect functions are injected.
fn ensure_with(
    verify_fn: &dyn Fn(&ConnectionInfo) -> bool,
    connect_fn: &dyn Fn() -> Result<ConnectionInfo, NetError>,
    saved: Option<&ConnectionInfo>,
) -> Result<MeshAccess, NetError> {
    // 1./2. reuse a live path (host or container proxy) if it still verifies.
    if let Some(s) = saved {
        if verify_fn(s) {
            return access_of(s);
        }
    }
    // 3. bring it up, then 4. verify — no silent success.
    let info = connect_fn()?;
    if !verify_fn(&info) {
        return Err(NetError::Backend(
            "mesh probe failed — tunnel is up but no handshake with the mesh server".into(),
        ));
    }
    access_of(&info)
}

/// Verified mesh access: reuse a live path or bring the tunnel up, then verify
/// via the WireGuard handshake.
pub fn ensure(pref: Preference) -> Result<MeshAccess, NetError> {
    let saved = status()?; // None if stale/not running
    ensure_with(&mesh_handshake_ok, &|| connect(pref), saved.as_ref())
}

/// True for addresses inside the WireGuard mesh subnet 10.13.13.0/24.
pub fn is_mesh_ip(host: &str) -> bool {
    let p: Vec<&str> = host.split('.').collect();
    p.len() == 4 && p[0] == "10" && p[1] == "13" && p[2] == "13" && p[3].parse::<u8>().is_ok()
}

/// The sidecar CONNECT proxy address ("host:port") from saved state, if any.
/// Callers building their own `ureq::Agent` use this to route mesh traffic.
pub fn mesh_proxy_addr() -> Option<String> {
    state::load().and_then(|s| s.proxy)
}

/// The sidecar CONNECT proxy as a `ureq::Proxy`, for callers that assemble
/// their own agent config: `cfg.proxy(vpn::mesh_proxy())`. `None` when the
/// host routes into the mesh itself (native or hostnet docker) or when no
/// tunnel is recorded — a plain agent is then exactly right.
pub fn mesh_proxy() -> Option<ureq::Proxy> {
    mesh_proxy_addr().and_then(|p| ureq::Proxy::new(&format!("http://{}", p)).ok())
}

/// Ask the hub for the mesh's shared peer key and store it locally so a
/// broker started here (`zc share`, `zc broker`) can act as a full peer.
/// Best-effort: an older hub without `/api/broker/config/mesh` (404) or a
/// missing key is not an error — the tunnel is up either way, the broker
/// just stays a client of the mesh rather than a peer.
pub fn sync_mesh_peer_key() {
    crate::credentials::load_into_env();
    let Ok(api_key) = std::env::var("ZAKURO_API_KEY") else {
        return;
    };
    if api_key.trim().is_empty() {
        return;
    }
    let api_url = crate::credentials::default_api_url();
    let endpoint = format!("{}/api/broker/config/mesh", api_url.trim_end_matches('/'));
    let resp = match ureq::get(&endpoint)
        .config()
        .timeout_global(Some(std::time::Duration::from_secs(10)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", &api_key)
        .call()
    {
        Ok(r) => r,
        Err(e) => {
            vlog(&format!("mesh peer key: request failed ({e})"));
            return;
        }
    };
    let status = resp.status().as_u16();
    if status != 200 {
        vlog(&format!(
            "mesh peer key: hub answered HTTP {status}; not stored"
        ));
        return;
    }
    let Ok(text) = resp.into_body().read_to_string() else {
        return;
    };
    let key = serde_json::from_str::<serde_json::Value>(&text)
        .ok()
        .and_then(|v| {
            v.get("peer_key")
                .and_then(|k| k.as_str())
                .map(str::to_string)
        })
        .filter(|k| !k.trim().is_empty());
    match key {
        Some(k) => match crate::credentials::save_mesh_peer_key(&k) {
            Ok(()) => vlog("mesh peer key stored"),
            Err(e) => eprintln!("  ⚠ could not store the mesh peer key: {e}"),
        },
        None => vlog("mesh peer key: hub response carried no peer_key"),
    }
}

/// HTTP agent for mesh-bound requests: routed through the sidecar CONNECT
/// proxy when the saved connection has one, plain otherwise.
pub fn mesh_agent(timeout: std::time::Duration) -> ureq::Agent {
    let mut cfg = ureq::Agent::config_builder()
        .timeout_connect(Some(timeout))
        .timeout_global(Some(timeout));
    if let Some(saved) = state::load() {
        if let Some(p) = saved.proxy {
            if let Ok(proxy) = ureq::Proxy::new(&format!("http://{}", p)) {
                cfg = cfg.proxy(Some(proxy));
            }
        }
    }
    ureq::Agent::new_with_config(cfg.build())
}

/// Connect to the mesh using the given backend preference.
pub fn connect(pref: Preference) -> Result<ConnectionInfo, NetError> {
    // Idempotent: if a live connection is already recorded, refresh + return it.
    // The peer key is synced on THIS path too: a machine that connected before
    // the hub served the key (or before this build) would otherwise never get
    // it, and its broker would sit on the mesh unable to peer.
    if let Some(existing) = status()? {
        sync_mesh_peer_key();
        return Ok(existing);
    }
    let profile = profile::fetch_wg_profile()?;
    let connector = select_connector(pref)?;
    let info = connector.connect(&profile)?;
    // Same credential, same moment: a machine that can join the tunnel should
    // also be able to run a broker that peers on it.
    sync_mesh_peer_key();
    Ok(info)
}

/// Current connection (None if not connected).
pub fn status() -> Result<Option<ConnectionInfo>, NetError> {
    if let Some(saved) = state::load() {
        let c = select_for_backend(saved.backend);
        if let Ok(Some(info)) = c.status() {
            return Ok(Some(info));
        }
        return Ok(None);
    }
    // No state file. A live tunnel may still exist (the file was deleted, or a
    // different HOME/ZAKURO_STATE_DIR wrote it): adopt it from the backend —
    // the docker helper rebuilds its info from container labels — instead of
    // reporting "not connected" and letting `connect` tear a working tunnel
    // down to build the same one again.
    if let Ok(Some(info)) = docker::DockerConnector.status() {
        return Ok(Some(info));
    }
    if let Ok(Some(info)) = native::NativeConnector.status() {
        return Ok(Some(info));
    }
    Ok(None)
}

/// Fetch this node's WireGuard profile and render it as wg-quick conf text.
/// Lets a host hand the conf to an isolated VPN container (`zc vpn conf`)
/// without bringing up an interface itself.
pub fn conf() -> Result<String, NetError> {
    profile::fetch_wg_profile()?.to_conf()
}

/// Disconnect whichever backend is active.
pub fn disconnect() -> Result<(), NetError> {
    if let Some(saved) = state::load() {
        select_for_backend(saved.backend).disconnect()?;
    } else {
        // Best-effort: tear down both, ignore errors.
        let _ = docker::DockerConnector.disconnect();
        let _ = native::NativeConnector.disconnect();
    }
    Ok(())
}

fn select_for_backend(b: Backend) -> Box<dyn connector::Connector> {
    match b {
        Backend::Native => Box::new(native::NativeConnector),
        Backend::Docker => Box::new(docker::DockerConnector),
    }
}

fn parse_pref(args: &[String]) -> Preference {
    if args.iter().any(|a| a == "--native") {
        Preference::Native
    } else if args.iter().any(|a| a == "--docker") {
        Preference::Docker
    } else {
        Preference::Auto
    }
}

/// Render a one-line human summary of a connection.
fn render(info: &ConnectionInfo) -> String {
    let reachable = info.peers.iter().filter(|p| p.reachable).count();
    let access = match &info.proxy {
        Some(p) if !info.host_routable => format!("proxy {}", p),
        _ => "host".to_string(),
    };
    format!(
        "connected to zakuro mesh — {} · {} · {} peer(s), {} reachable · access: {}",
        info.address,
        info.backend.label(),
        info.peers.len(),
        reachable,
        access,
    )
}

/// CLI entry point for `zc vpn …`. `args` is everything after `vpn`.
pub fn run_cli(args: &[String]) {
    use colored::Colorize;
    set_verbose(args.iter().any(|a| a == "--verbose" || a == "-v"));
    let sub = args.first().map(|s| s.as_str()).unwrap_or("status");
    match sub {
        "connect" | "up" => match connect(parse_pref(args)) {
            Ok(info) => println!("  {} {}", "".green(), render(&info)),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "ensure" => match ensure(parse_pref(args)) {
            Ok(MeshAccess::Host) => {
                println!("  {} mesh verified via host tunnel", "".green())
            }
            Ok(MeshAccess::Proxy(p)) => {
                println!("  {} mesh verified via container proxy {}", "".green(), p)
            }
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "disconnect" | "down" => match disconnect() {
            Ok(()) => println!("  {} disconnected from zakuro mesh", "".green()),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "status" => match status() {
            Ok(Some(info)) => println!("  {}", render(&info)),
            Ok(None) => println!("  not connected (local mode)"),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        "conf" => match conf() {
            Ok(text) => print!("{}", text),
            Err(e) => {
                eprintln!("  {} {}", "".red(), e);
                std::process::exit(1);
            }
        },
        other => {
            eprintln!(
                "usage: zc vpn [connect [--native|--docker] | ensure | disconnect | status | conf] (got '{}')",
                other
            );
            std::process::exit(1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vpn::connector::Preference;

    #[test]
    fn parse_pref_reads_flags() {
        assert_eq!(parse_pref(&["connect".into()]), Preference::Auto);
        assert_eq!(
            parse_pref(&["connect".into(), "--native".into()]),
            Preference::Native
        );
        assert_eq!(
            parse_pref(&["connect".into(), "--docker".into()]),
            Preference::Docker
        );
    }

    const SAMPLE_PROFILE: &str = r#"{
        "interface": { "private_key": "MKCl4DM7FbX1sFUiFd8VqKzdIGUMwJ28rTgFYezsclc=", "address": "10.13.13.6/24" },
        "peer": { "public_key": "/Lzp+YIUBrNgdABzyR221uhfx2uOWi4m5ZAdgxXzhFs=",
                  "endpoint": "144.202.121.242:51822", "allowed_ips": "10.13.13.0/24",
                  "persistent_keepalive": 25 }
    }"#;

    #[test]
    fn connection_info_proxy_roundtrip_and_default() {
        // old state files (no proxy key) still parse
        let legacy = r#"{"backend":"Docker","address":"10.13.13.6/24","link":"zakuro-wg",
                         "peers":[],"host_routable":false}"#;
        let info: ConnectionInfo = serde_json::from_str(legacy).unwrap();
        assert!(info.proxy.is_none());
        let with = ConnectionInfo {
            proxy: Some("127.0.0.1:18888".into()),
            ..info
        };
        let back: ConnectionInfo =
            serde_json::from_str(&serde_json::to_string(&with).unwrap()).unwrap();
        assert_eq!(back.proxy.as_deref(), Some("127.0.0.1:18888"));
    }

    #[test]
    fn ensure_ladder_reuse_host_reuse_proxy_then_connect() {
        use std::cell::Cell;
        // 1. saved native host connection that still verifies → Host (no connect)
        let native_saved = ConnectionInfo {
            backend: Backend::Native,
            address: "10.13.13.6/24".into(),
            link: "zakuro0".into(),
            peers: vec![],
            host_routable: true,
            proxy: None,
        };
        let r = ensure_with(&|_| true, &|| Err(NetError::NoBackend), Some(&native_saved)).unwrap();
        assert!(matches!(r, MeshAccess::Host));
        // 2. saved docker+proxy connection that still verifies → Proxy (no connect)
        let saved = ConnectionInfo {
            backend: Backend::Docker,
            address: "10.13.13.6/24".into(),
            link: "zakuro-wg".into(),
            peers: vec![],
            host_routable: false,
            proxy: Some("127.0.0.1:18888".into()),
        };
        let r = ensure_with(&|_| true, &|| Err(NetError::NoBackend), Some(&saved)).unwrap();
        assert!(matches!(r, MeshAccess::Proxy(ref p) if p == "127.0.0.1:18888"));
        // 3. saved no longer verifies → connect_fn runs; its result must verify too.
        //    verify keeps failing → Err (no silent success).
        let called = Cell::new(false);
        let err = ensure_with(
            &|_| false,
            &|| {
                called.set(true);
                Ok(saved.clone())
            },
            Some(&saved),
        )
        .unwrap_err();
        assert!(called.get());
        assert!(format!("{err}").contains("mesh probe failed"));
        // 4. fresh connect that verifies → Proxy
        let r = ensure_with(&|_| true, &|| Ok(saved.clone()), None).unwrap();
        assert!(matches!(r, MeshAccess::Proxy(_)));
    }

    #[test]
    fn mesh_ip_detection() {
        assert!(is_mesh_ip("10.13.13.4"));
        assert!(is_mesh_ip("10.13.13.254"));
        assert!(!is_mesh_ip("100.82.173.52")); // wireguard
        assert!(!is_mesh_ip("192.168.0.23"));
        assert!(!is_mesh_ip("10.13.14.4"));
        assert!(!is_mesh_ip("localhost"));
    }

    #[test]
    fn mesh_agent_uses_connect_proxy_when_state_has_one() {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        // fake peer: replies to any HTTP request
        let peer = TcpListener::bind("127.0.0.1:0").unwrap();
        let peer_port = peer.local_addr().unwrap().port();
        std::thread::spawn(move || {
            for s in peer.incoming().flatten() {
                let mut s = s;
                let mut b = [0u8; 1024];
                let _ = s.read(&mut b);
                let _ = s.write_all(
                    b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok",
                );
            }
        });
        // mini CONNECT proxy: accepts CONNECT, tunnels to the fake peer
        let proxy = TcpListener::bind("127.0.0.1:0").unwrap();
        let proxy_addr = proxy.local_addr().unwrap();
        std::thread::spawn(move || {
            for c in proxy.incoming().flatten() {
                let mut c = c;
                // read the CONNECT request line + headers (loop until CRLFCRLF)
                let mut req = Vec::new();
                let mut b = [0u8; 256];
                loop {
                    match c.read(&mut b) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            req.extend_from_slice(&b[..n]);
                            if req.windows(4).any(|w| w == b"\r\n\r\n") {
                                break;
                            }
                        }
                    }
                }
                // only a CONNECT to the mesh peer should ever arrive here
                if !String::from_utf8_lossy(&req).starts_with("CONNECT 10.13.13.9:9000") {
                    continue;
                }
                c.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n")
                    .unwrap();
                let mut up = std::net::TcpStream::connect(("127.0.0.1", peer_port)).unwrap();
                let mut c2 = c.try_clone().unwrap();
                let mut up2 = up.try_clone().unwrap();
                std::thread::spawn(move || {
                    let _ = std::io::copy(&mut c2, &mut up);
                });
                let _ = std::io::copy(&mut up2, &mut c);
            }
        });
        // state with proxy → agent must route through it
        let dir = std::env::temp_dir().join(format!("zc-vpn-agent-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::env::set_var("ZAKURO_STATE_DIR", &dir);
        state::save(&ConnectionInfo {
            backend: Backend::Docker,
            address: "10.13.13.6/24".into(),
            link: "zakuro-wg".into(),
            peers: vec![],
            host_routable: false,
            proxy: Some(proxy_addr.to_string()),
        })
        .unwrap();
        let agent = mesh_agent(std::time::Duration::from_secs(3));
        let body = agent
            .get("http://10.13.13.9:9000/health")
            .call()
            .unwrap()
            .into_body()
            .read_to_string()
            .unwrap();
        assert_eq!(body, "ok");
        std::env::remove_var("ZAKURO_STATE_DIR");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn conf_renders_wg_quick_from_profile_file() {
        let dir = std::env::temp_dir().join(format!("zc-vpn-conf-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("wg.json");
        std::fs::write(&path, SAMPLE_PROFILE).unwrap();
        // file hatch requires the explicit opt-in (see profile::fetch_wg_profile)
        std::env::set_var("ZAKURO_ALLOW_FILE_PROFILE", "1");
        std::env::set_var("ZAKURO_WG_PROFILE_FILE", &path);

        let conf = super::conf().expect("conf renders");
        assert!(conf.contains("[Interface]"));
        assert!(conf.contains("Address = 10.13.13.6/24"));
        assert!(conf.contains("[Peer]"));
        assert!(conf.contains("Endpoint = 144.202.121.242:51822"));

        std::env::remove_var("ZAKURO_ALLOW_FILE_PROFILE");
        std::env::remove_var("ZAKURO_WG_PROFILE_FILE");
        let _ = std::fs::remove_dir_all(&dir);
    }
}