running-process 4.10.16

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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use super::*;

/// A serialised guard: these tests mutate the real process environment, and
/// two of them setting the same variable at once would read each other's value.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn with_var<T>(name: &str, value: Option<&str>, body: impl FnOnce() -> T) -> T {
    let _guard = ENV_LOCK
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    let previous = std::env::var_os(name);
    match value {
        Some(value) => std::env::set_var(name, value),
        None => std::env::remove_var(name),
    }
    let outcome = body();
    match previous {
        Some(previous) => std::env::set_var(name, previous),
        None => std::env::remove_var(name),
    }
    outcome
}

const PROBE: &str = "RUNNING_PROCESS_ENV_VARS_PROBE";

/// An owned switch is on only for a spelling we recognise. This is the
/// direction that matters: a typo in a switch we define must not enable it.
#[test]
fn an_owned_flag_is_on_only_for_a_recognised_affirmative() {
    for on in ["1", "true", "TRUE", " True ", "yes", "on"] {
        assert!(
            with_var(PROBE, Some(on), || flag_owned(PROBE)),
            "{on:?} must turn an owned switch on"
        );
    }
    for off in ["", "0", "false", "no", "off", "OFF", " 0 "] {
        assert!(
            !with_var(PROBE, Some(off), || flag_owned(PROBE)),
            "{off:?} must leave an owned switch off"
        );
    }
    for unknown in ["maybe", "2", "y", "enabled", "tru"] {
        assert!(
            !with_var(PROBE, Some(unknown), || flag_owned(PROBE)),
            "{unknown:?} is not a spelling we defined, so the switch stays off"
        );
    }
    assert!(!with_var(PROBE, None, || flag_owned(PROBE)), "unset is off");
}

/// A foreign switch is off only for a spelling we recognise as falsy. The
/// unknown case flips, because we do not own what the writer may have meant.
#[test]
fn a_foreign_flag_is_off_only_for_a_recognised_negative() {
    for off in ["", "0", "false", "no", "off", " OFF "] {
        assert!(
            !with_var(PROBE, Some(off), || flag_foreign(PROBE)),
            "{off:?} must turn a foreign switch off"
        );
    }
    for on in ["1", "true", "yes", "on", "maybe", "2", "enabled"] {
        assert!(
            with_var(PROBE, Some(on), || flag_foreign(PROBE)),
            "{on:?} is not a falsy spelling, so the switch reads as on"
        );
    }
}

/// Absence is not a value. Reading unset as "on" would make every process
/// claim every marker it does not carry.
#[test]
fn an_unset_foreign_flag_is_off() {
    assert!(!with_var(PROBE, None, || flag_foreign(PROBE)));
}

/// The two semantics disagree exactly where they are meant to, and nowhere
/// else. If this ever passes trivially the distinction has collapsed.
#[test]
fn the_two_flag_semantics_differ_only_on_unrecognised_values() {
    for agreed in ["1", "true", "yes", "on", "0", "false", "no", "off", ""] {
        assert_eq!(
            with_var(PROBE, Some(agreed), || flag_owned(PROBE)),
            with_var(PROBE, Some(agreed), || flag_foreign(PROBE)),
            "{agreed:?} is a recognised spelling; both semantics must agree"
        );
    }
    for disputed in ["maybe", "2", "enabled"] {
        assert!(
            !with_var(PROBE, Some(disputed), || flag_owned(PROBE)),
            "owned: unknown is off"
        );
        assert!(
            with_var(PROBE, Some(disputed), || flag_foreign(PROBE)),
            "foreign: unknown is on"
        );
    }
}

/// An exact-value guard honours one spelling and refuses every other,
/// including plausible ones -- that refusal is the point.
#[test]
fn an_exact_value_guard_refuses_plausible_misspellings() {
    assert!(with_var(BROKER_ALLOW_PRIVILEGED.name, Some("1"), || {
        BROKER_ALLOW_PRIVILEGED.is_set()
    }));
    for refused in ["true", "yes", "on", "TRUE", " 1 "] {
        assert!(
            !with_var(BROKER_ALLOW_PRIVILEGED.name, Some(refused), || {
                BROKER_ALLOW_PRIVILEGED.is_set()
            }),
            "{refused:?} must not open a privilege guard"
        );
    }
}

