zlayer-paths 0.11.3

Centralized filesystem path resolution for ZLayer
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
use std::path::{Path, PathBuf};

/// Centralized filesystem path resolution for ZLayer.
///
/// All ZLayer crates should use this instead of hardcoding paths.
pub struct ZLayerDirs {
    data_dir: PathBuf,
}

impl ZLayerDirs {
    /// Create from an explicit data directory.
    pub fn new(data_dir: impl Into<PathBuf>) -> Self {
        Self {
            data_dir: data_dir.into(),
        }
    }

    /// Create using the platform default data directory.
    pub fn system_default() -> Self {
        Self::new(Self::default_data_dir())
    }

    // -- Platform defaults (associated functions) ----------------------------

    /// Platform-aware default data directory.
    ///
    /// - macOS: `~/.zlayer`
    /// - Linux (root): `/var/lib/zlayer`
    /// - Linux (user): `~/.zlayer`
    /// - Windows: `%ProgramData%\ZLayer` (system) or `C:\ProgramData\ZLayer`
    ///   fallback. HCS-backed nodes run as SYSTEM so the system-wide
    ///   `ProgramData` location is the right default.
    pub fn default_data_dir() -> PathBuf {
        #[cfg(target_os = "macos")]
        {
            home_dir_or_tmp().join(".zlayer")
        }
        #[cfg(target_os = "windows")]
        {
            windows_program_data_root()
        }
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            if is_root() {
                PathBuf::from("/var/lib/zlayer")
            } else {
                home_dir_or_tmp().join(".zlayer")
            }
        }
    }

    /// Detect the data directory of an existing installation.
    ///
    /// On Linux, if not root, checks whether `/var/lib/zlayer/daemon.json`
    /// exists (indicating a system-level install) and returns
    /// `/var/lib/zlayer` if so. On Windows, probes `%ProgramData%\ZLayer`
    /// for a `daemon.json` marker in case the caller lacks the env var but
    /// a prior system install is present. Otherwise falls back to
    /// [`default_data_dir`].
    pub fn detect_data_dir() -> PathBuf {
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            if !is_root() {
                let system_data = PathBuf::from("/var/lib/zlayer");
                if system_data.join("daemon.json").exists() {
                    return system_data;
                }
            }
        }
        #[cfg(target_os = "windows")]
        {
            let system_data = windows_program_data_root();
            if system_data.join("daemon.json").exists() {
                return system_data;
            }
        }
        Self::default_data_dir()
    }

    /// Default runtime directory.
    ///
    /// - Linux: `/var/run/zlayer`
    /// - macOS: `{default_data_dir}/run`
    /// - Windows: `{default_data_dir}\run` (i.e. `%ProgramData%\ZLayer\run`)
    pub fn default_run_dir() -> PathBuf {
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            PathBuf::from("/var/run/zlayer")
        }
        #[cfg(any(target_os = "macos", target_os = "windows"))]
        {
            Self::default_data_dir().join("run")
        }
    }

    /// Default log directory.
    ///
    /// - Linux: `/var/log/zlayer`
    /// - macOS: `{default_data_dir}/logs`
    /// - Windows: `{default_data_dir}\logs` (i.e. `%ProgramData%\ZLayer\logs`)
    pub fn default_log_dir() -> PathBuf {
        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
        {
            PathBuf::from("/var/log/zlayer")
        }
        #[cfg(any(target_os = "macos", target_os = "windows"))]
        {
            Self::default_data_dir().join("logs")
        }
    }

    /// Default Unix socket path.
    ///
    /// - Linux: `/var/run/zlayer.sock`
    /// - macOS: `{default_data_dir}/run/zlayer.sock`
    /// - Windows: `tcp://127.0.0.1:3669`
    pub fn default_socket_path() -> String {
        #[cfg(target_os = "windows")]
        {
            "tcp://127.0.0.1:3669".to_string()
        }
        #[cfg(not(target_os = "windows"))]
        {
            #[cfg(target_os = "macos")]
            {
                Self::default_data_dir()
                    .join("run")
                    .join("zlayer.sock")
                    .to_string_lossy()
                    .into_owned()
            }
            #[cfg(not(target_os = "macos"))]
            {
                "/var/run/zlayer.sock".to_string()
            }
        }
    }

    /// Default Docker-compatible API socket path.
    ///
    /// - Linux (root): `/var/run/zlayer/docker.sock`
    /// - Linux (user, `XDG_RUNTIME_DIR` set): `{XDG_RUNTIME_DIR}/zlayer/docker.sock`
    /// - Linux (user, no `XDG_RUNTIME_DIR`): `{default_data_dir}/run/docker.sock`
    /// - macOS: `{default_data_dir}/run/docker.sock`
    /// - Windows: `\\.\pipe\zlayer-docker`
    pub fn default_docker_socket_path() -> String {
        #[cfg(target_os = "windows")]
        {
            r"\\.\pipe\zlayer-docker".to_string()
        }
        #[cfg(not(target_os = "windows"))]
        {
            #[cfg(target_os = "macos")]
            {
                Self::default_data_dir()
                    .join("run")
                    .join("docker.sock")
                    .to_string_lossy()
                    .into_owned()
            }
            #[cfg(not(target_os = "macos"))]
            {
                if is_root() {
                    "/var/run/zlayer/docker.sock".to_string()
                } else if let Some(xdg) = std::env::var_os("XDG_RUNTIME_DIR") {
                    let mut p = PathBuf::from(xdg);
                    p.push("zlayer");
                    p.push("docker.sock");
                    p.to_string_lossy().into_owned()
                } else {
                    Self::default_data_dir()
                        .join("run")
                        .join("docker.sock")
                        .to_string_lossy()
                        .into_owned()
                }
            }
        }
    }

    /// Preferred system directory for the `zlayer` binary.
    ///
    /// Tries `/usr/local/bin` first (standard FHS, writable on most systems).
    /// Falls back to `{data_dir}/bin` (`/var/lib/zlayer/bin` on Linux as root)
    /// which is always writable since `ZLayer` owns that directory.
    ///
    /// On macOS and Windows, returns `/usr/local/bin` or the data-dir `bin`
    /// subdirectory respectively.
    pub fn default_binary_dir() -> PathBuf {
        // Probe /usr/local/bin writability — metadata mode bits lie on overlayfs
        #[cfg(unix)]
        {
            let probe = PathBuf::from("/usr/local/bin/.zlayer_write_probe");
            if std::fs::write(&probe, b"").is_ok() {
                let _ = std::fs::remove_file(&probe);
                return PathBuf::from("/usr/local/bin");
            }
        }
        // Fallback: our own bin dir (always writable)
        let dirs = Self::system_default();
        let bin_dir = dirs.bin();
        let _ = std::fs::create_dir_all(&bin_dir);
        bin_dir
    }

    // -- Core subdirectories -------------------------------------------------

    /// Root data directory.
    pub fn data_dir(&self) -> &Path {
        &self.data_dir
    }

    /// Container state directory (`{data}/containers`).
    pub fn containers(&self) -> PathBuf {
        self.data_dir.join("containers")
    }

    /// Unpacked image rootfs directory (`{data}/rootfs`).
    pub fn rootfs(&self) -> PathBuf {
        self.data_dir.join("rootfs")
    }

    /// OCI bundle directory (`{data}/bundles`).
    pub fn bundles(&self) -> PathBuf {
        self.data_dir.join("bundles")
    }

    /// Image/blob cache directory (`{data}/cache`).
    pub fn cache(&self) -> PathBuf {
        self.data_dir.join("cache")
    }

    /// Named volumes directory (`{data}/volumes`).
    pub fn volumes(&self) -> PathBuf {
        self.data_dir.join("volumes")
    }

    /// WASM module cache directory (`{data}/wasm`).
    pub fn wasm(&self) -> PathBuf {
        self.data_dir.join("wasm")
    }

    /// AOT-compiled WASM cache directory (`{data}/wasm/compiled`).
    pub fn wasm_compiled(&self) -> PathBuf {
        self.data_dir.join("wasm").join("compiled")
    }

    /// Encrypted secrets store directory (`{data}/secrets`).
    pub fn secrets(&self) -> PathBuf {
        self.data_dir.join("secrets")
    }

    /// TLS certificate storage directory (`{data}/certs`).
    pub fn certs(&self) -> PathBuf {
        self.data_dir.join("certs")
    }

    /// Raft consensus data directory (`{data}/raft`).
    pub fn raft(&self) -> PathBuf {
        self.data_dir.join("raft")
    }

    /// Admin password file path (`{data}/admin_password`).
    pub fn admin_password(&self) -> PathBuf {
        self.data_dir.join("admin_password")
    }

    /// Path to the persisted local-admin bearer token file.
    ///
    /// On Linux/macOS this file is informational — the daemon's UDS middleware
    /// already injects the bearer into UDS-originated requests. On Windows the
    /// `DaemonClient` reads this file on connect to authenticate against the
    /// loopback TCP listener (which has no socket-path-based local-admin
    /// bypass).
    ///
    /// Default: `<data_dir>/admin_bearer.token`
    ///
    /// On Windows this resolves under `%ProgramData%\ZLayer` so the file
    /// inherits the parent ACL (SYSTEM + Administrators write, Users read),
    /// which is adequate for the local-admin bearer.
    #[must_use]
    pub fn admin_bearer_path(&self) -> PathBuf {
        self.data_dir.join("admin_bearer.token")
    }

    /// Daemon metadata file path (`{data}/daemon.json`).
    pub fn daemon_json(&self) -> PathBuf {
        self.data_dir.join("daemon.json")
    }

    /// Path to the agent's local IPAM (per-node slice allocator) state file.
    pub fn agent_ipam_state(&self) -> PathBuf {
        self.data_dir.join("agent_ipam.json")
    }

    /// Logs subdirectory under data_dir (`{data}/logs`).
    /// Used on macOS where logs live under the user data dir.
    pub fn logs(&self) -> PathBuf {
        self.data_dir.join("logs")
    }

    // -- macOS sandbox / builder paths ---------------------------------------

    /// macOS VM state directory (`{data}/vms`).
    pub fn vms(&self) -> PathBuf {
        self.data_dir.join("vms")
    }

    /// OCI image storage directory (`{data}/images`).
    pub fn images(&self) -> PathBuf {
        self.data_dir.join("images")
    }

    /// Local binary directory (`{data}/bin`).
    pub fn bin(&self) -> PathBuf {
        self.data_dir.join("bin")
    }

    /// Toolchain download cache directory (`{data}/toolchain-cache`).
    pub fn toolchain_cache(&self) -> PathBuf {
        self.data_dir.join("toolchain-cache")
    }

    /// Temporary build directory (`{data}/tmp`).
    pub fn tmp(&self) -> PathBuf {
        self.data_dir.join("tmp")
    }
}

