micromux-control 0.2.0

Micromux is a local process supervisor with a terminal UI
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
//! Deterministic endpoint naming and runtime-dir resolution.
//!
//! The endpoint name is a fixed-length digest of the *canonical config path*, so the session and
//! the proxy derive the identical name from the same input and the common one-session-per-project
//! case needs no enumeration.

use std::borrow::Cow;
use std::fmt;
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

/// A control endpoint, keyed by filesystem path / pipe name. The supported transports are a closed
/// set: no network transport, ever.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ControlEndpoint {
    /// A Unix domain socket (Unix/macOS).
    Unix(PathBuf),
    /// A Windows named pipe (M1-Windows; currently unsupported).
    WindowsNamedPipe(String),
}

impl fmt::Display for ControlEndpoint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unix(path) => write!(f, "{}", path.display()),
            Self::WindowsNamedPipe(name) => f.write_str(name),
        }
    }
}

/// Preparation status for one plausible runtime directory.
#[derive(Debug, Clone)]
pub struct RuntimeDirStatus {
    /// Runtime directory path.
    pub path: PathBuf,
    /// Whether the directory was usable.
    pub usable: bool,
    /// Preparation error for unusable directories.
    pub error: Option<String>,
}

/// Extract the usable paths from runtime-dir preparation results.
#[must_use]
pub fn usable_runtime_dirs(statuses: &[RuntimeDirStatus]) -> Vec<PathBuf> {
    statuses
        .iter()
        .filter(|status| status.usable)
        .map(|status| status.path.clone())
        .collect()
}

/// Whether this build has a concrete control transport implementation.
#[cfg(unix)]
#[must_use]
pub const fn transport_supported() -> bool {
    true
}

/// Whether this build has a concrete control transport implementation.
#[cfg(not(unix))]
#[must_use]
pub const fn transport_supported() -> bool {
    false
}

/// A session config path in canonical form, the only input endpoint names are derived from.
///
/// The session binding an endpoint and every client re-deriving it must hash the exact same
/// bytes, or the two sides silently compute different socket names for the same project. A path
/// that reaches the config through a symlink diverges from its canonical form — macOS does this
/// for entire standard trees (`/tmp` and `/var` live under `/private`) — so raw user-supplied
/// paths are never acceptable input. Holding this type is proof the divergence was resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanonicalConfigPath(PathBuf);

impl CanonicalConfigPath {
    /// Canonicalize `path` (which must exist) and wrap it.
    ///
    /// # Errors
    ///
    /// Returns the underlying I/O error when `path` does not exist or cannot be canonicalized.
    pub fn new(path: impl AsRef<Path>) -> std::io::Result<Self> {
        Ok(Self(std::fs::canonicalize(path)?))
    }

    /// Wrap a path that is already canonical (e.g. `tokio::fs::canonicalize` output).
    ///
    /// Crate-private on purpose: external callers must prove canonicalization through
    /// [`Self::new`], while in-crate async resolvers may trust their own canonicalize calls.
    pub(crate) fn from_canonicalized(path: PathBuf) -> Self {
        Self(path)
    }

    /// The canonical path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

impl std::ops::Deref for CanonicalConfigPath {
    type Target = Path;

    fn deref(&self) -> &Path {
        &self.0
    }
}

impl AsRef<Path> for CanonicalConfigPath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

/// The deterministic short digest of a canonical config path. Fixed length keeps the macOS
/// `sun_path` budget under control.
#[must_use]
pub fn endpoint_hash(config_path: &CanonicalConfigPath) -> String {
    hash_path(config_path.as_path())
}

/// Raw digest of an arbitrary path's bytes. Crate-private: the typed [`endpoint_hash`] is the
/// public entrypoint, so endpoint names are only ever derived from canonical config paths.
pub(crate) fn hash_path(path: &Path) -> String {
    let input = endpoint_hash_input(path);
    let digest = Sha256::digest(input.as_ref());
    let mut out = String::with_capacity(16);
    for byte in digest.iter().take(8) {
        use std::fmt::Write as _;
        let _ = write!(out, "{byte:02x}");
    }
    out
}

#[cfg(unix)]
fn endpoint_hash_input(config_path: &Path) -> Cow<'_, [u8]> {
    use std::os::unix::ffi::OsStrExt;

