zc2 0.0.51

P2P compute broker with yen-denominated 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
use crate::exec;

use std::path::Path;

use std::env;
use std::str;

/// Fetched config, stored as DATA (`KEY=VALUE` lines parsed by zc, never
/// sourced by a shell). ZC-0014.
pub static CONFIG_FILE: &str = "/opt/zakuro/etc/zk0.env";
pub static CONFIG_DIR: &str = "/opt/zakuro/etc";
/// Pre-ZC-0014 location, a directory login shells source. zc never writes it
/// any more; an existing file is read once for migration and left in place.
pub static LEGACY_CONFIG_FILE: &str = "/opt/zakuro/etc/profile.d/zk0.sh";
use std::collections::HashSet;
pub fn eval(s1: &str) -> String {
    evaluate_expr(s1)
}
use crate::common::print_debug;

// fn skip_first_char_if_slash(output: &str) -> Result<String, String> {
//     // Check if the string is long enough to slice
//     if !output.is_empty() && output.starts_with('/') {
//         let result: String = output[1..].to_string();
//         return Ok(result);
//     } else if !output.is_empty() {
//         return Ok(output.to_string());
//     }
//     Err(String::from("String is empty!"))
// }

pub fn evaluate_expr(s1: &str) -> String {
    let mut output: String = String::from("");
    if !s1.starts_with("'") {
        // Extract path x:x
        for pathx in s1.split(':') {
            // For each x split by /
            let splits: Vec<&str> = pathx.split("/").collect();
            let condition: bool = splits.len() > 1;
            for varpath in splits {
                if let Some('$') = varpath.chars().next() {
                    let _varpath = &varpath[1..];
                    if let Ok(s) = env::var(_varpath) {
                        // println!("found: {:?}",&s);
                        env::set_var(_varpath, &s);
                        output.push_str(&s.to_string());
                    } else {
                        // println!("(var not found) ${:?}", _varpath);
                        output.push_str((&varpath).as_ref());
                    }
                } else if condition {
                    output.push_str(&format!("/{}", varpath));
                } else {
                    output.push_str((&varpath).as_ref());
                }
            }
            output.push(':');
        }
        if output.ends_with(':') {
            output = output[..output.len() - 1].to_string();
        }
        // match skip_first_char_if_slash(output.clone()){
        //     Ok(res) => {
        //         output = res;
        //     }
        //     Err(e) => {
        //         eprintln!("{}", e);
        //     }
        // }

        // output = skip_first_char_if_slash(&output).unwrap_or_else(|e| {
        //     eprintln!("{}", e);
        //     output.clone()  // Return the original output in case of an error
        // });

        // if (&output[1..]).to_string().starts_with('/') {
        //     output = (&output[1..]).to_string();
        // }
        output = output.replace("//", "/");
        // println!("{:?}",output);
        let string_list: Vec<&str> = output.split(":").collect();
        // Create a HashSet to store unique values
        let unique_values: HashSet<_> = string_list.into_iter().collect();
        // Convert the HashSet back to a Vec if needed
        let unique_list: Vec<_> = unique_values.into_iter().collect();
        // println!("{:?}", unique_list);
        output = unique_list.join(":");
    } else {
        output = String::from(s1);
    }

    output
}

/// Parse fetched config as strict `KEY=VALUE` data. Blank lines and `#`
/// comments are skipped, one optional leading `export ` is tolerated (old
/// files), and everything else must be a plain assignment. A line with shell
/// syntax (command substitution, backticks, `;`, `&`, `|`, redirections,
/// subshells, `${...}`, a bare `$`, control characters), a bad key or no `=`
/// is REJECTED individually: it is returned in the second list as
/// `(line number, key if any)` (never the value) and never applied. The other
/// lines still apply, so one unsupported line cannot drop a host's config.
pub type Assignments = Vec<(String, String)>;
pub type Rejected = Vec<(usize, String)>;