/// Convenience: `ZLayerDirs::system_default().admin_bearer_path()`.
#[must_use]
pub fn default_admin_bearer_path() -> PathBuf {
    ZLayerDirs::system_default().admin_bearer_path()
}

// -- Internal helpers --------------------------------------------------------

#[cfg(not(target_os = "windows"))]
fn home_dir_or_tmp() -> PathBuf {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/tmp"))
}

/// Resolve the Windows system-wide ZLayer data root.
///
/// Uses `%ProgramData%` (typically `C:\ProgramData`) when present, falling
/// back to the literal `C:\ProgramData\ZLayer` path when the env var is
/// missing (as can happen under a stripped-down service account).
#[cfg(target_os = "windows")]
fn windows_program_data_root() -> PathBuf {
    if let Some(program_data) = std::env::var_os("PROGRAMDATA") {
        let mut p = PathBuf::from(program_data);
        p.push("ZLayer");
        p
    } else {
        PathBuf::from(r"C:\ProgramData\ZLayer")
    }
}

/// Returns `true` when the current process is running with superuser /
/// Administrator privileges.
///
/// - Unix: true when the effective UID is `0`.
/// - Windows: true when the current process token is a member of the
///   built-in Administrators group (checked via `IsUserAnAdmin`).
/// - Other targets: always returns `false`.
#[cfg(unix)]
#[must_use]
pub fn is_root() -> bool {
    // SAFETY: `geteuid` is always safe to call and is thread-safe.
    unsafe { libc::geteuid() == 0 }
}