    Cow::Borrowed(config_path.as_os_str().as_bytes())
}

#[cfg(not(unix))]
fn endpoint_hash_input(config_path: &Path) -> Cow<'_, [u8]> {
    Cow::Owned(config_path.to_string_lossy().into_owned().into_bytes())
}

/// Resolve the per-user runtime directory for micromux endpoints, creating it with restrictive
/// permissions. Returns `None` when no directory can be resolved (control plane disabled).
#[must_use]
pub fn runtime_dir() -> Option<PathBuf> {
    for path in runtime_dir_candidates() {
        match ensure_private_dir(&path) {
            Ok(()) => return Some(path),
            Err(err) => {
                tracing::warn!(?err, dir = %path.display(), "failed to prepare runtime dir");
            }
        }
    }
    None
}

/// Report every plausible runtime directory and whether it is currently usable.
#[must_use]
pub fn runtime_dir_statuses() -> Vec<RuntimeDirStatus> {
    runtime_dir_candidates()
        .into_iter()
        .map(|path| match ensure_private_dir(&path) {
            Ok(()) => RuntimeDirStatus {
                path,
                usable: true,
                error: None,
            },
            Err(err) => RuntimeDirStatus {
                path,
                usable: false,
                error: Some(err.to_string()),
            },
        })
        .collect()
}

fn runtime_dir_candidates() -> Vec<PathBuf> {
    let mut candidates = Vec::new();

    if let Some(directory) = micromux::project_dir()
        .and_then(|directories| directories.runtime_dir().map(Path::to_path_buf))
    {
        push_unique(&mut candidates, directory);
    }

    #[cfg(unix)]
    if let Some(directory) = xdg_runtime_directory() {
        push_unique(&mut candidates, directory);
    }

    #[cfg(all(unix, target_os = "linux"))]
    if let Some(directory) =
        systemd_runtime_directory(Path::new("/run/user"), nix::unistd::Uid::current())
    {
        push_unique(&mut candidates, directory);
    }

    push_unique(&mut candidates, per_user_fallback_dir());
    candidates
}

fn push_unique(candidates: &mut Vec<PathBuf>, candidate: PathBuf) {
    if !candidates.iter().any(|existing| existing == &candidate) {
        candidates.push(candidate);
    }
}

#[cfg(unix)]
fn per_user_fallback_dir() -> PathBuf {
    let uid = nix::unistd::Uid::current();
    std::env::temp_dir().join(format!("micromux-{uid}"))
}

#[cfg(unix)]
pub(crate) fn project_lock_path(config_path: &CanonicalConfigPath) -> std::io::Result<PathBuf> {
    let uid = nix::unistd::Uid::current();
    let directory = Path::new("/tmp").join(format!("micromux-{uid}"));
    ensure_private_dir(&directory)?;
    Ok(directory.join(format!("{}.session.lock", endpoint_hash(config_path))))
}

#[cfg(not(unix))]
fn per_user_fallback_dir() -> PathBuf {
    std::env::temp_dir().join("micromux")
}

#[cfg(unix)]
fn xdg_runtime_directory() -> Option<PathBuf> {
    std::env::var_os("XDG_RUNTIME_DIR").and_then(|directory| {
        if directory.is_empty() {
            None
        } else {
            Some(PathBuf::from(directory).join("micromux"))
        }
    })
}

#[cfg(all(unix, target_os = "linux"))]
fn systemd_runtime_directory(base: &Path, user_identifier: nix::unistd::Uid) -> Option<PathBuf> {
    let user_runtime_directory = base.join(user_identifier.as_raw().to_string());
    user_runtime_directory
        .is_dir()
        .then(|| user_runtime_directory.join("micromux"))
}