pub fn parse_config(content: &str) -> (Assignments, Rejected) {
    let mut out = Vec::new();
    let mut rejected = Vec::new();
    for (n, raw) in content.lines().enumerate() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let line = line.strip_prefix("export ").unwrap_or(line).trim_start();
        let Some((key, value)) = line.split_once('=') else {
            rejected.push((n + 1, String::new()));
            continue;
        };
        let mut kc = key.chars();
        let key_ok = matches!(kc.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
            && kc.all(|c| c.is_ascii_alphanumeric() || c == '_');
        if !key_ok {
            rejected.push((n + 1, String::new()));
            continue;
        }
        let chars: Vec<char> = value.chars().collect();
        let bad = chars.iter().enumerate().any(|(i, c)| {
            c.is_control()
                || matches!(
                    c,
                    '`' | ';' | '&' | '|' | '<' | '>' | '(' | ')' | '{' | '}' | '\\'
                )
                || (*c == '$'
                    && !matches!(chars.get(i + 1), Some(d) if d.is_ascii_alphabetic() || *d == '_'))
        });
        if bad {
            rejected.push((n + 1, key.to_string()));
            continue;
        }
        out.push((key.to_string(), value.to_string()));
    }
    (out, rejected)
}

/// Fetch `url` with the `X-Content-SHA256` check and write the body to `path`
/// as data. A digest mismatch (or missing header) fails before anything is
/// written; per-line parsing (`parse_config`) happens later, on read.
fn fetch_config_to(agent: &ureq::Agent, url: &str, path: &str) -> Result<(), String> {
    let body = crate::verified_fetch::fetch_verified(agent, url)?;
    std::fs::write(path, body).map_err(|e| format!("writing {}: {}", path, e))
}

/// Set (to anything) to never bootstrap the legacy `zk0.env`. The desktop app
/// sets it on every zc it runs; an existing `zk0.env` is still applied.
pub const NO_ENV_PROFILE_VAR: &str = "ZC_NO_ENV_PROFILE";

fn dir_is_writable(dir: &str) -> bool {
    std::fs::metadata(dir).is_ok_and(|m| m.is_dir() && !m.permissions().readonly())
        && tempfile_probe(dir)
}

/// `readonly()` only reads the mode bits; a root-owned 0755 dir looks
/// writable. Creating a file is the only honest answer.
fn tempfile_probe(dir: &str) -> bool {
    let p = Path::new(dir).join(format!(".zc-write-probe-{}", std::process::id()));
    let ok = std::fs::write(&p, b"").is_ok();
    let _ = std::fs::remove_file(&p);
    ok
}

/// Whether a missing `zk0.env` may be bootstrapped (`sudo mkdir` + fetch).
/// The file only carries the Spark-era Linux fleet's defaults, so never on
/// macOS and never when opted out. Without a writable dir it needs sudo, and
/// sudo needs a terminal: a zc started by the desktop app, launchd or systemd
/// used to print "sudo: a terminal is required", "Permission denied" and
/// "Error reading config" on every run (the desktop cold start).
fn may_bootstrap(dir_writable: bool, interactive: bool, opted_out: bool, macos: bool) -> bool {
    !opted_out && !macos && (dir_writable || interactive)
}

/// What to do about a config dir that is not writable.
#[derive(Debug, PartialEq, Eq)]
enum DirFix {
    /// `create_dir_all` already made it usable.
    Done,
    /// Fall back to `sudo mkdir` + `sudo chown`.
    Sudo,
    /// Neither works: skip the env profile.
    Skip,
}

fn dir_fix_plan(created: bool, sudo_available: bool) -> DirFix {
    if created {
        DirFix::Done
    } else if sudo_available {
        DirFix::Sudo
    } else {
        DirFix::Skip
    }
}

fn sudo_on_path() -> bool {
    env::var_os("PATH").is_some_and(|p| env::split_paths(&p).any(|d| d.join("sudo").is_file()))
}

