rmux-sdk 0.6.1

Public, daemon-backed Rust SDK for the RMUX terminal multiplexer (facade, ensure-session, snapshots, events, detach helpers).
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
use std::env;
use std::ffi::{OsStr, OsString};
#[cfg(unix)]
use std::path::Path;
use std::path::PathBuf;
#[cfg(unix)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;

use rmux_sdk::bootstrap::discovery::{
    resolve_timeout, SDK_ENDPOINT_ENV, SDK_TIMEOUT_MS_ENV, V1_DEFAULT_TIMEOUT,
};
use rmux_sdk::{RmuxBuilder, RmuxEndpoint};

static ENV_LOCK: Mutex<()> = Mutex::new(());
#[cfg(unix)]
static UNIQUE_ID: AtomicUsize = AtomicUsize::new(0);

#[test]
fn timeout_resolution_uses_per_operation_builder_env_then_default() {
    let _lock = lock_env();
    let _env = EnvGuard::remove(SDK_TIMEOUT_MS_ENV);

    assert_eq!(resolve_timeout(None, None), Some(V1_DEFAULT_TIMEOUT));
    env::set_var(SDK_TIMEOUT_MS_ENV, "1500");
    assert_eq!(
        resolve_timeout(None, None),
        Some(Duration::from_millis(1500))
    );
    assert_eq!(
        RmuxBuilder::new().resolved_timeout(None),
        Some(Duration::from_millis(1500))
    );
    assert_eq!(
        RmuxBuilder::new()
            .default_timeout(Duration::from_millis(2500))
            .resolved_timeout(None),
        Some(Duration::from_millis(2500))
    );
    assert_eq!(
        RmuxBuilder::new()
            .default_timeout(Duration::from_millis(2500))
            .resolved_timeout(Some(Duration::ZERO)),
        Some(Duration::ZERO)
    );
    assert_eq!(
        RmuxBuilder::new()
            .default_timeout(Duration::ZERO)
            .resolved_timeout(None),
        Some(Duration::ZERO)
    );
    assert_eq!(
        RmuxBuilder::new()
            .default_timeout(Duration::from_millis(2500))
            .resolved_timeout(Some(Duration::from_millis(25))),
        Some(Duration::from_millis(25))
    );
}

#[test]
fn duration_max_resolves_to_no_timeout_at_explicit_layers() {
    let _lock = lock_env();
    let _env = EnvGuard::set(SDK_TIMEOUT_MS_ENV, "1500");

    assert_eq!(
        RmuxBuilder::new()
            .default_timeout(Duration::from_millis(2500))
            .resolved_timeout(Some(Duration::MAX)),
        None
    );
    assert_eq!(
        RmuxBuilder::new()
            .default_timeout(Duration::MAX)
            .resolved_timeout(None),
        None
    );
}

#[test]
fn malformed_timeout_environment_falls_back_to_v1_default() {
    let _lock = lock_env();
    let _env = EnvGuard::set(SDK_TIMEOUT_MS_ENV, "not-a-number");

    assert_eq!(resolve_timeout(None, None), Some(V1_DEFAULT_TIMEOUT));
}

#[test]
fn explicit_endpoint_variants_bypass_sdk_environment() {
    let _lock = lock_env();
    let _endpoint = EnvGuard::set(SDK_ENDPOINT_ENV, "definitely-not-a-discovered-endpoint");

    let unix_endpoint = RmuxEndpoint::UnixSocket(PathBuf::from("relative-explicit.sock"));
    assert_eq!(
        RmuxBuilder::new()
            .endpoint(unix_endpoint.clone())
            .resolved_endpoint()
            .expect("resolve explicit Unix endpoint"),
        unix_endpoint
    );

    let windows_endpoint = RmuxEndpoint::WindowsPipe("explicit-pipe".to_owned());
    assert_eq!(
        RmuxBuilder::new()
            .endpoint(windows_endpoint.clone())
            .resolved_endpoint()
            .expect("resolve explicit Windows endpoint"),
        windows_endpoint
    );
}

#[cfg(unix)]
#[test]
fn unix_endpoint_precedence_uses_explicit_then_sdk_env_then_default() {
    let _lock = lock_env();
    let root = TestRoot::new("endpoint-precedence");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);

    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());
    assert!(default_path.starts_with(root.path()));
    assert_eq!(default_path.file_name(), Some(OsStr::new("default")));

    let env_path = default_path
        .parent()
        .expect("owned socket root")
        .join("sdk-env.sock");
    let _listener = bind_unix_socket(&env_path);
    env::set_var(SDK_ENDPOINT_ENV, &env_path);

    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        env_path
    );

    let explicit_path = root.path().join("explicit-outside-owned-root.sock");
    assert_eq!(
        expect_unix_endpoint(
            RmuxBuilder::new()
                .unix_socket(&explicit_path)
                .resolved_endpoint()
        ),
        explicit_path
    );
    assert_eq!(
        expect_unix_endpoint(
            RmuxBuilder::new()
                .unix_socket(root.path().join("discarded-explicit.sock"))
                .default_endpoint()
                .resolved_endpoint()
        ),
        env_path
    );
}