#[cfg(unix)]
fn ensure_private_dir(dir: &Path) -> std::io::Result<()> {
    use nix::fcntl::{OFlag, open};
    use nix::sys::stat::{Mode, SFlag, fchmod, fstat};
    use std::os::unix::fs::DirBuilderExt;

    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(dir)?;

    let fd = open(
        dir,
        OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,
        Mode::empty(),
    )
    .map_err(nix_to_io)?;
    let metadata = fstat(&fd).map_err(nix_to_io)?;
    if !SFlag::from_bits_truncate(metadata.st_mode).contains(SFlag::S_IFDIR) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotADirectory,
            "runtime dir path is not a directory",
        ));
    }
    if metadata.st_uid != nix::unistd::Uid::current().as_raw() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "runtime dir is not owned by the current user",
        ));
    }

    // `recursive` does not re-apply the mode to a pre-existing dir; the directory mode is what gates
    // `connect`, so set it defensively.
    if metadata.st_mode & 0o777 != 0o700 {
        fchmod(&fd, Mode::from_bits_truncate(0o700)).map_err(nix_to_io)?;
    }
    Ok(())
}

#[cfg(unix)]
fn nix_to_io(err: nix::errno::Errno) -> std::io::Error {
    std::io::Error::from_raw_os_error(err as i32)
}

#[cfg(not(unix))]
fn ensure_private_dir(dir: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(dir)
}

/// Build a control endpoint from a known endpoint hash within `runtime_dir`.
#[must_use]
pub fn endpoint_from_hash(runtime_dir: &Path, hash: &str) -> ControlEndpoint {
    #[cfg(unix)]
    {
        ControlEndpoint::Unix(runtime_dir.join(format!("{hash}.sock")))
    }
    #[cfg(not(unix))]
    {
        let _ = runtime_dir;
        ControlEndpoint::WindowsNamedPipe(format!(r"\\.\pipe\micromux-{hash}"))
    }
}