/// Scanning another process's environment applies the same foreign rule as
/// reading our own, so a marker means the same thing seen from either side.
#[test]
fn scanning_a_value_agrees_with_reading_the_variable() {
    for value in ["1", "true", "maybe", "0", "false", "off", ""] {
        assert_eq!(
            value_is_affirmative_foreign(value),
            with_var(PROBE, Some(value), || flag_foreign(PROBE)),
            "{value:?} must read the same scanned as it does read directly"
        );
    }
}

/// The table is the inventory an embedder reads, so it must be findable and
/// must not say the same thing twice.
#[test]
fn declarations_are_sorted_and_unique() {
    let names: Vec<&str> = DECLARED.iter().map(|var| var.name).collect();
    let mut sorted = names.clone();
    sorted.sort_unstable();
    assert_eq!(names, sorted, "declarations must stay alphabetical");
    let mut unique = sorted.clone();
    unique.dedup();
    assert_eq!(unique, sorted, "a variable must be declared once");
}

/// Every declaration says what happens when the variable is unset and what it
/// is for. A blank field makes the inventory useless to the reader it exists
/// for.
#[test]
fn declarations_are_documented() {
    for var in DECLARED {
        assert!(!var.name.is_empty());
        assert!(
            !var.default.is_empty(),
            "{} has no documented default",
            var.name
        );
        assert!(!var.summary.is_empty(), "{} has no summary", var.name);
        match var.owner {
            Owner::Crate => assert!(
                var.name.starts_with("RUNNING_PROCESS_"),
                "{} is declared as ours but is not namespaced",
                var.name
            ),
            // Foreign variables are named by whoever defines them -- XDG,
            // systemd, Windows -- so there is no prefix to check. What matters
            // is that they are listed at all: an embedder scrubbing the
            // environment needs to know we read them.
            Owner::Foreign => assert!(!var.name.is_empty()),
        }
    }
}

/// The check that keeps the inventory true: every environment variable this
/// crate reads by name is declared here.
///
/// Scanning for `env::var("...")` rather than for our own prefix is what makes
/// the table answer the question an embedder actually asks. soldr vendors this
/// crate and scrubs route-selecting variables from the environments it builds;
/// it needs to know we read `XDG_RUNTIME_DIR` and `TMPDIR`, not only that we
/// read our own switches. Dropping `XDG_RUNTIME_DIR` is precisely what
/// stranded every request in zackees/soldr#2442.
///
/// Without this, the table is a snapshot that silently rots the first time
/// someone adds a variable -- the state this module was written to end. It
/// reads the sources rather than the built binary because a string literal is
/// what a future author will write.
#[test]
fn declaration_table_covers_every_variable() {
    let declared: std::collections::BTreeSet<&str> = DECLARED.iter().map(|var| var.name).collect();
    let mut undeclared: std::collections::BTreeSet<String> = Default::default();

    for path in source_files() {
        let text = std::fs::read_to_string(&path).expect("read source file");
        for found in literal_env_names(&text) {
            if !declared.contains(found.as_str()) {
                undeclared.insert(format!("{found} (in {})", path.display()));
            }
        }
    }

    assert!(
        undeclared.is_empty(),
        "these variables are read but not declared in DECLARED:\n  {}",
        undeclared.into_iter().collect::<Vec<_>>().join("\n  ")
    );
}

/// Names this crate uses for something other than reading an environment
/// variable, and so has nothing to declare for.
const NOT_ENVIRONMENT_READS: &[&str] = &[
    // Test fixtures that assert on environment *materialization* -- they are
    // written into a child's environment, never read from ours.
    "RUNNING_PROCESS_TEST_CLIENT_ONLY_ENV",
    "RUNNING_PROCESS_TEST_DAEMON_ONLY_ENV",
    "RUNNING_PROCESS_MATERIALIZE_CANARY",
    "RUNNING_PROCESS_BASELINE_CANARY",
    // This module's own probe variable.
    "RUNNING_PROCESS_ENV_VARS_PROBE",
];

const PREFIX: &str = "RUNNING_PROCESS_";

/// The call shapes that read a variable by name.
const READS: &[&str] = &["env::var(\"", "env::var_os(\""];

