running-process 4.5.5

Subprocess and PTY runtime for the running-process project
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
//! Canonical v1 broker pipe-name derivation.
//!
//! Phase 1 of #228 (issue #230). Every name is derived from the
//! caller's [`user_sid_hash`](super::sid::user_sid_hash) plus a few
//! frozen string templates. The Windows form is a named pipe
//! (`\\.\pipe\...`); the Unix form is a filesystem socket path under
//! the broker shadow directory.
//!
//! The four canonical names exposed here are:
//!
//! | Function                  | Purpose                                                             |
//! |---------------------------|---------------------------------------------------------------------|
//! | [`shared_broker_pipe`]    | Single per-user broker that serves every service together.          |
//! | [`private_broker_pipe`]   | Service-isolated broker (e.g. one zccache instance only).           |
//! | [`explicit_instance_pipe`]| Hand-named broker for tests/dev/multi-instance scenarios.           |
//! | [`backend_pipe`]          | The per-backend handle the broker hands a client after negotiation. |
//!
//! ## Validation
//!
//! Service names must match `[a-z0-9-]{1,64}`. Version strings must
//! match a semver-like `^[0-9]+\.[0-9]+\.[0-9]+(-[a-z0-9.]+)?$`.
//! Explicit instance names match `[a-z0-9-]{1,64}`. Case-only
//! collisions (`Zccache` vs `zccache`) are rejected with
//! [`PipePathError::InvalidName`] because Windows named pipes are
//! case-insensitive and silently coalescing would let a malicious
//! caller hijack a legitimate broker.
//!
//! ## Length limits
//!
//! - Windows `\\.\pipe\` names without the `\\?\` long-path prefix
//!   are capped by `MAX_PATH = 260` characters.
//! - macOS `sun_path` (the path field of `struct sockaddr_un`) is 104
//!   bytes. The Unix path returned here is validated to stay under
//!   that bound after combining `shadow_dir() + "/broker/" + name +
//!   ".sock"`.

use std::path::PathBuf;

#[cfg(unix)]
use crate::broker::lifecycle::sid::hash_to_16_hex;
use crate::broker::lifecycle::sid::SidError;

/// Errors that prevent computing a valid pipe path.
#[derive(Debug, thiserror::Error)]
pub enum PipePathError {
    /// A name argument failed regex validation.
    #[error("invalid name {name:?}: {reason}")]
    InvalidName {
        /// The offending input.
        name: String,
        /// Why it was rejected.
        reason: &'static str,
    },

    /// The derived path exceeds a platform-specific bound.
    #[error("derived path exceeds {limit_label} ({len} > {max})")]
    PathTooLong {
        /// Length we tried to produce.
        len: usize,
        /// Platform-specific cap.
        max: usize,
        /// "Windows MAX_PATH" / "macOS sun_path" / etc.
        limit_label: &'static str,
    },

    /// Failure to compute the per-user SID hash.
    #[error(transparent)]
    Sid(#[from] SidError),
}

/// A pipe address in platform-neutral form.
///
/// Exactly one of [`Self::windows`] or [`Self::unix`] is populated on
/// any given host. The other field is `None`. Callers select the
/// active platform's value via `cfg(windows)` / `cfg(unix)` blocks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PipePath {
    /// Windows named-pipe path (e.g. `\\.\pipe\rpb-v1-abc-shared`).
    pub windows: Option<String>,
    /// Unix domain socket path (e.g.
    /// `/run/user/1000/running-process/broker/rpb-v1-abc-shared.sock`).
    pub unix: Option<PathBuf>,
}

/// Windows MAX_PATH ceiling without the `\\?\` long-path prefix.
pub const WINDOWS_MAX_PATH: usize = 260;

/// macOS `sun_path` field ceiling. POSIX requires at least 92;
/// Darwin's `struct sockaddr_un` actually has 104.
pub const MACOS_SUN_PATH_MAX: usize = 104;

/// Linux `sun_path` field ceiling. glibc defines it as 108.
pub const LINUX_SUN_PATH_MAX: usize = 108;

/// Compile-time prefix every broker pipe shares. Encodes the v1
/// envelope version and the "running-process broker" namespace so
/// pipe names cannot accidentally collide with anything else under
/// `\\.\pipe\` or `shadow_dir()/broker/`.
const PIPE_PREFIX: &str = "rpb-v1";