/// Returns `true` when the current process is running with superuser /
/// Administrator privileges.
#[cfg(windows)]
#[must_use]
pub fn is_root() -> bool {
    use windows::Win32::UI::Shell::IsUserAnAdmin;
    // SAFETY: `IsUserAnAdmin` has no preconditions and returns a BOOL.
    unsafe { IsUserAnAdmin().as_bool() }
}

/// Fallback for non-unix, non-windows targets.
#[cfg(not(any(unix, windows)))]
#[must_use]
pub fn is_root() -> bool {
    false
}

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

    // Windows tests below mutate the `PROGRAMDATA` env var to exercise
    // platform-default path resolution. Cargo runs tests concurrently,
    // so readers (`system_default`, `default_admin_bearer_path`) must
    // serialize against the mutators or they race and observe a mix of
    // pre- and post-mutation env state.
    #[cfg(target_os = "windows")]
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn subdirectories_are_relative_to_data_dir() {
        let dirs = ZLayerDirs::new("/test/data");
        assert_eq!(dirs.containers(), PathBuf::from("/test/data/containers"));
        assert_eq!(dirs.rootfs(), PathBuf::from("/test/data/rootfs"));
        assert_eq!(dirs.bundles(), PathBuf::from("/test/data/bundles"));
        assert_eq!(dirs.cache(), PathBuf::from("/test/data/cache"));
        assert_eq!(dirs.volumes(), PathBuf::from("/test/data/volumes"));
        assert_eq!(dirs.wasm(), PathBuf::from("/test/data/wasm"));
        assert_eq!(
            dirs.wasm_compiled(),
            PathBuf::from("/test/data/wasm/compiled")
        );
        assert_eq!(dirs.secrets(), PathBuf::from("/test/data/secrets"));
        assert_eq!(dirs.certs(), PathBuf::from("/test/data/certs"));
        assert_eq!(dirs.raft(), PathBuf::from("/test/data/raft"));
        assert_eq!(
            dirs.admin_password(),
            PathBuf::from("/test/data/admin_password")
        );
        assert_eq!(dirs.daemon_json(), PathBuf::from("/test/data/daemon.json"));
        assert_eq!(dirs.logs(), PathBuf::from("/test/data/logs"));
        assert_eq!(dirs.vms(), PathBuf::from("/test/data/vms"));
        assert_eq!(dirs.images(), PathBuf::from("/test/data/images"));
        assert_eq!(dirs.bin(), PathBuf::from("/test/data/bin"));
        assert_eq!(
            dirs.toolchain_cache(),
            PathBuf::from("/test/data/toolchain-cache")
        );
        assert_eq!(dirs.tmp(), PathBuf::from("/test/data/tmp"));
    }

    #[test]
    fn system_default_uses_default_data_dir() {
        #[cfg(target_os = "windows")]
        let _env_guard = ENV_LOCK.lock().unwrap();
        let dirs = ZLayerDirs::system_default();
        assert_eq!(dirs.data_dir(), ZLayerDirs::default_data_dir().as_path());
    }

    #[test]
    fn admin_bearer_path_is_under_data_dir() {
        let dirs = ZLayerDirs::new(PathBuf::from("/tmp/zlayer-test"));
        assert_eq!(
            dirs.admin_bearer_path(),
            PathBuf::from("/tmp/zlayer-test/admin_bearer.token")
        );
    }

    #[test]
    fn default_admin_bearer_path_matches_system_default() {
        #[cfg(target_os = "windows")]
        let _env_guard = ENV_LOCK.lock().unwrap();
        assert_eq!(
            default_admin_bearer_path(),
            ZLayerDirs::system_default().admin_bearer_path()
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_default_data_dir_uses_program_data() {
        let _env_guard = ENV_LOCK.lock().unwrap();
        let prev = std::env::var_os("PROGRAMDATA");
        std::env::set_var("PROGRAMDATA", r"C:\TestProgramData");

        let data = ZLayerDirs::default_data_dir();
        assert_eq!(data, PathBuf::from(r"C:\TestProgramData\ZLayer"));

        // Sub-paths should live under the ProgramData root.
        let dirs = ZLayerDirs::system_default();
        assert_eq!(dirs.certs(), data.join("certs"));
        assert_eq!(dirs.secrets(), data.join("secrets"));
        assert_eq!(dirs.logs(), data.join("logs"));

        // Run/log helpers should also honour the ProgramData root.
        assert_eq!(ZLayerDirs::default_run_dir(), data.join("run"));
        assert_eq!(ZLayerDirs::default_log_dir(), data.join("logs"));

        // Socket path on Windows is a TCP loopback endpoint, not a filesystem
        // path.
        assert_eq!(ZLayerDirs::default_socket_path(), "tcp://127.0.0.1:3669");

        match prev {
            Some(v) => std::env::set_var("PROGRAMDATA", v),
            None => std::env::remove_var("PROGRAMDATA"),
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_default_data_dir_fallback_when_env_missing() {
        let _env_guard = ENV_LOCK.lock().unwrap();
        let prev = std::env::var_os("PROGRAMDATA");
        std::env::remove_var("PROGRAMDATA");

        let data = ZLayerDirs::default_data_dir();
        assert_eq!(data, PathBuf::from(r"C:\ProgramData\ZLayer"));

        if let Some(v) = prev {
            std::env::set_var("PROGRAMDATA", v);
        }
    }

    #[test]
    fn default_docker_socket_path_not_empty() {
        let result = ZLayerDirs::default_docker_socket_path();
        assert!(!result.is_empty());
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn default_docker_socket_path_platform_shape() {
        let result = ZLayerDirs::default_docker_socket_path();
        assert!(result.starts_with(r"\\.\pipe"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn default_docker_socket_path_platform_shape() {
        let result = ZLayerDirs::default_docker_socket_path();
        assert!(result.ends_with("/docker.sock"));
    }

    #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))]
    #[test]
    fn default_docker_socket_path_platform_shape() {
        let result = ZLayerDirs::default_docker_socket_path();
        assert!(result.ends_with("/docker.sock"));
    }
}