fn literal_env_names(text: &str) -> Vec<String> {
    let mut found = Vec::new();
    for read in READS {
        let mut index = 0;
        while let Some(start) = text[index..].find(read) {
            let open = index + start + read.len();
            let Some(len) = text[open..].find('"') else {
                break;
            };
            let name = &text[open..open + len];
            // A name, not an expression or a bare prefix used to build one.
            let is_a_name = !name.is_empty()
                && name != PREFIX
                && name
                    .chars()
                    .all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_');
            if is_a_name && !NOT_ENVIRONMENT_READS.contains(&name) {
                found.push(name.to_owned());
            }
            index = open + len;
        }
    }
    found
}

fn source_files() -> Vec<std::path::PathBuf> {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    let mut files = Vec::new();
    let mut stack = vec![root];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                files.push(path);
            }
        }
    }
    assert!(!files.is_empty(), "the crate must have sources to scan");
    files
}

/// A declaration says what happens when the variable is unset; the parser
/// decides what actually happens. They must be the same thing.
///
/// This test exists because they were not: `BROKER_OWNED_BIND` is documented as
/// on by default and was first declared `ForeignFlag`, whose unset case is off.
/// Nothing else in the suite would have noticed -- the switch is only exercised
/// when a test sets it -- so the default would have silently inverted.
#[test]
fn an_unset_flag_matches_its_declared_default() {
    for var in DECLARED {
        let declared_on = match var.kind {
            EnvKind::OwnedFlag | EnvKind::ForeignFlag | EnvKind::OptOutFlag => {
                describes_an_enabled_default(var.default)
            }
            EnvKind::ExactValue(_) => describes_an_enabled_default(var.default),
            _ => continue,
        };
        let actually_on = with_var(var.name, None, || var.is_set());
        assert_eq!(
            actually_on,
            declared_on,
            "{}: declared default {:?} says {}, but reading it unset gives {}",
            var.name,
            var.default,
            if declared_on { "on" } else { "off" },
            actually_on
        );
    }
}

/// Read a declared default line as on or off.
///
/// The defaults are prose, because an embedder reads them; this maps the two
/// shapes actually in use rather than pretending prose is a boolean. A default
/// that matches neither shape fails loudly instead of defaulting to "off",
/// which would let a mis-worded line pass the check above vacuously.
fn describes_an_enabled_default(default: &str) -> bool {
    match default {
        "broker-owned bind is used" => true,
        "privileged startup is refused"
        | "the broker is used"
        | "processes are tracked"
        | "the guard does not run"
        | "the process is not a daemon"
        | "a dev-build daemon relocates itself"
        | "not running under GitHub Actions" => false,
        other => panic!(
            "default {other:?} is not a phrasing this check recognises; \
             add it rather than letting the assertion pass vacuously"
        ),
    }
}

/// What `0` means is a property of the variable, and every numeric variable
/// must have decided it.
///
/// This is where a real bug lived: three millisecond parsers guarded against
/// zero and two did not, so `CLIENT_CONNECT_TIMEOUT_MS=0` produced a
/// zero-duration connect timeout -- every connection failing instantly --
/// while the same `0` on the RPC timeout fell back to the default. Neither
/// behaviour was written down, so neither was wrong on purpose.
#[test]
fn zero_means_what_each_numeric_variable_declares() {
    let mut checked = 0;
    for var in DECLARED {
        let EnvKind::Number {
            zero_selects_default,
        } = var.kind
        else {
            continue;
        };
        checked += 1;
        let sentinel = std::time::Duration::from_millis(9_999);
        let read = with_var(var.name, Some("0"), || var.millis_or(sentinel));
        if zero_selects_default {
            assert_eq!(
                read, sentinel,
                "{}: zero must fall back to the caller's default",
                var.name
            );
        } else {
            assert_eq!(
                read,
                std::time::Duration::ZERO,
                "{}: zero must be honoured as zero",
                var.name
            );
        }
    }
    assert!(checked >= 8, "expected the numeric variables to be checked");
}

