Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions crates/tinycomputer-accessibility/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,20 @@ mod swift_source;

#[cfg(target_os = "macos")]
pub(crate) fn private_cache_dir(name: &str) -> Result<std::path::PathBuf, String> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};

let temp_dir = std::fs::canonicalize(std::env::temp_dir())
.map_err(|error| format!("failed to resolve temporary directory: {error}"))?;
let temp_metadata = std::fs::symlink_metadata(&temp_dir)
private_cache_dir_in(&temp_dir, name)
}

/// [`private_cache_dir`] under `temp_dir`, an already-resolved directory.
#[cfg(target_os = "macos")]
fn private_cache_dir_in(
temp_dir: &std::path::Path,
name: &str,
) -> Result<std::path::PathBuf, String> {
use std::os::unix::fs::{MetadataExt, PermissionsExt};

let temp_metadata = std::fs::symlink_metadata(temp_dir)
.map_err(|error| format!("failed to inspect temporary directory: {error}"))?;
if !temp_metadata.is_dir()
|| temp_metadata.mode() & 0o077 != 0
Expand Down
37 changes: 29 additions & 8 deletions crates/tinycomputer-accessibility/src/helper/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,18 +105,35 @@ pub(crate) fn helper_send_receive(
} // UNIFIED_HELPER released here — fire-and-forget callers can proceed

// Read until the line matches `id` (discards stale lines after a timeout or reordering).
let deadline = Instant::now() + HELPER_RECV_TIMEOUT;
match await_reply(&RESPONSE_RX, &id_str, HELPER_RECV_TIMEOUT)? {
Some(value) => Ok(value),
None => {
reset_helper_process();
Err(format!(
"helper response timed out waiting for id {id_str} (stale lines may follow)"
))
}
}
}

/// Reads lines from the helper's reply channel until one carries `id_str`,
/// discarding blank, stale, and unnumbered lines. `None` when `timeout`
/// passes first.
#[cfg(target_os = "macos")]
fn await_reply(
rx_slot: &StdMutex<Option<mpsc::Receiver<String>>>,
id_str: &str,
timeout: Duration,
) -> Result<Option<Value>, String> {
let deadline = Instant::now() + timeout;
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
reset_helper_process();
return Err(format!(
"helper response timed out waiting for id {id_str} (stale lines may follow)"
));
return Ok(None);
}
let chunk = remaining.min(Duration::from_millis(500));
let response_line = {
let rx_guard = RESPONSE_RX
let rx_guard = rx_slot
.lock()
.map_err(|_| "response rx lock poisoned".to_string())?;
let rx = rx_guard
Expand Down Expand Up @@ -148,9 +165,9 @@ pub(crate) fn helper_send_receive(
let matches = value
.get("id")
.and_then(|v| v.as_str())
.is_some_and(|rid| rid == id_str.as_str());
.is_some_and(|rid| rid == id_str);
if matches {
return Ok(value);
return Ok(Some(value));
}
log::debug!(
"[accessibility] discarding helper response with mismatched or missing id (want id={id_str})"
Expand Down Expand Up @@ -397,3 +414,7 @@ fn ensure_helper_binary() -> Result<PathBuf, String> {

Ok(binary_path)
}

#[cfg(test)]
#[path = "process_tests.rs"]
mod tests;
54 changes: 54 additions & 0 deletions crates/tinycomputer-accessibility/src/helper/process_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//! The helper reply wait: only the line carrying the request's id answers it.

#![cfg(target_os = "macos")]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::sync::{Mutex as StdMutex, mpsc};
use std::time::Duration;

use super::await_reply;

/// A reply channel holding `lines`. Keep the sender alive so an empty
/// channel times out instead of disconnecting.
fn channel(
lines: &[&str],
) -> (
mpsc::Sender<String>,
StdMutex<Option<mpsc::Receiver<String>>>,
) {
let (tx, rx) = mpsc::channel();
for line in lines {
tx.send((*line).to_owned()).unwrap();
}
(tx, StdMutex::new(Some(rx)))
}

#[test]
fn stale_blank_and_unnumbered_lines_are_skipped_until_the_id_matches() {
let (_tx, rx) = channel(&[
r#"{"id":"6","ok":"stale"}"#,
" ",
r#"{"ok":"no id"}"#,
r#"{"id":"7","ok":"mine"}"#,
]);
let reply = await_reply(&rx, "7", Duration::from_secs(1))
.unwrap()
.unwrap();
assert_eq!(reply["ok"], "mine");
}

#[test]
fn no_matching_reply_before_the_timeout_is_none() {
let (_tx, rx) = channel(&[r#"{"id":"6"}"#]);
assert!(
await_reply(&rx, "7", Duration::from_millis(50))
.unwrap()
.is_none()
);
}

#[test]
fn a_reply_that_is_not_json_is_an_error() {
let (_tx, rx) = channel(&["not json"]);
assert!(await_reply(&rx, "7", Duration::from_secs(1)).is_err());
}
59 changes: 58 additions & 1 deletion crates/tinycomputer-accessibility/src/helper_tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,64 @@
//! Tests for the platform-independent entry points of the Swift helper module.
//! Tests for the platform-independent entry points of the Swift helper module,
//! and the macOS helper cache directory.

#[cfg(not(target_os = "macos"))]
#[test]
fn precompile_entry_point_is_a_noop_off_macos() {
super::precompile_helper_background();
}

#[cfg(target_os = "macos")]
mod cache_dir {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use std::os::unix::fs::PermissionsExt;

use super::super::private_cache_dir_in;

/// A resolved temporary directory private to its owner.
fn private_temp() -> (tempfile::TempDir, std::path::PathBuf) {
let temp = tempfile::tempdir().unwrap();
let path = std::fs::canonicalize(temp.path()).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
(temp, path)
}

fn mode(path: &std::path::Path) -> u32 {
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}

#[test]
fn a_new_cache_dir_is_created_owner_only() {
let (_temp, root) = private_temp();
let dir = private_cache_dir_in(&root, "helper").unwrap();
assert_eq!(dir, root.join("helper"));
assert_eq!(mode(&dir), 0o700);
}

#[test]
fn an_existing_own_cache_dir_is_reused_and_made_owner_only() {
let (_temp, root) = private_temp();
let existing = root.join("helper");
std::fs::create_dir(&existing).unwrap();
std::fs::set_permissions(&existing, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(private_cache_dir_in(&root, "helper").unwrap(), existing);
assert_eq!(mode(&existing), 0o700);
}

#[test]
fn a_symlinked_cache_dir_is_refused() {
let (_temp, root) = private_temp();
let elsewhere = root.join("elsewhere");
std::fs::create_dir(&elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, root.join("helper")).unwrap();
assert!(private_cache_dir_in(&root, "helper").is_err());
}

#[test]
fn a_temp_dir_others_can_write_is_refused() {
let (_temp, root) = private_temp();
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o770)).unwrap();
assert!(private_cache_dir_in(&root, "helper").is_err());
assert!(!root.join("helper").exists(), "nothing is created there");
}
}
Loading