#[cfg(unix)]
#[test]
fn unix_rmux_tmpdir_canonicalization_feeds_default_and_sdk_allowlist() {
    let _lock = lock_env();
    let root = TestRoot::new("tmpdir-canonical");
    let real_tmpdir = root.path().join("real-tmp");
    let linked_tmpdir = root.path().join("linked-tmp");
    std::fs::create_dir_all(&real_tmpdir).expect("create real tmpdir");
    std::os::unix::fs::symlink(&real_tmpdir, &linked_tmpdir).expect("create tmpdir symlink");

    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", linked_tmpdir.as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);

    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());
    let real_tmpdir = std::fs::canonicalize(real_tmpdir).expect("canonical real tmpdir");
    assert!(default_path.starts_with(&real_tmpdir));
    assert!(!default_path.starts_with(&linked_tmpdir));
    assert_eq!(default_path.file_name(), Some(OsStr::new("default")));

    let owned_root = default_path.parent().expect("owned socket root");
    let env_path = owned_root.join("sdk-env.sock");
    let _listener = bind_unix_socket(&env_path);
    env::set_var(SDK_ENDPOINT_ENV, &env_path);

    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        env_path
    );
}

#[cfg(unix)]
#[test]
fn unix_malformed_env_endpoint_falls_back_to_platform_default() {
    let _lock = lock_env();
    let root = TestRoot::new("malformed-env");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);
    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());

    env::set_var(SDK_ENDPOINT_ENV, "relative.sock");

    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        default_path
    );
}

#[cfg(unix)]
#[test]
fn unix_env_endpoint_accepts_missing_target_inside_owned_root() {
    let _lock = lock_env();
    let root = TestRoot::new("missing-env-target");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);
    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());
    let owned_root = default_path.parent().expect("owned socket root");
    std::fs::create_dir_all(owned_root).expect("create owned root");

    let env_path = owned_root.join("not-yet-bound.sock");
    env::set_var(SDK_ENDPOINT_ENV, &env_path);

    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        env_path
    );
}

#[cfg(unix)]
#[test]
fn unix_disallowed_env_endpoint_falls_back_to_platform_default() {
    let _lock = lock_env();
    let root = TestRoot::new("disallowed-env");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);
    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());

    let disallowed = root.path().join("not-rmux-owned").join("sdk.sock");
    let _listener = bind_unix_socket(&disallowed);
    env::set_var(SDK_ENDPOINT_ENV, &disallowed);

    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        default_path
    );
}

#[cfg(unix)]
#[test]
fn unix_env_endpoint_rejects_parent_escape_and_symlinked_parent() {
    let _lock = lock_env();
    let root = TestRoot::new("parent-escape");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);
    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());
    let owned_root = default_path.parent().expect("owned socket root");
    std::fs::create_dir_all(owned_root).expect("create owned root");

    let escaped_socket = root.path().join("escaped").join("sdk.sock");
    let _escaped_listener = bind_unix_socket(&escaped_socket);
    let traversal_path = owned_root.join("..").join("escaped").join("sdk.sock");
    env::set_var(SDK_ENDPOINT_ENV, &traversal_path);
    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        default_path
    );

    let symlink_target = root.path().join("symlink-target");
    std::fs::create_dir_all(&symlink_target).expect("create symlink target");
    let symlinked_parent = owned_root.join("linked-parent");
    std::os::unix::fs::symlink(&symlink_target, &symlinked_parent).expect("create parent symlink");
    let linked_socket = symlink_target.join("sdk.sock");
    let _linked_listener = bind_unix_socket(&linked_socket);

    env::set_var(SDK_ENDPOINT_ENV, symlinked_parent.join("sdk.sock"));
    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        default_path
    );
}

#[cfg(unix)]
#[test]
fn unix_env_endpoint_rejects_symlink_and_regular_file_targets() {
    let _lock = lock_env();
    let root = TestRoot::new("unsafe-targets");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);
    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());
    let owned_root = default_path.parent().expect("owned socket root");
    std::fs::create_dir_all(owned_root).expect("create owned root");

    let regular = owned_root.join("regular-file.sock");
    std::fs::write(&regular, b"not a socket").expect("write regular file");
    env::set_var(SDK_ENDPOINT_ENV, &regular);
    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        default_path
    );

    let real_socket = owned_root.join("real.sock");
    let _listener = bind_unix_socket(&real_socket);
    let symlink = owned_root.join("link.sock");
    std::os::unix::fs::symlink(&real_socket, &symlink).expect("create socket symlink");
    env::set_var(SDK_ENDPOINT_ENV, &symlink);

    assert_eq!(
        expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint()),
        default_path
    );
}