/// A value that is not a number is a mistake, not a smaller number. Every
/// numeric variable falls back rather than guessing.
#[test]
fn an_unparseable_number_falls_back_to_the_default() {
    let sentinel = std::time::Duration::from_millis(4_242);
    for var in DECLARED {
        if !matches!(var.kind, EnvKind::Number { .. }) {
            continue;
        }
        for junk in ["", "  ", "abc", "12ms", "-1", "1.5"] {
            assert_eq!(
                with_var(var.name, Some(junk), || var.millis_or(sentinel)),
                sentinel,
                "{}: {junk:?} is not a number and must not be read as one",
                var.name
            );
        }
    }
}

/// Whitespace around a number is a formatting accident, not a different value.
#[test]
fn a_number_is_read_through_surrounding_whitespace() {
    let sentinel = std::time::Duration::from_millis(1);
    assert_eq!(
        with_var(CLIENT_RPC_TIMEOUT_MS.name, Some(" 250 "), || {
            CLIENT_RPC_TIMEOUT_MS.millis_or(sentinel)
        }),
        std::time::Duration::from_millis(250)
    );
}

/// A path is taken as the host wrote it. Repairing invalid Unicode would point
/// somewhere else, and an empty value names no path at all.
#[test]
fn a_path_is_taken_verbatim_and_an_empty_one_is_absent() {
    assert_eq!(
        with_var(MANIFEST_DIR.name, Some("/tmp/manifests"), || MANIFEST_DIR
            .path()),
        Some(std::path::PathBuf::from("/tmp/manifests"))
    );
    assert_eq!(
        with_var(MANIFEST_DIR.name, Some(""), || MANIFEST_DIR.path()),
        None
    );
    assert_eq!(
        with_var(MANIFEST_DIR.name, None, || MANIFEST_DIR.path()),
        None
    );
}

/// Text reads the same way: set-but-empty is not a value.
#[test]
fn empty_text_is_absent() {
    assert_eq!(
        with_var(DAEMON_SCOPE.name, Some("dev"), || DAEMON_SCOPE.text()),
        Some("dev".to_owned())
    );
    assert_eq!(
        with_var(DAEMON_SCOPE.name, Some(""), || DAEMON_SCOPE.text()),
        None
    );
}

/// Nothing outside this module reads an environment variable by name.
///
/// #1101 asks for a lint banning raw `env::var` once the tree is migrated, and
/// defers it until then because landing it early "just produces a large
/// allowlist that never shrinks". The migration is done, so this lands with no
/// allowlist at all -- which is the only version of this rule worth having.
///
/// What it forbids is a read whose variable name is written as a string
/// literal at the call site. Helpers that
/// take a name as a parameter are untouched, because a generic save-and-restore
/// around an arbitrary variable is not a policy decision about that variable
/// and has nothing to declare.
#[test]
fn no_literal_environment_read_lives_outside_this_module() {
    let mut offenders: Vec<String> = Vec::new();
    for path in source_files() {
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();
        // This module is where reading by name is supposed to happen.
        if name == "env_vars.rs" {
            continue;
        }
        let text = std::fs::read_to_string(&path).expect("read source file");
        for read in READS {
            let mut index = 0;
            while let Some(start) = text[index..].find(read) {
                let open = index + start + read.len();
                let Some(len) = text[open..].find('"') else {
                    break;
                };
                let named = &text[open..open + len];
                if !NOT_ENVIRONMENT_READS.contains(&named) {
                    offenders.push(format!("{}: {read}{named}\")", path.display()));
                }
                index = open + len;
            }
        }
    }
    offenders.sort();
    assert!(
        offenders.is_empty(),
        "read these through `crate::env_vars` instead, so the variable is \
         declared and parsed one way:\n  {}",
        offenders.join("\n  ")
    );
}

/// The combined inventory is the one list an embedder checks, so it must be
/// findable, say each name once, and document every entry -- including the
/// platform layer's variables that `DECLARED` never listed.
#[test]
fn the_combined_inventory_is_sorted_unique_and_documented() {
    let all = all_declared();
    let names: Vec<&str> = all.iter().map(|var| var.name).collect();
    let mut sorted = names.clone();
    sorted.sort_unstable();
    sorted.dedup();
    assert_eq!(names, sorted, "all_declared() must be sorted and unique");
    for var in &all {
        assert!(
            !var.summary.trim().is_empty(),
            "{} has no summary",
            var.name
        );
        assert!(
            !var.default.trim().is_empty(),
            "{} has no default",
            var.name
        );
    }
    for var in DECLARED.iter().chain(platform::DECLARED_PLATFORM) {
        assert!(
            names.contains(&var.name),
            "{} is declared but missing from all_declared()",
            var.name
        );
    }
}