pub fn update() {
    // The lab profile has no legacy `/env` profile: a node's environment comes
    // from its `node.env`. Without this every zc start there tried `sudo mkdir
    // /opt/zakuro/etc` and logged "Error downloading env profile" for a file
    // that only carries the Spark-era fleet's defaults. A `zk0.env` that does
    // exist is still applied.
    let profile = crate::profile::active();
    if !profile.legacy_env_profile && !Path::new(CONFIG_FILE).exists() {
        return;
    }
    if !Path::new(CONFIG_FILE).exists() {
        if let Ok(legacy) = std::fs::read_to_string(LEGACY_CONFIG_FILE) {
            // Migration: read the old profile.d script as data (never
            // executed). The legacy file itself is left untouched.
            // Copy only the valid assignments.
            let (ok, _) = parse_config(&legacy);
            let data: String = ok.iter().map(|(k, v)| format!("{}={}\n", k, v)).collect();
            let _ = std::fs::write(CONFIG_FILE, data);
        }
    }
    let dir_writable = dir_is_writable(CONFIG_DIR);
    if !Path::new(CONFIG_FILE).exists()
        && !may_bootstrap(
            dir_writable,
            std::io::IsTerminal::is_terminal(&std::io::stdin()),
            env::var_os(NO_ENV_PROFILE_VAR).is_some(),
            cfg!(target_os = "macos"),
        )
    {
        return;
    }
    if !Path::new(CONFIG_FILE).exists() {
        if !dir_writable {
            // Root (containers) can just create it; sudo is the fallback and
            // only when it exists.
            let created =
                std::fs::create_dir_all(CONFIG_DIR).is_ok() && dir_is_writable(CONFIG_DIR);
            match dir_fix_plan(created, sudo_on_path()) {
                DirFix::Done => {}
                DirFix::Sudo => {
                    for command in [
                        &format!("sudo mkdir -p {}", CONFIG_DIR),
                        &format!("sudo chown -R $USER {}", CONFIG_DIR),
                    ] {
                        exec::tty(command);
                    }
                }
                DirFix::Skip => {
                    eprintln!("zc: cannot create {}; skipping the env profile", CONFIG_DIR);
                    return;
                }
            }
        }
        // Fetched over HTTPS with the X-Content-SHA256 check (no shell); on
        // any failure nothing is written. Location is unchanged (see #385).
        let url = format!("{}/env", profile.get_base);
        let agent = ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .timeout_global(Some(std::time::Duration::from_secs(30)))
                .build(),
        );
        if let Err(e) = fetch_config_to(&agent, &url, CONFIG_FILE) {
            eprintln!("Error downloading env profile: {}", e);
        }
    }

    let content = match std::fs::read_to_string(CONFIG_FILE) {
        Ok(content) => content,
        Err(e) => {
            eprintln!("Error reading config: {}", e);
            return;
        }
    };
    apply_script(&content);
}

/// `all` is a valid `NVIDIA_VISIBLE_DEVICES` (container runtime) value but not a
/// valid `CUDA_VISIBLE_DEVICES` one: libcuda reads it as "no device is visible"
/// and `cuInit` fails with 100 (CUDA_ERROR_NO_DEVICE). The profile script ships
/// `CUDA_VISIBLE_DEVICES=all`, so exporting it blinds every CUDA call this
/// process (and its children) makes. Leaving it unset means "all devices".
fn is_invalid_cuda_mask(key: &str, value: &str) -> bool {
    key == "CUDA_VISIBLE_DEVICES" && value.trim().eq_ignore_ascii_case("all")
}