/// Compute the shared-broker pipe address.
///
/// The shared broker is the default: one instance per user that fans
/// every service request out to the right backend.
pub fn shared_broker_pipe(user_sid_hash: &str) -> Result<PipePath, PipePathError> {
    validate_sid_hash(user_sid_hash)?;
    build_pipe_path(&format!("{PIPE_PREFIX}-{user_sid_hash}-shared"))
}

/// Compute the private-broker pipe address for a single service.
///
/// Service names must match `[a-z0-9-]{1,64}`.
pub fn private_broker_pipe(user_sid_hash: &str, service: &str) -> Result<PipePath, PipePathError> {
    validate_sid_hash(user_sid_hash)?;
    validate_service_name(service)?;
    build_pipe_path(&format!("{PIPE_PREFIX}-{user_sid_hash}-svc-{service}"))
}

/// Compute the explicit-instance broker pipe address.
///
/// `name` must match `[a-z0-9-]{1,64}` and is otherwise unrestricted.
/// Used for tests and multi-instance dev setups.
pub fn explicit_instance_pipe(user_sid_hash: &str, name: &str) -> Result<PipePath, PipePathError> {
    validate_sid_hash(user_sid_hash)?;
    validate_service_name(name)?; // same `[a-z0-9-]{1,64}` rule
    build_pipe_path(&format!("{PIPE_PREFIX}-{user_sid_hash}-inst-{name}"))
}

