From 718712eb0132fe0b7a1390eaa12187c672b84233 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:57:05 -0500 Subject: [PATCH] fix: secure and refresh unrooted log exports --- .../launcher/agent/AgentBridgeProvider.kt | 9 +++- .../session/EnhancedSessionLogShare.kt | 5 ++- .../session/SessionLogShareZipTest.kt | 7 +++- docs/agent-control.md | 2 + tools/droiddeckctl | 41 +++++++++++++++++-- tools/tests/test_droiddeckctl.py | 25 +++++++++-- 6 files changed, 78 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt index 5570bd9810..a7a9306808 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentBridgeProvider.kt @@ -25,6 +25,7 @@ import com.droiddeck.launcher.session.SessionState import org.json.JSONArray import org.json.JSONObject import java.io.File +import java.util.UUID import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @@ -206,7 +207,13 @@ class AgentBridgeProvider : ContentProvider() { private fun logs(context: Context): JSONObject { val dir = logDir(context)?.takeIf { it.isDirectory } ?: return error("NO_SESSION_LOGS", "No session artifact directory is available") - val zip = SessionLogShare.zipFolder(context, dir, File(context.getExternalFilesDir(null), "agent-logs")) + val output = File(context.getExternalFilesDir(null), "agent-logs/${UUID.randomUUID()}") + val zip = try { + SessionLogShare.zipFolder(context, dir, output) + } catch (error: Exception) { + output.deleteRecursively() + throw error + } ?: return error("NO_SESSION_LOGS", "The session artifact directory is empty") return JSONObject().put("ok", true).put("command", "logs").put("sessionId", dir.name).put("zip", zip.absolutePath) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index 899faf4ca0..d20da13d62 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -27,6 +27,7 @@ import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes import java.security.MessageDigest import java.util.Locale +import java.util.UUID import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream @@ -107,7 +108,7 @@ internal object EnhancedSessionLogShare { return emptyList() } val out = SessionLogShare.shareDir(context).apply { deleteRecursively(); mkdirs() } - val stage = File(out, ".diagnostic-stage").apply { mkdirs() } + val stage = File(context.cacheDir, "${out.name}-${UUID.randomUUID()}.diagnostic-stage").apply { mkdirs() } val redactionLearningComplete = LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) val discovery = collect(context, folder, limits.maxDiscoveredFiles, legacy = false) val candidates = discovery.candidates @@ -173,7 +174,7 @@ internal object EnhancedSessionLogShare { out.deleteRecursively() return null } - val stage = File(out, ".diagnostic-stage").apply { mkdirs() } + val stage = File(context.cacheDir, "${out.name}-${UUID.randomUUID()}.diagnostic-stage").apply { mkdirs() } val records = ArrayList() val budget = Budget(limits.maxBytesTotal) val zip = File(out, "DroidDeck-${folder.name}.zip") diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt index cd4a711d15..0779a378cb 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareZipTest.kt @@ -29,15 +29,20 @@ class SessionLogShareZipTest { @Test fun anArchiveCanBeWrittenOutsideTheShareFolder() { SessionLogShare.clear(app) val session = File(LinuxRuntime.logDir(app), "2026-11-03-01-steam").apply { mkdirs() } - val out = File(app.getExternalFilesDir(null), "agent-logs") + val out = File(app.getExternalFilesDir(null), "agent-logs/request-1") + val secondOut = File(app.getExternalFilesDir(null), "agent-logs/request-2") try { File(session, "session.log").writeText("booted\n") val zip = SessionLogShare.zipFolder(app, session, out)!! + val secondZip = SessionLogShare.zipFolder(app, session, secondOut)!! assertEquals(out, zip.parentFile) assertFalse(File(app.cacheDir, "share").exists()) assertTrue(zip.isFile) + assertTrue(secondZip.isFile) + assertTrue(zip.isFile) } finally { out.deleteRecursively() + secondOut.deleteRecursively() session.deleteRecursively() } } diff --git a/docs/agent-control.md b/docs/agent-control.md index dbbdbb9b03..eba6ca7735 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -78,6 +78,8 @@ text. This does not redact arbitrary authorized command results, CDP data, prefe captures. Scenario directories are owner-only and JSON reports are written with mode 0600. Review artifacts before sharing. `logs` downloads the archive Share logs builds (scrubbed, Steam logs over 8 MiB left out) from the app's external files folder, since adb cannot read the session folder itself. +When the installed app predates archive export, the CLI falls back to pulling the private session folder; +that legacy path is available only with root and is not scrubbed before download. ## Device selection and output diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 559a437a89..14676771f5 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -424,8 +424,20 @@ def start_session(adb: str, serial: str, request: dict) -> dict: def unpack_logs(archive: Path, destination: Path, session_id: str) -> None: """Unpack a Share logs zip so the session's own files sit at the top of destination.""" + destination = destination.resolve() + destination.mkdir(parents=True, exist_ok=True) + manifest = destination / ".droiddeckctl-managed-logs.json" try: - with zipfile.ZipFile(archive) as z: + previous = json.loads(manifest.read_text(encoding="utf-8")) + if not isinstance(previous, list) or any(not isinstance(name, str) for name in previous): + previous = [] + except (OSError, ValueError): + previous = [] + previous = set(previous) + extracted = set() + try: + with tempfile.TemporaryDirectory(prefix="droiddeckctl-logs-") as temp, zipfile.ZipFile(archive) as z: + staged = Path(temp) for entry in z.infolist(): name = entry.filename if name.startswith(session_id + "/"): @@ -433,9 +445,29 @@ def unpack_logs(archive: Path, destination: Path, session_id: str) -> None: target = (destination / name).resolve() if entry.is_dir() or not name or not target.is_relative_to(destination): continue - target.parent.mkdir(parents=True, exist_ok=True) - with z.open(entry) as source, target.open("wb") as copy: + relative = target.relative_to(destination).as_posix() + if relative == manifest.name: + continue + staged_file = staged / relative + staged_file.parent.mkdir(parents=True, exist_ok=True) + with z.open(entry) as source, staged_file.open("wb") as copy: shutil.copyfileobj(source, copy) + extracted.add(relative) + for name in extracted - previous: + target = destination / name + if target.exists() or target.is_symlink(): + raise ControlError(f"Refusing to overwrite an unrelated file: {target}", "LOG_PULL_FAILED") + for name in previous - extracted: + target = (destination / name).resolve() + if target.is_relative_to(destination) and target.is_file() and not target.is_symlink(): + target.unlink() + for name in extracted: + target = destination / name + target.parent.mkdir(parents=True, exist_ok=True) + os.replace(staged / name, target) + temp_manifest = manifest.with_name(manifest.name + ".tmp") + temp_manifest.write_text(json.dumps(sorted(extracted), indent=2) + "\n", encoding="utf-8") + os.replace(temp_manifest, manifest) except (OSError, zipfile.BadZipFile) as exc: raise ControlError(f"Could not unpack the session logs: {exc}", "LOG_PULL_FAILED") from exc @@ -766,6 +798,7 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120) else: zip_path = checked(exported, "LOG_PULL_FAILED")["zip"] + cleanup_dir = str(Path(zip_path).parent) try: if exported.get("sessionId", session["id"]) != session["id"]: raise ControlError("A new session started while the logs were exported; run logs again", @@ -777,7 +810,7 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict: unpack_logs(local_zip, destination, session["id"]) finally: # The copy sits in shared storage, so it does not outlive the pull. - run_adb(adb, serial, "shell", "rm", "-f", zip_path, timeout=30) + run_adb(adb, serial, "shell", "rm", "-rf", cleanup_dir, timeout=30) if result.returncode != 0: detail = (result.stderr or result.stdout).decode(errors="replace").strip() raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED") diff --git a/tools/tests/test_droiddeckctl.py b/tools/tests/test_droiddeckctl.py index 565e918c81..0b521b5a05 100644 --- a/tools/tests/test_droiddeckctl.py +++ b/tools/tests/test_droiddeckctl.py @@ -138,7 +138,7 @@ CPUFREQ = textwrap.dedent('''\ def battery(tenths): return f"Current Battery Service state:\n level: 80\n temperature: {tenths}\n technology: Li-poly" PRIVATE_LOG_DIR = "/data/user/0/com.droiddeck.launcher/files/logs/sessions/s1" -EXPORTED_ZIP = "/storage/emulated/0/Android/data/com.droiddeck.launcher/files/agent-logs/DroidDeck-s1.zip" +EXPORTED_ZIP = "/storage/emulated/0/Android/data/com.droiddeck.launcher/files/agent-logs/request-1/DroidDeck-s1.zip" def share_zip(entries): @@ -542,7 +542,7 @@ class DroiddeckctlTest(FakeAdbTest): self.assertEqual("e", (destination / "stores" / "epic.log").read_text()) self.assertFalse((self.dir / "outside").exists()) self.assertEqual([["pull", EXPORTED_ZIP]], [c["args"][:2] for c in self.calls() if c["args"][:1] == ["pull"]]) - self.assertIn(["shell", "rm", "-f", EXPORTED_ZIP], [c["args"] for c in self.calls()]) + self.assertIn(["shell", "rm", "-rf", str(Path(EXPORTED_ZIP).parent)], [c["args"] for c in self.calls()]) def test_logs_of_a_session_that_started_meanwhile_are_refused(self): self.configure({"state": ended_state(), "logs": {"ok": True, "sessionId": "s2", "zip": EXPORTED_ZIP}}, @@ -551,7 +551,26 @@ class DroiddeckctlTest(FakeAdbTest): self.assertEqual(6, code) self.assertEqual("LOG_PULL_FAILED", out["error"]["code"]) self.assertFalse((self.dir / "artifacts").exists()) - self.assertIn(["shell", "rm", "-f", EXPORTED_ZIP], [c["args"] for c in self.calls()]) + self.assertIn(["shell", "rm", "-rf", str(Path(EXPORTED_ZIP).parent)], [c["args"] for c in self.calls()]) + + def test_logs_replace_the_previous_snapshot_and_preserve_unrelated_files(self): + destination = self.dir / "artifacts" + destination.mkdir() + (destination / "notes.txt").write_text("keep me") + first = self.dir / "first.zip" + with zipfile.ZipFile(first, "w") as archive: + archive.writestr("s1/session.log", "first") + archive.writestr("s1/steam/console.log", "old") + ctl.unpack_logs(first, destination, "s1") + self.assertEqual("old", (destination / "steam/console.log").read_text()) + + second = self.dir / "second.zip" + with zipfile.ZipFile(second, "w") as archive: + archive.writestr("s1/session.log", "second") + ctl.unpack_logs(second, destination, "s1") + self.assertEqual("second", (destination / "session.log").read_text()) + self.assertFalse((destination / "steam/console.log").exists()) + self.assertEqual("keep me", (destination / "notes.txt").read_text()) def test_logs_from_an_older_build_fall_back_to_the_private_folder(self): self.configure({"state": ended_state()})