fn apply_script(script_content: &str) {
    let (assignments, rejected) = parse_config(script_content);
    for (line, key) in rejected {
        eprintln!(
            "zc: ignoring line {} of {} (shell syntax or not KEY=VALUE){}",
            line,
            CONFIG_FILE,
            if key.is_empty() {
                String::new()
            } else {
                format!(": {}", key)
            }
        );
    }
    for (key, _value) in assignments {
        if env::var(&key).is_err() {
            let value = evaluate_expr(&_value);
            print_debug(&format!("{}={}", key, value));
            if is_invalid_cuda_mask(&key, &value) {
                continue;
            }
            env::set_var(key, value);
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn dir_fix_plan_prefers_create_then_sudo_then_skip() {
        assert_eq!(dir_fix_plan(true, true), DirFix::Done);
        assert_eq!(dir_fix_plan(true, false), DirFix::Done);
        assert_eq!(dir_fix_plan(false, true), DirFix::Sudo);
        assert_eq!(dir_fix_plan(false, false), DirFix::Skip);
    }

    use super::*;

    #[test]
    fn a_gui_or_service_zc_never_reaches_for_sudo() {
        // (dir_writable, interactive, opted_out, macos)
        assert!(
            !may_bootstrap(false, false, false, false),
            "launchd/systemd/app: no tty for sudo"
        );
        assert!(!may_bootstrap(true, true, false, true), "never on macOS");
        assert!(
            !may_bootstrap(true, true, true, false),
            "ZC_NO_ENV_PROFILE wins"
        );
        assert!(
            may_bootstrap(false, true, false, false),
            "a terminal on a fleet node may sudo"
        );
        assert!(
            may_bootstrap(true, false, false, false),
            "a writable dir needs no sudo"
        );
    }

    #[test]
    fn a_missing_dir_is_not_writable() {
        assert!(!dir_is_writable("/nonexistent/zc-envs-test"));
        let d = std::env::temp_dir();
        assert!(dir_is_writable(d.to_str().unwrap()));
    }

    /// Regression: x399's profile script has `CUDA_VISIBLE_DEVICES=all`; applying
    /// it made `zc bench node` report `cuInit returned 100` and zero GPUs.
    #[test]
    fn profile_script_does_not_blind_cuda() {
        env::remove_var("CUDA_VISIBLE_DEVICES");
        apply_script("CUDA_VISIBLE_DEVICES=all\nZC_ENVS_TEST_MARKER=1\n");
        assert!(env::var("CUDA_VISIBLE_DEVICES").is_err());
        assert_eq!(env::var("ZC_ENVS_TEST_MARKER").as_deref(), Ok("1"));
        env::remove_var("ZC_ENVS_TEST_MARKER");
    }

    #[test]
    fn real_cuda_masks_are_kept() {
        assert!(!is_invalid_cuda_mask("CUDA_VISIBLE_DEVICES", "0,1"));
        assert!(!is_invalid_cuda_mask("CUDA_VISIBLE_DEVICES", "GPU-abc"));
        assert!(!is_invalid_cuda_mask("NVIDIA_VISIBLE_DEVICES", "all"));
        assert!(is_invalid_cuda_mask("CUDA_VISIBLE_DEVICES", "all"));
    }

    #[test]
    fn lines_with_shell_syntax_are_rejected() {
        for bad in [
            "A=$(touch /tmp/x)",
            "A=`id`",
            "A=1; rm -rf ~",
            "A=1 && id",
            "A=${HOME}",
            "A=$",
            "A=b|c",
            "A=b>c",
            "not an assignment",
            "1BAD=x",
            "A B=x",
        ] {
            let (ok, rej) = parse_config(bad);
            assert!(ok.is_empty(), "should not apply {:?}", bad);
            assert_eq!(rej.len(), 1, "should reject {:?}", bad);
        }
        // Only the bad line is dropped; the rest still apply.
        env::remove_var("ZC_ENVS_TEST_GOOD");
        env::remove_var("ZC_ENVS_TEST_BAD");
        apply_script("ZC_ENVS_TEST_GOOD=1\nZC_ENVS_TEST_BAD=$(id)\n");
        assert_eq!(env::var("ZC_ENVS_TEST_GOOD").as_deref(), Ok("1"));
        assert!(env::var("ZC_ENVS_TEST_BAD").is_err());
        env::remove_var("ZC_ENVS_TEST_GOOD");
    }

    /// The live prod `/env` body (2026-10-04) carries `ZAK_IP=$(zc wg0ip)`.
    /// That line is dropped, every other key still applies.
    #[test]
    fn prod_env_body_applies_all_but_command_substitution() {
        let body = "ZAKURO_HOME=$HOME/.zakuro\nZAKURO_CONTEXT=$ZAKURO_HOME/node\nZAKURO_ROOT=/opt/zakuro\nZAKURO_BIN=$ZAKURO_ROOT/bin\nPYENV=\"zak310\"\nZAK_PYTHON=/opt/miniconda/envs/$PYENV/bin\nPATH=$PATH:$ZAK_PYTHON:/usr/bin:/usr/local/bin:/usr/bin:$SPARK_HOME/bin:$SPARK_HOME/sbin:$ZAKURO_BIN\nSPARK_HOME=/opt/spark\nMASTER_HOST=\"10.13.13.2\"\nSPARK_MASTER='spark://$MASTER_HOST:$SPARK_MASTER_PORT'\nSPARK_NO_DAEMONIZE=true\nZAK_IP=$(zc wg0ip)\nSPARK_LOCAL_IP=$ZAK_IP\n";
        let (ok, rej) = parse_config(body);
        assert_eq!(rej, vec![(12, "ZAK_IP".to_string())]);
        assert_eq!(ok.len(), 12);
        assert!(ok.iter().any(|(k, _)| k == "PATH"));
        assert!(ok.iter().any(|(k, _)| k == "SPARK_LOCAL_IP"));
        assert!(!ok.iter().any(|(k, _)| k == "ZAK_IP"));
    }

    #[test]
    fn plain_assignments_parse() {
        let (v, rej) = parse_config("# c\n\nexport A=1\nPATH=$PATH:/opt/zakuro/bin\nB='x'\n");
        assert!(rej.is_empty());
        assert_eq!(v.len(), 3);
        assert_eq!(v[1], ("PATH".into(), "$PATH:/opt/zakuro/bin".into()));
    }

    fn serve(body: &'static str, digest: String) -> String {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let addr = server.server_addr().to_ip().unwrap();
        std::thread::spawn(move || {
            if let Ok(req) = server.recv() {
                let h = tiny_http::Header::from_bytes(
                    crate::verified_fetch::HASH_HEADER.as_bytes(),
                    digest.as_bytes(),
                )
                .unwrap();
                let _ = req.respond(tiny_http::Response::from_string(body).with_header(h));
            }
        });
        format!("http://{addr}/env")
    }

    fn sha(b: &str) -> String {
        hex::encode(ring::digest::digest(&ring::digest::SHA256, b.as_bytes()))
    }

    fn agent() -> ureq::Agent {
        ureq::Agent::new_with_config(ureq::Agent::config_builder().build())
    }

    /// #378 + #385: a verified body with a command substitution is written to
    /// the config file as data, then parsed per line: only that line is rejected.
    #[test]
    fn verified_body_is_written_then_only_shell_line_rejected() {
        let body = "ZAKURO_ROOT=/opt/zakuro\nZAK_IP=$(zc wg0ip)\nSPARK_NO_DAEMONIZE=true\n";
        let url = serve(body, sha(body));
        let dir = std::env::temp_dir().join(format!("zc-envs-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("zk0.env");
        fetch_config_to(&agent(), &url, path.to_str().unwrap()).unwrap();
        let written = std::fs::read_to_string(&path).unwrap();
        assert_eq!(written, body);
        let (ok, rej) = parse_config(&written);
        assert_eq!(rej, vec![(2, "ZAK_IP".to_string())]);
        assert_eq!(ok.len(), 2);
    }

    /// A tampered body is rejected before anything is written.
    #[test]
    fn tampered_body_writes_nothing() {
        let url = serve("ZAKURO_ROOT=/evil\n", sha("ZAKURO_ROOT=/opt/zakuro\n"));
        let dir = std::env::temp_dir().join(format!("zc-envs-{}-{}", std::process::id(), line!()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("zk0.env");
        assert!(fetch_config_to(&agent(), &url, path.to_str().unwrap()).is_err());
        assert!(!path.exists());
    }

    /// No code path may point the fetched-config file at a shell-sourced dir.
    #[test]
    fn config_file_is_not_shell_sourced() {
        assert!(!CONFIG_FILE.contains("profile.d"));
        assert!(!CONFIG_DIR.contains("profile.d"));
        assert!(!CONFIG_FILE.ends_with(".sh"));
    }
}