/// Compute the control endpoint for a session's canonical config path within `runtime_dir`.
#[must_use]
pub fn endpoint_for(runtime_dir: &Path, config_path: &CanonicalConfigPath) -> ControlEndpoint {
    endpoint_from_hash(runtime_dir, &endpoint_hash(config_path))
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use color_eyre::eyre;
    use similar_asserts::assert_eq;
    #[cfg(all(unix, target_os = "linux"))]
    use std::io;

    #[test]
    fn endpoint_hash_is_deterministic_and_fixed_length() {
        let a = hash_path(Path::new("/home/user/project/micromux.yaml"));
        let b = hash_path(Path::new("/home/user/project/micromux.yaml"));
        let c = hash_path(Path::new("/home/user/other/micromux.yaml"));
        assert_eq!(a, b);
        assert_eq!(a, "3f98f83e6e2c8d23");
        assert_eq!(a.len(), 16);
        assert_ne!(a, c);
    }

    /// The invariant [`CanonicalConfigPath`] exists to enforce: a config reached through a
    /// symlink and through its real path must derive the identical endpoint.
    #[cfg(unix)]
    #[test]
    fn symlinked_and_real_config_paths_derive_the_same_endpoint() -> eyre::Result<()> {
        let root = tempfile::tempdir()?;
        let project = root.path().join("project");
        std::fs::create_dir(&project)?;
        let config = project.join("micromux.yaml");
        std::fs::write(&config, "version: 1\nservices: {}\n")?;
        let alias = root.path().join("alias");
        std::os::unix::fs::symlink(&project, &alias)?;

        let through_real = CanonicalConfigPath::new(&config)?;
        let through_alias = CanonicalConfigPath::new(alias.join("micromux.yaml"))?;

        assert_eq!(through_real, through_alias);
        assert_eq!(
            endpoint_for(root.path(), &through_real),
            endpoint_for(root.path(), &through_alias)
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn per_user_fallback_socket_path_fits_the_darwin_sun_path_budget() -> eyre::Result<()> {
        use std::os::unix::ffi::OsStrExt;

        // macOS has the tightest `sockaddr_un` budget of the supported platforms: `sun_path` is
        // 104 bytes including the NUL terminator. The whole endpoint design (fixed 16-hex hash,
        // short per-user runtime dirs) exists to stay under it, so a regression here — a longer
        // hash, a longer dir name — must fail on every platform, not only once macOS CI runs.
        const DARWIN_SUN_PATH_LEN: usize = 104;
        // The observed shape of a real macOS per-user temp dir (`$TMPDIR`), the longest runtime
        // dir base among the supported platforms.
        let representative_macos_tmp =
            Path::new("/var/folders/8j/sfr9qqcj73j4p6nhwcfpr0th0000gn/T");

        // Worst-case the variable part of the production fallback dir name: the largest uid.
        let uid = nix::unistd::Uid::current().to_string();
        let fallback_name = per_user_fallback_dir()
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .ok_or_else(|| eyre::eyre!("fallback runtime dir has no final component"))?;
        assert!(
            fallback_name.contains(&uid),
            "fallback dir name {fallback_name:?} no longer embeds the uid; update this test"
        );
        let worst_case_name = fallback_name.replace(&uid, &u32::MAX.to_string());

        let worst_case_dir = representative_macos_tmp.join(worst_case_name);
        let hash = hash_path(Path::new("/any/project/micromux.yaml"));
        let ControlEndpoint::Unix(socket_path) = endpoint_from_hash(&worst_case_dir, &hash) else {
            eyre::bail!("a unix build must derive unix socket endpoints");
        };

        let len = socket_path.as_os_str().as_bytes().len();
        assert!(
            len < DARWIN_SUN_PATH_LEN,
            "worst-case fallback socket path is {len} bytes, over the {DARWIN_SUN_PATH_LEN}-byte \
             macOS sun_path budget: {}",
            socket_path.display()
        );
        Ok(())
    }

    #[cfg(not(unix))]
    #[test]
    fn non_unix_endpoints_are_named_pipes_and_transport_is_unsupported() {
        let hash = hash_path(Path::new("C:/project/micromux.yaml"));
        let endpoint = endpoint_from_hash(Path::new("ignored"), &hash);

        assert_eq!(
            endpoint,
            ControlEndpoint::WindowsNamedPipe(format!(r"\\.\pipe\micromux-{hash}"))
        );
        assert!(!transport_supported());
    }

    #[cfg(unix)]
    #[test]
    fn endpoint_hash_uses_raw_unix_path_bytes() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let first = PathBuf::from(OsString::from_vec(b"/tmp/micromux-\xff.yaml".to_vec()));
        let second = PathBuf::from(OsString::from_vec(b"/tmp/micromux-\xfe.yaml".to_vec()));

        assert_ne!(hash_path(&first), hash_path(&second));
    }

    #[cfg(unix)]
    #[test]
    fn ensure_private_dir_rejects_symlink_leaf() -> std::io::Result<()> {
        use std::os::unix::fs::PermissionsExt;

        let root = tempfile::Builder::new()
            .prefix("micromux-control-symlink-test-")
            .tempdir()?;

        let target = root.path().join("target");
        std::fs::create_dir_all(&target)?;
        std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755))?;
        let link = root.path().join("link");
        std::os::unix::fs::symlink(&target, &link)?;

        let err = ensure_private_dir(&link).expect_err("symlink leaf must be rejected");
        assert!(is_symlink_leaf_error(&err));
        assert_eq!(
            std::fs::metadata(&target)?.permissions().mode() & 0o777,
            0o755,
            "the symlink target must not be chmodded"
        );
        Ok(())
    }

    #[cfg(all(unix, target_os = "linux"))]
    #[test]
    fn inferred_systemd_runtime_directory_matches_project_runtime_shape() -> io::Result<()> {
        let root = tempfile::Builder::new()
            .prefix("micromux-control-endpoint-test-")
            .tempdir()?;

        let user_identifier = nix::unistd::Uid::from_raw(4242);
        assert_eq!(
            systemd_runtime_directory(root.path(), user_identifier),
            None
        );

        let user_runtime_directory = root.path().join("4242");
        std::fs::create_dir_all(&user_runtime_directory)?;
        assert_eq!(
            systemd_runtime_directory(root.path(), user_identifier),
            Some(user_runtime_directory.join("micromux"))
        );

        Ok(())
    }

    #[cfg(unix)]
    fn is_symlink_leaf_error(err: &std::io::Error) -> bool {
        matches!(
            err.kind(),
            std::io::ErrorKind::AlreadyExists | std::io::ErrorKind::NotADirectory
        ) || err.raw_os_error() == Some(nix::errno::Errno::ELOOP as i32)
    }
}