/// A name read by both crates has one declaration, owned by the platform
/// layer and referred to from `DECLARED` with `use`. Two separate
/// declarations would be two places to edit, and the day they disagreed
/// `all_declared()` would silently keep whichever it saw first. The `use`
/// arm is what makes it one declaration; this holds the observable half:
/// what `DECLARED` publishes for a shared name is exactly the platform's.
#[test]
fn a_name_in_both_tables_is_one_declaration() {
    let mut shared = 0;
    for ours in DECLARED {
        let Some(theirs) = platform::DECLARED_PLATFORM
            .iter()
            .find(|theirs| theirs.name == ours.name)
        else {
            continue;
        };
        shared += 1;
        assert!(
            ours.summary == theirs.summary
                && ours.default == theirs.default
                && ours.kind == theirs.kind
                && ours.owner == theirs.owner,
            "{} is declared twice; refer to the platform declaration with `use` instead",
            ours.name
        );
    }
    assert!(shared > 0, "expected variables read by both crates");
}

/// Production code reaches the environment only through a declared
/// [`EnvVar`], or [`string_named`]/[`os_named`] for a name that is
/// caller-supplied data. This is the textual counterpart of the
/// `running_process_env_direct` Dylint lint: the lint sees only the host's
/// module graph and default features, this sees every `cfg` branch and every
/// feature-gated file, binaries included.
///
/// Test code is recognised by layout: a `#[cfg(test)]` (or
/// `#[cfg(all(test, ..))]`) inline `mod name {` runs to the end of its file,
/// as do `tests.rs`/`*_tests.rs` files and `tests/` directories.
#[test]
fn production_code_calls_std_env_only_through_declarations() {
    let mut offenders = Vec::new();
    for path in source_files() {
        let in_test_tree = path.components().any(|part| part.as_os_str() == "tests");
        let name = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default();
        if in_test_tree
            || name == "env_vars.rs"
            || name == "tests.rs"
            || name.ends_with("_tests.rs")
        {
            continue;
        }
        let text = std::fs::read_to_string(&path).expect("read source file");
        let lines: Vec<&str> = text.lines().collect();
        let cut = lines
            .iter()
            .enumerate()
            .position(|(index, line)| {
                let line = line.trim_start();
                (line.starts_with("#[cfg(test)]") || line.starts_with("#[cfg(all(test"))
                    && lines[index + 1..]
                        .iter()
                        .map(|next| next.trim())
                        .find(|next| !next.is_empty() && !next.starts_with("#["))
                        .is_some_and(|next| next.starts_with("mod ") && next.ends_with('{'))
            })
            .unwrap_or(lines.len());
        for (index, line) in lines[..cut].iter().enumerate() {
            let direct = [
                "env::var(",
                "env::var_os(",
                "env::set_var(",
                "env::remove_var(",
            ]
            .iter()
            .any(|call| line.contains(call));
            if direct && !line.trim_start().starts_with("//") {
                offenders.push(format!("{}:{}", path.display(), index + 1));
            }
        }
    }
    assert!(
        offenders.is_empty(),
        "read these through a declared `crate::env_vars` constant: {offenders:#?}"
    );
}

/// `all_declared()` deduplicates by name, which would quietly hide a variable
/// declared twice with different wording. The probe crate's table is a third,
/// independent declaration site, so check it shares no name with the other two.
#[cfg(feature = "probe")]
#[test]
fn the_probe_table_shares_no_name_with_the_running_process_or_platform_tables() {
    let below: Vec<&str> = DECLARED
        .iter()
        .chain(platform::DECLARED_PLATFORM)
        .map(|var| var.name)
        .collect();
    for var in running_process_probe::env_vars::DECLARED_PROBE {
        assert!(
            !below.contains(&var.name),
            "{} is declared by both the probe crate and a lower table",
            var.name
        );
    }
    let all = all_declared();
    for var in running_process_probe::env_vars::DECLARED_PROBE {
        assert!(
            all.iter().any(|listed| listed.name == var.name),
            "{} is missing from all_declared()",
            var.name
        );
    }
}