/// Compute the backend pipe address the broker hands a client after
/// Hello negotiation.
///
/// `random128` is a 16-byte (128-bit) random suffix the broker
/// generates per connection. Rendered as lowercase hex to keep the
/// pipe name in the `[a-z0-9-]` charset.
pub fn backend_pipe(user_sid_hash: &str, random128: &[u8; 16]) -> Result<PipePath, PipePathError> {
    validate_sid_hash(user_sid_hash)?;
    let mut suffix = String::with_capacity(32);
    for b in random128 {
        suffix.push(nibble_to_hex(b >> 4));
        suffix.push(nibble_to_hex(b & 0x0F));
    }
    build_pipe_path(&format!("{PIPE_PREFIX}-{user_sid_hash}-be-{suffix}"))
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

/// Validate a service name against `[a-z0-9-]{1,64}`.
///
/// Exposed for callers that want to validate user input before
/// computing the pipe name (so they can surface a friendlier error).
pub fn validate_service_name(name: &str) -> Result<(), PipePathError> {
    if name.is_empty() {
        return Err(PipePathError::InvalidName {
            name: name.into(),
            reason: "service name must be at least 1 character",
        });
    }
    if name.len() > 64 {
        return Err(PipePathError::InvalidName {
            name: name.into(),
            reason: "service name must be 64 characters or fewer",
        });
    }
    for c in name.chars() {
        match c {
            'a'..='z' | '0'..='9' | '-' => {}
            'A'..='Z' => {
                // Case-only collision guard — see module docs.
                return Err(PipePathError::InvalidName {
                    name: name.into(),
                    reason: "uppercase letters are forbidden (case-only \
                             collisions with lowercase names would silently \
                             merge under Windows named-pipe semantics)",
                });
            }
            _ => {
                return Err(PipePathError::InvalidName {
                    name: name.into(),
                    reason: "only lowercase ASCII letters, digits, and '-' allowed",
                });
            }
        }
    }
    Ok(())
}

/// Validate a semver-like version string against
/// `^[0-9]+\.[0-9]+\.[0-9]+(-[a-z0-9.]+)?$`.
///
/// Used by callers that want to render `{service}-{version}` into a
/// pipe name themselves (the helpers here keep the name format flat,
/// but the validator is exposed for the broker-side dispatch table).
pub fn validate_version(version: &str) -> Result<(), PipePathError> {
    if version.is_empty() {
        return Err(PipePathError::InvalidName {
            name: version.into(),
            reason: "version must not be empty",
        });
    }
    // Split off pre-release tail.
    let (core, prerelease) = match version.split_once('-') {
        Some((core, tail)) => (core, Some(tail)),
        None => (version, None),
    };
    let parts: Vec<&str> = core.split('.').collect();
    if parts.len() != 3 {
        return Err(PipePathError::InvalidName {
            name: version.into(),
            reason: "version core must be MAJOR.MINOR.PATCH",
        });
    }
    for p in &parts {
        if p.is_empty() || !p.chars().all(|c| c.is_ascii_digit()) {
            return Err(PipePathError::InvalidName {
                name: version.into(),
                reason: "MAJOR/MINOR/PATCH must be non-empty digits",
            });
        }
    }
    if let Some(tail) = prerelease {
        if tail.is_empty() {
            return Err(PipePathError::InvalidName {
                name: version.into(),
                reason: "pre-release suffix after '-' must not be empty",
            });
        }
        for c in tail.chars() {
            match c {
                'a'..='z' | '0'..='9' | '.' => {}
                _ => {
                    return Err(PipePathError::InvalidName {
                        name: version.into(),
                        reason: "pre-release tail allows only [a-z0-9.]",
                    });
                }
            }
        }
    }
    Ok(())
}

fn validate_sid_hash(s: &str) -> Result<(), PipePathError> {
    if s.len() != 16 {
        return Err(PipePathError::InvalidName {
            name: s.into(),
            reason: "user_sid_hash must be exactly 16 hex characters",
        });
    }
    for c in s.chars() {
        if !(c.is_ascii_digit() || ('a'..='f').contains(&c)) {
            return Err(PipePathError::InvalidName {
                name: s.into(),
                reason: "user_sid_hash must be lowercase hex",
            });
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Path assembly
// ---------------------------------------------------------------------------

#[inline]
fn nibble_to_hex(n: u8) -> char {
    match n {
        0..=9 => (b'0' + n) as char,
        10..=15 => (b'a' + (n - 10)) as char,
        _ => unreachable!("nibble out of range"),
    }
}

fn build_pipe_path(name: &str) -> Result<PipePath, PipePathError> {
    #[cfg(windows)]
    {
        let path = format!(r"\\.\pipe\{name}");
        if path.len() > WINDOWS_MAX_PATH {
            return Err(PipePathError::PathTooLong {
                len: path.len(),
                max: WINDOWS_MAX_PATH,
                limit_label: "Windows MAX_PATH",
            });
        }
        Ok(PipePath {
            windows: Some(path),
            unix: None,
        })
    }

    #[cfg(unix)]
    {
        let dir = unix_broker_socket_dir();
        // macOS sun_path is only 104 bytes. Per the #228 spec, every
        // macOS pipe name folds to `{16char-hash}.sock` — there is no
        // budget to embed the full canonical name. Linux gets 108 bytes
        // AND a guaranteed $XDG_RUNTIME_DIR (or short /tmp fallback),
        // so we keep the full name there for debuggability.
        let leaf = if cfg!(target_os = "macos") {
            format!("{}.sock", hash_to_16_hex(name.as_bytes()))
        } else {
            format!("{name}.sock")
        };
        let candidate = dir.join(leaf);
        let candidate_str = candidate.to_string_lossy();
        let limit = if cfg!(target_os = "macos") {
            MACOS_SUN_PATH_MAX
        } else {
            LINUX_SUN_PATH_MAX
        };
        let limit_label = if cfg!(target_os = "macos") {
            "macOS sun_path"
        } else {
            "Linux sun_path"
        };
        // sockaddr_un is NUL-terminated, so the path string itself
        // must be strictly less than the field width.
        if candidate_str.len() >= limit {
            return Err(PipePathError::PathTooLong {
                len: candidate_str.len(),
                max: limit - 1,
                limit_label,
            });
        }
        Ok(PipePath {
            windows: None,
            unix: Some(candidate),
        })
    }
}

#[cfg(unix)]
fn unix_broker_socket_dir() -> PathBuf {
    // We deliberately do NOT call `client::paths::shadow_dir()` here
    // because that function has filesystem side effects
    // (`create_dir_all`). The names module must be pure / no-IO so the
    // hash + length-limit tests stay deterministic. Callers that need
    // to actually bind the socket are expected to create the parent
    // directory themselves.
    #[cfg(target_os = "macos")]
    {
        // Per the #228 spec: macOS has no $XDG_RUNTIME_DIR and a tight
        // 104-byte sun_path. Use `$TMPDIR/.rp-{uid}` so the parent dir
        // stays short enough to leave room for the hashed leaf.
        // `$TMPDIR` on macOS is per-user (e.g. `/var/folders/.../T/`)
        // so the `-{uid}` suffix is technically redundant there, but
        // we keep it so the path is well-formed when `$TMPDIR` is
        // unset (CI containers, restricted launchd contexts) and we
        // fall back to `/tmp`.
        let uid = unsafe { libc::getuid() };
        let tmp = std::env::var_os("TMPDIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("/tmp"));
        tmp.join(format!(".rp-{uid}"))
    }
    #[cfg(not(target_os = "macos"))]
    {
        if let Some(d) = std::env::var_os("XDG_RUNTIME_DIR") {
            PathBuf::from(d).join("running-process").join("broker")
        } else {
            // Fallback: /tmp/running-process-{uid}/broker
            let uid = unsafe { libc::getuid() };
            PathBuf::from(format!("/tmp/running-process-{uid}/broker"))
        }
    }
}

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

    const SAMPLE_HASH: &str = "0123456789abcdef";

    #[test]
    fn shared_broker_pipe_builds() {
        let p = shared_broker_pipe(SAMPLE_HASH).expect("shared pipe should build");
        #[cfg(windows)]
        {
            let w = p.windows.expect("windows form populated on Windows");
            assert!(w.starts_with(r"\\.\pipe\rpb-v1-"));
            assert!(w.ends_with("-shared"));
        }
        #[cfg(all(unix, not(target_os = "macos")))]
        {
            let u = p.unix.expect("unix form populated on Unix");
            let s = u.to_string_lossy();
            assert!(s.contains("rpb-v1-"));
            assert!(s.ends_with("-shared.sock"));
        }
        #[cfg(target_os = "macos")]
        {
            // macOS folds the canonical name into a 16-char hash —
            // the `rpb-v1-...-shared` segment is the *input* to the
            // hash but doesn't survive into the path.
            let u = p.unix.expect("unix form populated on macOS");
            let s = u.to_string_lossy();
            assert!(s.ends_with(".sock"));
        }
    }

    #[test]
    fn private_broker_pipe_rejects_uppercase() {
        let err = private_broker_pipe(SAMPLE_HASH, "Zccache").unwrap_err();
        match err {
            PipePathError::InvalidName { .. } => {}
            _ => panic!("expected InvalidName, got {err:?}"),
        }
    }

    #[test]
    fn validate_version_accepts_semver() {
        validate_version("1.0.0").unwrap();
        validate_version("1.11.20").unwrap();
        validate_version("0.0.1-alpha.1").unwrap();
        validate_version("2.3.4-rc.1.beta").unwrap();
    }

    #[test]
    fn validate_version_rejects_invalid() {
        assert!(validate_version("").is_err());
        assert!(validate_version("1.0").is_err());
        assert!(validate_version("1.0.0.0").is_err());
        assert!(validate_version("1.0.0-").is_err());
        assert!(validate_version("1.0.0-ALPHA").is_err()); // uppercase
        assert!(validate_version("v1.0.0").is_err());
    }

    #[test]
    fn backend_pipe_uses_hex_suffix() {
        let p = backend_pipe(SAMPLE_HASH, &[0xABu8; 16]).expect("backend pipe");
        let s = match (p.windows, p.unix) {
            (Some(w), None) => w,
            (None, Some(u)) => u.to_string_lossy().into_owned(),
            _ => panic!("exactly one form must be populated"),
        };
        // macOS folds the canonical name into a 16-char hash to fit
        // `sun_path` (104 bytes), so the literal `-be-` segment and
        // raw hex suffix don't appear on that platform — we still
        // assert the leaf shape and uniqueness in the integration
        // test `macos_pipe_paths_are_hashed_leaves`.
        #[cfg(not(target_os = "macos"))]
        {
            assert!(s.contains("-be-"));
            assert!(s.contains(&"ab".repeat(16)));
        }
        #[cfg(target_os = "macos")]
        {
            assert!(s.ends_with(".sock"));
        }
    }
}