#[cfg(unix)]
#[test]
fn unix_explicit_paths_bypass_auto_discovery_safety_checks() {
    let _lock = lock_env();
    let root = TestRoot::new("explicit-exception");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", root.path().as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);

    let explicit = root.path().join("not-rmux-owned").join("regular.sock");
    std::fs::create_dir_all(explicit.parent().expect("explicit parent"))
        .expect("create explicit parent");
    std::fs::write(&explicit, b"not a socket").expect("write explicit regular file");

    assert_eq!(
        expect_unix_endpoint(
            RmuxBuilder::new()
                .unix_socket(&explicit)
                .resolved_endpoint()
        ),
        explicit
    );
}

#[cfg(unix)]
#[test]
fn unix_unresolved_rmux_tmpdir_still_falls_back_to_tmp() {
    let _lock = lock_env();
    let root = TestRoot::new("tmpdir-fallback");
    let missing = root.path().join("does-not-exist");
    let _tmpdir = EnvGuard::set_os("RMUX_TMPDIR", missing.as_os_str());
    let _endpoint = EnvGuard::remove(SDK_ENDPOINT_ENV);

    let default_path = expect_unix_endpoint(RmuxBuilder::new().resolved_endpoint());
    let tmp = std::fs::canonicalize("/tmp").expect("canonical /tmp");

    assert!(default_path.starts_with(tmp));
    assert_eq!(default_path.file_name(), Some(OsStr::new("default")));
}

#[cfg(windows)]
#[test]
fn windows_endpoint_precedence_uses_explicit_then_sdk_env_then_default() {
    let _lock = lock_env();
    let _endpoint = EnvGuard::set(SDK_ENDPOINT_ENV, r"\\.\pipe\rmux-S-1-5-21-sdk-default");

    assert_eq!(
        expect_windows_endpoint(RmuxBuilder::new().resolved_endpoint()),
        r"\\.\pipe\rmux-S-1-5-21-sdk-default"
    );
    assert_eq!(
        expect_windows_endpoint(
            RmuxBuilder::new()
                .windows_pipe("explicit-pipe")
                .resolved_endpoint()
        ),
        "explicit-pipe"
    );

    env::set_var(SDK_ENDPOINT_ENV, r"\\.\pipe\not-rmux");
    let fallback = expect_windows_endpoint(RmuxBuilder::new().resolved_endpoint());
    assert!(fallback.starts_with(r"\\.\pipe\rmux-"));
}

fn lock_env() -> MutexGuard<'static, ()> {
    ENV_LOCK
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

struct EnvGuard {
    key: &'static str,
    previous: Option<OsString>,
}

impl EnvGuard {
    fn set(key: &'static str, value: &str) -> Self {
        Self::set_os(key, OsStr::new(value))
    }

    fn set_os(key: &'static str, value: &OsStr) -> Self {
        let previous = env::var_os(key);
        env::set_var(key, value);
        Self { key, previous }
    }

    fn remove(key: &'static str) -> Self {
        let previous = env::var_os(key);
        env::remove_var(key);
        Self { key, previous }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        match &self.previous {
            Some(value) => env::set_var(self.key, value),
            None => env::remove_var(self.key),
        }
    }
}

#[cfg(unix)]
struct TestRoot {
    path: PathBuf,
}

#[cfg(unix)]
impl TestRoot {
    fn new(label: &str) -> Self {
        let unique = UNIQUE_ID.fetch_add(1, Ordering::Relaxed);
        // Keep Unix socket fixtures below macOS' short sockaddr_un budget.
        let path = PathBuf::from("/tmp").join(format!(
            "rmux-sd-{}-{}-{unique}",
            compact_label(label),
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).expect("create test root");
        let path = std::fs::canonicalize(path).expect("canonical test root");

        Self { path }
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

#[cfg(unix)]
impl Drop for TestRoot {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

#[cfg(unix)]
fn expect_unix_endpoint(endpoint: rmux_sdk::Result<RmuxEndpoint>) -> PathBuf {
    match endpoint.expect("resolve endpoint") {
        RmuxEndpoint::UnixSocket(path) => path,
        endpoint => panic!("expected Unix socket endpoint, got {endpoint:?}"),
    }
}

#[cfg(unix)]
fn compact_label(label: &str) -> String {
    let compact = label
        .chars()
        .filter(|character| character.is_ascii_alphanumeric())
        .take(12)
        .collect::<String>();
    if compact.is_empty() {
        "x".to_owned()
    } else {
        compact
    }
}

#[cfg(unix)]
fn bind_unix_socket(path: &Path) -> std::os::unix::net::UnixListener {
    let parent = path.parent().expect("socket parent");
    std::fs::create_dir_all(parent).expect("create socket parent");
    let _ = std::fs::remove_file(path);
    std::os::unix::net::UnixListener::bind(path).expect("bind Unix socket")
}

#[cfg(windows)]
fn expect_windows_endpoint(endpoint: rmux_sdk::Result<RmuxEndpoint>) -> String {
    match endpoint.expect("resolve endpoint") {
        RmuxEndpoint::WindowsPipe(pipe) => pipe,
        endpoint => panic!("expected Windows pipe endpoint, got {endpoint:?}"),
    }
}