mirror of
https://github.com/tobi/disktree.git
synced 2026-12-01 00:01:02 +00:00
app: explore SSH scans read-only and export host-guarded cleanup
This commit is contained in:
@@ -11,6 +11,7 @@
|
||||
use std::fmt::Write as _;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::identity::HostIdentity;
|
||||
use crate::removal::Target;
|
||||
use crate::size::human_bytes;
|
||||
use crate::space::SpaceInfo;
|
||||
@@ -44,6 +45,23 @@ pub fn agent_prompt(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
space: Option<SpaceInfo>,
|
||||
) -> String {
|
||||
agent_prompt_for(
|
||||
targets,
|
||||
root,
|
||||
space,
|
||||
platform(),
|
||||
HostIdentity::current().as_ref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Same prompt, with the scanned machine's platform rather than the UI host's.
|
||||
pub fn agent_prompt_for(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
space: Option<SpaceInfo>,
|
||||
platform: &str,
|
||||
identity: Option<&HostIdentity>,
|
||||
) -> String {
|
||||
let total: u64 = targets.iter().map(|target| target.bytes).sum();
|
||||
let mut prompt = String::new();
|
||||
@@ -52,10 +70,35 @@ pub fn agent_prompt(
|
||||
"I need to free up disk space on this {} machine. I used disktree \
|
||||
to look through {} and picked the directories and files below for \
|
||||
deletion, {} in all.",
|
||||
platform(),
|
||||
platform,
|
||||
line(root).text(),
|
||||
human_bytes(total),
|
||||
);
|
||||
if let Some(identity) = identity {
|
||||
let _ = writeln!(
|
||||
prompt,
|
||||
"\nMANDATORY HOST CHECK before any destructive action:\n\
|
||||
Run hostname on the target and require the exact value {}.\n\
|
||||
An SSH alias is not proof of machine identity.",
|
||||
shell_quote(&identity.hostname),
|
||||
);
|
||||
if let Some(id) = &identity.machine_id {
|
||||
let _ = writeln!(
|
||||
prompt,
|
||||
"Read /etc/machine-id on the target and require {}.",
|
||||
shell_quote(id)
|
||||
);
|
||||
}
|
||||
prompt.push_str(
|
||||
"If either check fails, cannot be performed, or differs, STOP \
|
||||
and ask me. Do not delete anything or bypass these checks.\n",
|
||||
);
|
||||
} else {
|
||||
prompt.push_str(
|
||||
"\nHOST IDENTITY WAS NOT CAPTURED. Before deleting anything, STOP \
|
||||
and ask me to confirm the actual target hostname and machine ID.\n",
|
||||
);
|
||||
}
|
||||
if let Some(space) = space {
|
||||
let _ = writeln!(
|
||||
prompt,
|
||||
@@ -107,6 +150,131 @@ pub fn agent_prompt(
|
||||
prompt
|
||||
}
|
||||
|
||||
/// A POSIX shell literal, including embedded quotes. Never interpolate paths
|
||||
/// as shell source, even when the path came from our own scanner.
|
||||
pub fn shell_quote(text: &str) -> String {
|
||||
format!("'{}'", text.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
/// Export only; preview by default.
|
||||
///
|
||||
/// Remote scripts send their payload to the
|
||||
/// named SSH host, so running the export locally cannot remove local paths.
|
||||
/// GNU/Linux tools are required. This is deliberately more conservative than
|
||||
/// the app: symlinks and changed canonical paths are refused.
|
||||
pub fn delete_script(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
host: Option<&str>,
|
||||
) -> String {
|
||||
let identity = if host.is_none() {
|
||||
HostIdentity::current()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
delete_script_for(targets, root, host, identity.as_ref())
|
||||
}
|
||||
|
||||
/// Use the identity captured by the scanner, not the UI machine or SSH alias.
|
||||
pub fn delete_script_for(
|
||||
targets: &[Target],
|
||||
root: &Path,
|
||||
host: Option<&str>,
|
||||
identity: Option<&HostIdentity>,
|
||||
) -> String {
|
||||
let mut body = String::from("set -eu\n");
|
||||
body.push_str(&host_guard(identity));
|
||||
body.push_str(
|
||||
"command -v realpath >/dev/null\ncommand -v findmnt >/dev/null\n",
|
||||
);
|
||||
let _ = writeln!(body, "root={}", shell_quote(&root.to_string_lossy()));
|
||||
body.push_str(r#"remove() {
|
||||
p=$1
|
||||
case "$root" in /) prefix=/;; *) prefix=$root/;; esac
|
||||
case "$p" in "$prefix"*) ;; *) echo "Outside scan: $p" >&2; return 1;; esac
|
||||
[ "$p" != "$root" ] || return 1
|
||||
real=$(realpath -e -- "$p") || return 1
|
||||
[ "$real" = "$p" ] || {
|
||||
echo "Changed or linked path: $p" >&2; return 1;
|
||||
}
|
||||
case "$HOME/" in "$p/"*) echo "Contains home: $p" >&2; return 1;; esac
|
||||
for system in /etc /usr /boot /bin /sbin /lib /lib64 /dev /proc /sys /run /var/lib /nix /gnu; do
|
||||
case "$p/" in "$system/"*) echo "System path: $p" >&2; return 1;; esac
|
||||
case "$system/" in "$p/"*) echo "Contains system: $p" >&2; return 1;; esac
|
||||
done
|
||||
mounts=$(findmnt -rn --raw -o TARGET) || return 1
|
||||
printf '%s\n' "$mounts" | while IFS= read -r mount; do
|
||||
mount=$(env printf '%b' "$mount") || exit 1
|
||||
case "$mount/" in "$p/"*) echo "Contains mount: $p" >&2; exit 1;; esac
|
||||
done
|
||||
rm -rf --one-file-system --preserve-root=all -- "$p"
|
||||
}
|
||||
"#);
|
||||
for target in targets {
|
||||
if let Line::Plain(path) = line(&target.path) {
|
||||
let _ = writeln!(body, "remove {}", shell_quote(&path));
|
||||
}
|
||||
}
|
||||
let mut script = String::from(
|
||||
r#"#!/bin/sh
|
||||
(
|
||||
# Generated by disktree; review every path before running.
|
||||
# GNU/Linux only. Races, shared blocks and changed sizes are possible.
|
||||
# This is NOT a substitute for checking git work and tool-owned data.
|
||||
set -eu
|
||||
if [ "${1-}" != --delete ]; then
|
||||
"#,
|
||||
);
|
||||
let preview = format!(
|
||||
"PREVIEW ONLY. Target: {}. Review this script, then pass --delete.\n{}",
|
||||
host.unwrap_or("this machine"),
|
||||
delete_list(targets)
|
||||
);
|
||||
let _ = writeln!(
|
||||
script,
|
||||
"printf '%s\\n' {}\nexit 0\nfi",
|
||||
shell_quote(&preview)
|
||||
);
|
||||
if let Some(host) = host {
|
||||
let _ = writeln!(
|
||||
script,
|
||||
"printf '%s' {} | ssh -T -- {} 'sh -s'",
|
||||
shell_quote(&body),
|
||||
shell_quote(host)
|
||||
);
|
||||
} else {
|
||||
script.push_str(&body);
|
||||
}
|
||||
script.push_str("\n)\n");
|
||||
script
|
||||
}
|
||||
|
||||
fn host_guard(identity: Option<&HostIdentity>) -> String {
|
||||
let Some(identity) = identity else {
|
||||
return "echo 'Refusing deletion: scan has no host identity.' >&2\n\
|
||||
exit 1\n"
|
||||
.into();
|
||||
};
|
||||
let mut guard = String::from(
|
||||
"# Refuse to operate on any machine other than the scanned host.\n\
|
||||
IFS= read -r actual_host < /proc/sys/kernel/hostname || exit 1\n",
|
||||
);
|
||||
let _ = writeln!(
|
||||
guard,
|
||||
"[ \"$actual_host\" = {} ] || {{ echo 'Wrong hostname; refusing deletion.' >&2; exit 1; }}",
|
||||
shell_quote(&identity.hostname),
|
||||
);
|
||||
if let Some(id) = &identity.machine_id {
|
||||
guard.push_str("IFS= read -r actual_id < /etc/machine-id || exit 1\n");
|
||||
let _ = writeln!(
|
||||
guard,
|
||||
"[ \"$actual_id\" = {} ] || {{ echo 'Wrong machine ID; refusing deletion.' >&2; exit 1; }}",
|
||||
shell_quote(id),
|
||||
);
|
||||
}
|
||||
guard
|
||||
}
|
||||
|
||||
/// How a path can be written on one line.
|
||||
enum Line {
|
||||
/// As it is.
|
||||
@@ -168,6 +336,141 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn scripts_quote_paths_preview_and_remove_only_the_selection() {
|
||||
use std::process::Command;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let chosen = dir.path().join("quote'; $(touch injected)");
|
||||
let keep = dir.path().join("keep");
|
||||
std::fs::write(&chosen, b"chosen").unwrap();
|
||||
std::fs::write(&keep, b"keep").unwrap();
|
||||
let targets = [target(chosen.to_str().unwrap(), 6, false)];
|
||||
let script_path = dir.path().join("export.sh");
|
||||
let script = delete_script(&targets, dir.path(), None);
|
||||
std::fs::write(&script_path, script).unwrap();
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg("-n")
|
||||
.arg(&script_path)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg(&script_path)
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(chosen.exists(), "preview never deletes");
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg(&script_path)
|
||||
.arg("--delete")
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(!chosen.exists());
|
||||
assert!(keep.exists());
|
||||
|
||||
let remote = delete_script(&targets, dir.path(), Some("dev"));
|
||||
assert!(remote.contains("| ssh -T -- 'dev'"));
|
||||
std::fs::write(&script_path, remote).unwrap();
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg("-n")
|
||||
.arg(&script_path)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
Command::new("sh")
|
||||
.arg(&script_path)
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn scripts_refuse_paths_reached_through_symlinks() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let outside = tempfile::tempdir().unwrap();
|
||||
let keep = outside.path().join("keep");
|
||||
std::fs::write(&keep, b"keep").unwrap();
|
||||
symlink(outside.path(), dir.path().join("link")).unwrap();
|
||||
let path = dir.path().join("link/keep");
|
||||
let script = delete_script(
|
||||
&[target(path.to_str().unwrap(), 4, false)],
|
||||
dir.path(),
|
||||
None,
|
||||
);
|
||||
let file = dir.path().join("export.sh");
|
||||
std::fs::write(&file, script).unwrap();
|
||||
assert!(
|
||||
!std::process::Command::new("sh")
|
||||
.arg(file)
|
||||
.arg("--delete")
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
assert!(keep.exists());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn wrong_host_missing_identity_and_wrong_machine_id_cannot_delete() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("keep");
|
||||
std::fs::write(&file, b"keep").unwrap();
|
||||
let targets = [target(file.to_str().unwrap(), 4, false)];
|
||||
let actual = HostIdentity::current().unwrap();
|
||||
let mut wrong_host = actual.clone();
|
||||
wrong_host.hostname = "this-is-not-the-scanned-host".into();
|
||||
let mut wrong_id = actual.clone();
|
||||
wrong_id.machine_id = Some("00000000000000000000000000000000".into());
|
||||
for identity in [Some(wrong_host), Some(wrong_id), None] {
|
||||
let script = delete_script_for(
|
||||
&targets,
|
||||
dir.path(),
|
||||
None,
|
||||
identity.as_ref(),
|
||||
);
|
||||
let path = dir.path().join("script.sh");
|
||||
std::fs::write(&path, script).unwrap();
|
||||
let output = std::process::Command::new("sh")
|
||||
.arg(path)
|
||||
.arg("--delete")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(file.exists(), "host check must precede removal");
|
||||
}
|
||||
let prompt = agent_prompt_for(
|
||||
&targets,
|
||||
dir.path(),
|
||||
None,
|
||||
"linux",
|
||||
Some(&actual),
|
||||
);
|
||||
assert!(prompt.contains("MANDATORY HOST CHECK"));
|
||||
assert!(prompt.contains(&actual.hostname));
|
||||
if let Some(id) = actual.machine_id {
|
||||
assert!(prompt.contains(&id));
|
||||
}
|
||||
assert!(prompt.contains("Do not delete anything or bypass"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_is_one_path_per_line() {
|
||||
let targets = [
|
||||
|
||||
Reference in New Issue
Block a user