Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Verify canonical scan roots before recording history baselines (#93)

Vishnu Srivatsavaeebc077e0ed8
diff --git a/docs/scan-history.md b/docs/scan-history.md
index 5eb0044..2515f5d 100644
--- a/docs/scan-history.md
+++ b/docs/scan-history.md
@@ -5,8 +5,8 @@ scan: no previous comparable scan, unchanged totals, or signed changes in bytes,
files and folders. Queries use the existing host catalog, with no new ADB calls
or device traversal. Deletion permissions are unchanged.
-Only verified, published scan completions with **zero access errors** become
-history baselines. Failed, cancelled, truncated, root-changed and partially
+Only verified, published scan completions with **zero access errors** and
+verified canonical-root metadata become history baselines. Failed, cancelled, truncated, root-changed and partially
readable scans leave previous history intact. History failures never turn a
successful scan into a failed scan; the comparison becomes unavailable and the
reason is written to stderr. A complete scan with legitimate exclusions can be
@@ -28,12 +28,28 @@ contents or authentication secrets. Files created on Unix have mode 0600;
Windows uses the app data directory's inherited permissions. This is local
plaintext metadata, not encrypted storage.
-Comparisons require matching device serial, daemon-confirmed root, access mode,
-exclusion policy, counting-semantics version and skipped-entry count. Root mode
-reports its resolved root; shell mode retains the confirmed requested root.
-Different shell aliases remain separate keys rather than being guessed
-identical on the host. A counting/exclusion rule change must bump the semantics
-version. Version 1 is the first history format; unsupported format versions are
+Comparisons require matching device serial, daemon-verified canonical root,
+access mode, exclusion policy, counting-semantics version and skipped-entry
+count. Both shell and read-only scans use the resolved root. Different aliases of
+one directory can compare; retargeting an alias to another resolved root cannot
+reuse that baseline. Only the history key uses the canonical path: displayed
+paths and descriptor-anchored deletion still use the existing scan root.
+
+After verified completion and catalog publication, the host sends
+`SCAN_ROOT_INFO` to the same owned daemon on a new authenticated TCP connection,
+with a three-second absolute deadline and the existing 128 KiB response limit.
+The daemon resolves its pinned scan root and checks device/inode identity and
+the original root path before and after resolution. The host requires metadata
+version 1, the exact scanned root, matching access mode and a canonical absolute
+path. Unavailable, changed or malformed metadata skips history recording,
+leaving the scan usable and previous baselines intact. No extra ADB command or
+second storage scan is involved. UI comparison queries still use only host memory.
+
+Counting/identity semantics version **2** separates these verified canonical
+keys from version-1 logical-path baselines. After upgrading, the first eligible
+scan establishes a fresh baseline; old entries remain subject to normal
+retention. Future counting/exclusion changes must also bump this version.
+Version 1 is the first history format; unsupported format versions are
left unchanged, with no speculative migration.
Deltas describe logical scanned bytes and counts, not file-content changes,
@@ -85,7 +101,9 @@ non-regular-path failures, Unix symlinks/private file modes, and a separate
process holding the OS lock. Rust serialization and frontend parsing share a
first-scan wire fixture, preventing null-versus-omitted fields from drifting.
Scoped queries reject old generations/revisions and compare live catalog
-totals. Existing stream tests cover invalid/truncated completion and cancellation
+totals. Additional tests cover canonical alias equivalence, retargeted aliases,
+legacy-key isolation, malformed/mismatched metadata and deterministic alias
+replacement during native resolution. Existing stream tests cover invalid/truncated completion and cancellation
before publication; the history hook runs strictly after that publication gate.
Node tests validate numbers, timestamps, scopes and reconciliation. The built
@@ -93,7 +111,18 @@ UI replay uses mocked IPC for first comparisons, unchanged rescans, deletion
deltas, device separation and partial-scan unavailability. These are offline
checks, not physical-device validation. To check manually, restart
`npm run tauri dev`, scan twice, then use a disposable deletion and rescan.
-No Android daemon rebuild is required.
+This change requires rebuilding the Android daemon before manual testing:
+
+```sh
+bash engine/build.sh
+npm run tauri dev
+```
+
+The daemon pushes on the next connection. An older daemon still scans normally,
+but its unknown-command response disables history comparison instead of falling
+back to an unverified path. Check two stable scans, then (on a disposable test
+setup) aliases of the same directory and an alias retargeted to another root.
+The scan stream remains v1 and the authenticated session protocol remains v3.
Tracked in #36, adapting the history idea from
[Shanmukh's fork](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692)
diff --git a/docs/scan-stream-v1.md b/docs/scan-stream-v1.md
index 62c397a..1939dfb 100644
--- a/docs/scan-stream-v1.md
+++ b/docs/scan-stream-v1.md
@@ -119,3 +119,26 @@ Directory streaming and compact host construction are inspired by
particularly `e21a430`, `ec0679f` and `e7a7383`. This implementation keeps the
current C++ engine, authenticated session, anchored reads/deletion and root
safeguards rather than adopting the fork's daemon/transport wholesale.
+
+
+## Canonical root metadata for scan history
+
+After a verified stream reaches EOF, the host may send authenticated
+`SCAN_ROOT_INFO` on a fresh connection to the same owned daemon. A successful
+reply is small-command JSON, not a scan frame:
+
+```json
+{"status":"ok","version":1,"scan_root":"/sdcard","canonical_root":"/storage/emulated/0","read_only":false}
+```
+
+The paths above are illustrative. The daemon resolves only its pinned scan
+root and verifies the resolved path and original path against that root's
+device/inode identity. A missing or changed root returns an error. Resolving
+metadata does not grant deletion authority or replace deletion paths.
+
+The host checks the exact stream root, access mode, metadata version and
+canonical path before using it for history. Metadata failure does not invalidate
+a completed scan, but it cannot create or select a history baseline. Older
+daemons return Unknown command: scans continue, history remains unavailable
+until the daemon is rebuilt. This additive command changes neither session
+protocol v3 nor scan-stream v1; older clients do not need to request it.
diff --git a/engine/daemon.cpp b/engine/daemon.cpp
index ee2de46..bcceb56 100644
--- a/engine/daemon.cpp
+++ b/engine/daemon.cpp
@@ -400,6 +400,20 @@ static void handle_client(int fd) {
out.write(g_read_only ? "true" : "false");
out.write("}\n");
}
+ else if (cmd == "SCAN_ROOT_INFO") {
+ std::string canonical;
+ if (!g_scan_root.canonical_path(canonical) || canonical.size() > 16 * 1024) {
+ out.write("{\"status\":\"error\",\"message\":\"No unchanged successful scan root\"}\n");
+ } else {
+ out.write("{\"status\":\"ok\",\"version\":1,\"scan_root\":\"");
+ json_escape_into(out, g_scan_root.path);
+ out.write("\",\"canonical_root\":\"");
+ json_escape_into(out, canonical);
+ out.write("\",\"read_only\":");
+ out.write(g_read_only ? "true" : "false");
+ out.write("}\n");
+ }
+ }
else if (cmd == "SHUTDOWN") {
out.write("{\"status\":\"ok\",\"message\":\"shutting down\"}\n");
out.flush();
diff --git a/engine/safe_delete.h b/engine/safe_delete.h
index 822b20a..f3eea70 100644
--- a/engine/safe_delete.h
+++ b/engine/safe_delete.h
@@ -2,6 +2,7 @@
#include <cerrno>
#include <cstdint>
+#include <cstdlib>
#include <cstring>
#include <string>
#include <utility>
@@ -66,6 +67,23 @@ struct Root {
return fd.get() >= 0 && ::stat(path.c_str(), &current) == 0 &&
same_entry(identity, current);
}
+
+ // Resolve metadata only while it still describes this pinned scan root.
+ // Deletion continues to use the original path and descriptor, never this
+ // resolved string. Reject alias changes before or during resolution.
+ bool canonical_path(std::string& resolved) const {
+ if (!unchanged()) return false;
+ char* canonical = ::realpath(path.c_str(), nullptr);
+ if (!canonical) return false;
+ SOCKETSWEEP_DELETE_CHECKPOINT("canonical_root", fd.get(), canonical);
+ struct stat current{};
+ const bool matches = ::stat(canonical, &current) == 0 &&
+ same_entry(identity, current) && unchanged();
+ if (matches) resolved = canonical;
+ std::free(canonical);
+ return matches;
+ }
+
};
struct Result {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index cc3256c..e464566 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -458,7 +458,7 @@ fn run_scan(
let generation = new_random_id()?;
let catalog = scan_store::Catalog::new(response, generation.clone());
let json = catalog.summary_json()?;
- let history_entry = scan_history::completed_entry(&serial, &catalog);
+ let history_entry = scan_history::prepare_completion(&serial, &catalog);
// Serialize bounded metadata before publishing deletion authority.
let mut active = ACTIVE_SCAN
.lock()
@@ -471,7 +471,10 @@ fn run_scan(
drop(active);
// Completion and cancellation are committed above. History I/O happens
// outside the catalog lock and never changes whether the scan succeeded.
- let recorded = history_entry.and_then(|entry| {
+ let recorded = history_entry.and_then(|completion| {
+ let root_info = daemon_command_at(connection.address, "SCAN_ROOT_INFO",
+ &connection.token, Duration::from_secs(3))?;
+ let entry = completion.verify_root(&root_info)?;
let directory = app.path().app_data_dir()
.map_err(|e| format!("Cannot locate the app data directory: {e}"))?;
scan_history::record(&directory, entry)
diff --git a/src-tauri/src/scan_history.rs b/src-tauri/src/scan_history.rs
index f78c612..b4b2039 100644
--- a/src-tauri/src/scan_history.rs
+++ b/src-tauri/src/scan_history.rs
@@ -14,7 +14,9 @@ use std::time::{SystemTime, UNIX_EPOCH};
/// st_size bytes, symlink/`.`/`..` exclusion everywhere; root read-only adds
/// serial traversal, inode deduplication, virtual-filesystem and root mount
/// alias exclusions). Old entries stay unread comparisons, not false deltas.
-pub(crate) const COUNTING_SEMANTICS: u32 = 1;
+// v2 also requires a daemon-verified canonical root; logical-path baselines
+// from v1 cannot be reused even when their strings happen to match.
+pub(crate) const COUNTING_SEMANTICS: u32 = 2;
const FORMAT_VERSION: u32 = 1;
const MAX_PER_KEY: usize = 10;
const MAX_ENTRIES: usize = 100;
@@ -32,6 +34,15 @@ const INVALID_PREFIX: &str = "scan-history.invalid-";
// complete read/modify/replace transaction across app instances.
static FILE_LOCK: Mutex<()> = Mutex::new(());
+// A concurrent process spawn may briefly inherit a duplicate descriptor before
+// exec closes it. Explicit unlock releases ownership even while a copy exists.
+struct HistoryLock(std::fs::File);
+impl Drop for HistoryLock {
+ fn drop(&mut self) {
+ let _ = self.0.unlock();
+ }
+}
+
#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash, Debug)]
#[serde(rename_all = "snake_case")]
pub(crate) enum AccessMode {
@@ -73,7 +84,7 @@ pub(crate) struct HistoryEntry {
}
impl HistoryEntry {
- pub(crate) fn new(
+ fn new(
serial: &str,
root: &str,
read_only: bool,
@@ -314,6 +325,7 @@ pub(crate) fn record(directory: &Path, entry: HistoryEntry) -> Result<Recorded,
.map_err(|e| format!("Cannot open the history lock: {e}"))?;
lock.try_lock()
.map_err(|e| format!("History is busy or cannot be locked: {e}"))?;
+ let _lock = HistoryLock(lock);
let mut entries = match load(&path)? {
Loaded::Missing => Vec::new(),
Loaded::Entries(entries) => entries,
@@ -404,7 +416,62 @@ pub(crate) fn record(directory: &Path, entry: HistoryEntry) -> Result<Recorded,
Ok(Recorded { previous })
}
-pub(crate) fn completed_entry(serial: &str, catalog: &Catalog) -> Result<HistoryEntry, String> {
+/// Captured before catalog publication; verification can then perform network
+/// I/O without holding the catalog lock. Only verified roots produce entries.
+pub(crate) struct CompletedScan(HistoryEntry);
+
+impl CompletedScan {
+ pub(crate) fn verify_root(mut self, raw: &str) -> Result<HistoryEntry, String> {
+ #[derive(Deserialize)]
+ #[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
+ enum RootInfo {
+ Ok {
+ version: u32,
+ scan_root: String,
+ canonical_root: String,
+ read_only: bool,
+ },
+ Error {
+ message: String,
+ },
+ }
+ let info: RootInfo =
+ serde_json::from_str(raw).map_err(|_| "Invalid scan-root metadata".to_string())?;
+ let (version, scan_root, canonical_root, read_only) = match info {
+ RootInfo::Ok {
+ version,
+ scan_root,
+ canonical_root,
+ read_only,
+ } => (version, scan_root, canonical_root, read_only),
+ RootInfo::Error { message } => {
+ return Err(if message == "Unknown command" {
+ "Daemon lacks SCAN_ROOT_INFO; rebuild it to enable scan history".into()
+ } else {
+ format!("Canonical scan root unavailable: {message}")
+ })
+ }
+ };
+ let canonical = canonical_root == "/"
+ || (canonical_root.starts_with('/')
+ && canonical_root
+ .split('/')
+ .skip(1)
+ .all(|part| !matches!(part, "" | "." | "..")));
+ if version != 1
+ || scan_root != self.0.key.root
+ || read_only != (self.0.key.access == AccessMode::RootReadOnly)
+ || !canonical
+ {
+ return Err("Scan-root metadata does not match this scan".into());
+ }
+ self.0.key.root = canonical_root;
+ self.0.validate()?;
+ Ok(self.0)
+ }
+}
+
+pub(crate) fn prepare_completion(serial: &str, catalog: &Catalog) -> Result<CompletedScan, String> {
let (errors, skipped) = catalog.coverage();
if errors != 0 {
return Err("Scans with access errors are not recorded as history baselines".into());
@@ -424,7 +491,7 @@ pub(crate) fn completed_entry(serial: &str, catalog: &Catalog) -> Result<History
)?;
entry.skipped = skipped;
entry.validate()?;
- Ok(entry)
+ Ok(CompletedScan(entry))
}
// ── Current-scan comparison ──────────────────────────────────────────────────
@@ -567,7 +634,17 @@ mod tests {
serde_json::from_slice(&directory.read()).unwrap()
}
+ fn root_info(root: &str, canonical: &str, read_only: bool) -> String {
+ json!({"status":"ok", "version":1, "scan_root":root,
+ "canonical_root":canonical, "read_only":read_only})
+ .to_string()
+ }
+
fn response(size: u64) -> Response {
+ response_at(size, "/fixture", false)
+ }
+
+ fn response_at(size: u64, root: &str, read_only: bool) -> Response {
fn frame(kind: &str, data: Value) -> Vec<u8> {
let data = serde_json::to_vec(&json!({"type":kind,"data":data})).unwrap();
let mut bytes = (data.len() as u32).to_be_bytes().to_vec();
@@ -575,22 +652,22 @@ mod tests {
bytes
}
let entries = vec![
- json!({"id":0,"parent":null,"name":"fixture","kind":"directory","size":0,"counted":true}),
+ json!({"id":0,"parent":null,"name":root.rsplit('/').next().filter(|name| !name.is_empty()).unwrap_or("/"),"kind":"directory","size":0,"counted":true}),
json!({"id":1,"parent":0,"name":"leaf","kind":"file","size":size,"counted":true}),
];
let mut bytes = frame(
"started",
- json!({"stream_version":1,"root":"/fixture","read_only":false}),
+ json!({"stream_version":1,"root":root,"read_only":read_only}),
);
bytes.extend(frame("entries", json!({"entries":entries})));
let count = bytes.len();
bytes.extend(frame(
"done",
json!({"total_files":1,"total_dirs":1,"total_size":size,"errors":0,
- "skipped":0,"scan_time_ms":1,"scan_threads":4,"serialize_ms":0,
+ "skipped":0,"scan_time_ms":1,"scan_threads":if read_only {1} else {4},"serialize_ms":0,
"send_ms":0,"bytes_sent":count}),
));
- scan_stream::read(&mut Reader::new(bytes), false, |_| Ok(())).unwrap()
+ scan_stream::read(&mut Reader::new(bytes), read_only, |_| Ok(())).unwrap()
}
#[test]
@@ -922,19 +999,25 @@ mod tests {
let catalog = Catalog::new(response(7), "coverage".into());
record(
directory.path(),
- completed_entry("phone", &catalog).unwrap(),
+ prepare_completion("phone", &catalog)
+ .unwrap()
+ .verify_root(&root_info("/fixture", "/fixture", false))
+ .unwrap(),
)
.unwrap();
let original = directory.read();
let mut partial = response(3);
partial.errors = 1;
let partial = Catalog::new(partial, "partial".into());
- assert!(completed_entry("phone", &partial).is_err());
+ assert!(prepare_completion("phone", &partial).is_err());
assert_eq!(directory.read(), original);
let mut excluded = response(3);
excluded.skipped = 2;
let excluded = Catalog::new(excluded, "excluded".into());
- let changed = completed_entry("phone", &excluded).unwrap();
+ let changed = prepare_completion("phone", &excluded)
+ .unwrap()
+ .verify_root(&root_info("/fixture", "/fixture", false))
+ .unwrap();
assert!(record(directory.path(), changed.clone())
.unwrap()
.previous
@@ -1060,4 +1143,124 @@ mod tests {
assert_eq!(recorded.previous.unwrap().total_files, 1);
assert!(!temporary.exists());
}
+ #[test]
+ fn verified_canonical_roots_merge_aliases_but_separate_retargeting_and_legacy_keys() {
+ let directory = Directory::new("canonical");
+ let first = Catalog::new(response_at(7, "/alias-a", false), "first".into());
+ let baseline = prepare_completion("phone", &first)
+ .unwrap()
+ .verify_root(&root_info("/alias-a", "/physical/original", false))
+ .unwrap();
+ assert!(record(directory.path(), baseline)
+ .unwrap()
+ .previous
+ .is_none());
+ let second = Catalog::new(response_at(9, "/alias-b", false), "second".into());
+ let same = prepare_completion("phone", &second)
+ .unwrap()
+ .verify_root(&root_info("/alias-b", "/physical/original", false))
+ .unwrap();
+ assert_eq!(
+ record(directory.path(), same)
+ .unwrap()
+ .previous
+ .unwrap()
+ .total_size,
+ 7
+ );
+ let retargeted = prepare_completion("phone", &first)
+ .unwrap()
+ .verify_root(&root_info("/alias-a", "/physical/replacement", false))
+ .unwrap();
+ assert!(record(directory.path(), retargeted)
+ .unwrap()
+ .previous
+ .is_none());
+ let mut legacy = entry("legacy-phone", "/physical/original", false, 1, 1, 1);
+ legacy.key.counting_semantics = 1;
+ record(directory.path(), legacy).unwrap();
+ let current = prepare_completion("legacy-phone", &first)
+ .unwrap()
+ .verify_root(&root_info("/alias-a", "/physical/original", false))
+ .unwrap();
+ assert!(record(directory.path(), current)
+ .unwrap()
+ .previous
+ .is_none());
+ let readonly = Catalog::new(response_at(7, "/physical/original", true), "root".into());
+ let root = prepare_completion("phone", &readonly)
+ .unwrap()
+ .verify_root(&root_info("/physical/original", "/physical/original", true))
+ .unwrap();
+ assert!(record(directory.path(), root).unwrap().previous.is_none());
+ }
+
+ #[test]
+ fn malformed_stale_or_unverified_root_metadata_never_records_a_baseline() {
+ let directory = Directory::new("bad-root-info");
+ record(
+ directory.path(),
+ entry("phone", "/physical", false, 1, 1, 1),
+ )
+ .unwrap();
+ let original = directory.read();
+ let catalog = Catalog::new(response(7), "metadata".into());
+ let mut cases = vec![
+ "null".into(),
+ "{".into(),
+ json!({"status":"error", "message":"Unknown command"}).to_string(),
+ json!({"status":"error", "message":"No unchanged successful scan root"}).to_string(),
+ root_info("/wrong-scan", "/physical", false),
+ root_info("/fixture", "/physical", true),
+ ];
+ for path in ["relative", "/a/../b", "/a/./b", "//a", "/a/", "/a\0b"] {
+ cases.push(root_info("/fixture", path, false));
+ }
+ cases.push(root_info(
+ "/fixture",
+ &format!("/{}", "x".repeat(MAX_ROOT_BYTES)),
+ false,
+ ));
+ let mut version: Value =
+ serde_json::from_str(&root_info("/fixture", "/physical", false)).unwrap();
+ version["version"] = json!(2);
+ cases.push(version.to_string());
+ version["version"] = json!(1);
+ version["extra"] = json!(true);
+ cases.push(version.to_string());
+ for raw in cases {
+ let result = prepare_completion("phone", &catalog)
+ .unwrap()
+ .verify_root(&raw)
+ .and_then(|entry| record(directory.path(), entry));
+ assert!(result.is_err(), "{raw}");
+ assert_eq!(directory.read(), original);
+ }
+ for root in [
+ "/",
+ "/physical/a b",
+ "/physical/quote\"name",
+ "/physical/line\nname",
+ ] {
+ assert!(prepare_completion("phone", &catalog)
+ .unwrap()
+ .verify_root(&root_info("/fixture", root, false))
+ .is_ok());
+ }
+ }
+ #[test]
+ fn releasing_history_lock_does_not_wait_for_duplicate_descriptors() {
+ let directory = Directory::new("lock-copy");
+ std::fs::create_dir_all(directory.path()).unwrap();
+ let path = directory.path().join(LOCK_NAME);
+ let file = open_regular(&path, true).unwrap();
+ file.try_lock().unwrap();
+ let duplicate = file.try_clone().unwrap();
+ drop(HistoryLock(file));
+ let next = open_regular(&path, true).unwrap();
+ next.try_lock()
+ .expect("A duplicate must not prolong the previous writer's lock");
+ drop(HistoryLock(next));
+ drop(duplicate);
+ }
}
diff --git a/tests/safe_delete_test.cpp b/tests/safe_delete_test.cpp
index 54c8b91..d431a93 100644
--- a/tests/safe_delete_test.cpp
+++ b/tests/safe_delete_test.cpp
@@ -172,6 +172,26 @@ static void root_alias_swap_at_unlink_keeps_original_anchor() {
"Further deletion through the changed alias must be rejected");
}
+static void canonical_root_rejects_alias_changes_during_resolution() {
+ Fixture f;
+ const auto alias = f.base / "alias";
+ fs::create_directory_symlink(f.storage, alias);
+ require(f.root.open(alias.string()), "Cannot pin alias");
+ std::string canonical;
+ require(f.root.canonical_path(canonical) && canonical == f.storage.string(),
+ "Canonical metadata must identify the pinned root");
+ bool swapped = false;
+ checkpoint = [&](const char* event, int, const char*) {
+ if (std::string(event) != "canonical_root" || swapped) return;
+ swapped = true;
+ fs::remove(alias);
+ fs::create_directory_symlink(f.outside, alias);
+ };
+ require(!f.root.canonical_path(canonical) && swapped,
+ "Root metadata must reject an alias retargeted during resolution");
+ f.protected_file_survived();
+}
+
static void repeated_calls_release_descriptors() {
Fixture f;
struct rlimit limit{};
@@ -210,6 +230,7 @@ int main(int argc, char** argv) {
else if (test == "leaf_replaced") leaf_swap_before_identity_check();
else if (test == "leaf_unlink") leaf_swap_at_unlink_does_not_follow_symlink();
else if (test == "root_alias") root_alias_swap_at_unlink_keeps_original_anchor();
+ else if (test == "canonical_root") canonical_root_rejects_alias_changes_during_resolution();
else if (test == "descriptors") repeated_calls_release_descriptors();
else if (test == "depth") depth_limit_fails_without_following_links();
else require(false, "Unknown test case");
diff --git a/tests/test_daemon.py b/tests/test_daemon.py
index d4a86d9..6a454d9 100644
--- a/tests/test_daemon.py
+++ b/tests/test_daemon.py
@@ -116,7 +116,7 @@ class DaemonTests(DaemonHarness):
target = self.root / "keep"
target.write_text("keep")
self.scan()
- for command in ["PING", f"SCAN {self.root}", f"DELETE {target}", "SHUTDOWN"]:
+ for command in ["PING", "SCAN_ROOT_INFO", f"SCAN {self.root}", f"DELETE {target}", "SHUTDOWN"]:
self.assertEqual(self.raw_request((command + "\n").encode())["status"], "error")
wrong = f"AUTH {'0' * 64}\n{command}\n".encode()
self.assertEqual(self.raw_request(wrong)["status"], "error")
@@ -288,6 +288,7 @@ class DeletionRaceTests(unittest.TestCase):
def test_leaf_replacement_before_identity_check(self): self.run_case("leaf_replaced")
def test_leaf_symlink_replacement_at_unlink(self): self.run_case("leaf_unlink")
def test_scan_root_alias_swap_at_unlink(self): self.run_case("root_alias")
+ def test_canonical_root_rejects_alias_changes_during_resolution(self): self.run_case("canonical_root")
def test_repeated_calls_release_descriptors(self): self.run_case("descriptors")
def test_deep_recursion_stops_safely(self): self.run_case("depth")
diff --git a/tests/test_stream_scan.py b/tests/test_stream_scan.py
index e454b49..cd79724 100644
--- a/tests/test_stream_scan.py
+++ b/tests/test_stream_scan.py
@@ -66,6 +66,40 @@ class StreamScanTests(DaemonHarness):
self.assertEqual(item['total_size'], sum(e['size'] for e in entries.values()))
return item, entries, batches
+ def test_scan_root_info_requires_success_and_tracks_retargeted_aliases(self):
+ effective_read_only = self.read_only or os.geteuid() == 0
+ self.assertEqual(self.request('SCAN_ROOT_INFO')['status'], 'error')
+ alias = self.root.parent / 'scan-alias'
+ alias.symlink_to(self.root, target_is_directory=True)
+ done, entries, _ = self.collect(alias)
+ self.assertEqual(done['type'], 'done')
+ info = self.request('SCAN_ROOT_INFO')
+ self.assertEqual(info, dict(status='ok', version=1, scan_root=entries[0]['path'],
+ canonical_root=str(self.root.resolve()), read_only=effective_read_only))
+ outside = self.root.parent / 'other-root'
+ outside.mkdir()
+ alias.unlink()
+ alias.symlink_to(outside, target_is_directory=True)
+ if not effective_read_only:
+ self.assertEqual(self.request('SCAN_ROOT_INFO')['status'], 'error')
+ # Read-only traversal pins its resolved original path, so changing the
+ # caller's alias does not change which directory that scan describes.
+ done, _, _ = self.collect(alias)
+ self.assertEqual(done['type'], 'done')
+ self.assertEqual(self.request('SCAN_ROOT_INFO')['canonical_root'], str(outside.resolve()))
+ self.collect(outside / 'missing')
+ self.assertEqual(self.request('SCAN_ROOT_INFO')['status'], 'error')
+
+ def test_scan_root_info_preserves_escaped_canonical_names_and_exact_verb(self):
+ target = self.root.parent / 'target \" with space'
+ target.mkdir()
+ alias = self.root.parent / 'plain-alias'
+ alias.symlink_to(target, target_is_directory=True)
+ self.assertEqual(self.collect(alias)[0]['type'], 'done')
+ self.assertEqual(self.request('SCAN_ROOT_INFO')['canonical_root'], str(target.resolve()))
+ for command in ['SCAN_ROOT_INFOX', 'SCAN_ROOT_INFO /', 'SCAN_ROOT_INFO ']:
+ self.assertEqual(self.request(command)['status'], 'error')
+
def test_stream_requires_authentication_before_any_frames(self):
for prefix in ["", f"AUTH {'0' * 64}\n"]:
result = self.raw_request(f"{prefix}SCAN_STREAM {self.root}\n".encode())