Skip to content

Commit 08c0666

Browse files
fix(tools): refuse cross-user signing-conflict removal
Check other users before removing foreground-user app data. Fail closed when installation ownership cannot be verified, and report retained signing conflicts without attempting broader uninstall.
1 parent 7ea3a02 commit 08c0666

5 files changed

Lines changed: 116 additions & 7 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ Avoid blocking work on latency-sensitive threads, unnecessary polling, duplicate
105105
- **Measurement tools:** profile build + simpleperf ([docs/PROFILING.md](docs/PROFILING.md)); pin a preset with `adb shell setprop debug.projectmtv.preset '<name prefix>'` and clear it afterwards (`debug.projectmtv.update_from` also exists); `tools/tv-diagnostics.sh <tv-ip>:5555 --sweep` ([docs/DIAGNOSTICS.md](docs/DIAGNOSTICS.md); profile builds require `--package nl.neerdael.projectmtv.profile` with a matching `--apk` or `--no-install`; build/`--release` modes reject alternate package IDs before connecting); Preset Lab for offline rendering comparisons (desktop timings do not establish TV performance).
106106
- **Documented device coverage:** NVIDIA SHIELD TV 2019 (`sif`, 2 GB, 32-bit) and SHIELD TV Pro 2019 (`mdarcy`, 3 GB), Android 11; Ugoos AM6 (Amlogic S922X, Mali-G52 MP6, Android 9). No emulator configuration is committed.
107107
- **The notification listener restarts the app after `am force-stop`** (within about a second, verified on the AM6, Android 9, and the AM9 Pro, Android 14): a stop/start is warm, and the process reads `projectm_settings` at that restart. A process that reads the file mid-write saves its migration flags over it. Resolve `am get-current-user` once; use that numeric ID for settings/listener commands, permission grants, installation and `am force-stop`/`am start`. Filter `ps -A -o UID,PID,NAME` by exact process name and `UID / 100000` for that user; `pidof` includes other users. Failed/malformed queries must not mean "no process". Write `/data/user/<userId>/<package>/shared_prefs/projectm_settings.xml`, not user 0's `/data/data` alias. Disallow the listener only if that user enabled it, restore the same user's access, and check `surface=` in its STATS lines ([docs/PROFILING.md](docs/PROFILING.md)); `tv-diagnostics.sh` uses this scope for its cold start and records the user. Command support was checked in Android 9/14 sources; older releases remain unverified.
108+
- **Diagnostics signing conflicts:** `--allow-uninstall` attempts removal only for the captured Android user. Before removing data, inspect `pm list users` and exact package results from `pm list packages --user <userId>` for every other user, including stopped users; refuse if another user has the package or a query fails/is malformed. Shared or preinstalled package code can retain the incompatible signing key. A retained conflict fails explicitly after the scoped retry; never broaden to all-user uninstall. Use `--no-install` or a matching-key APK instead ([docs/DIAGNOSTICS.md](docs/DIAGNOSTICS.md)).
108109
- **Measured lessons (ARCHITECTURE §5):** listing ~10k assets took 8.4 s and blocked UI inflation → the worker reads `presets.idx`; GL linking at switches froze the picture 0.5–1.9 s → background prewarm and program caches; tile-based GPUs paid for render-target loads → patches 0009–0016.
109110

110111
## Dependencies, state, and lifecycle
@@ -194,7 +195,7 @@ python3 -m unittest discover -s .github/scripts/tests -v
194195
| `tools/check-patch-series.sh` | full series applies to a clean export of the submodule's `HEAD` (so the submodule must be at the pinned commit) | Verified: "all 29 patches apply" on `main`; the 32-patch series was verified with the same steps against `e0b0a967`; "all 35 patches apply" on 2026-10-04 with 0033–0035; 37 patches verified after integrating the parser fix for the random-binding task |
195196
| `tools/projectm-host-tests.sh [--gtest_filter=…]` | patched projectM GTest suite (build in `build/projectm-host`); needs CMake, Ninja, C++ compiler, Homebrew googletest | Verified on macOS: 179/179 on `main`, 204/204 with 0030–0032, 222/222 with 0001–0035 (configured with `-DCMAKE_DISABLE_FIND_PACKAGE_FLEX=ON -DCMAKE_DISABLE_FIND_PACKAGE_BISON=ON` to match the Android build's pre-generated parser) |
196197
| `python3 -m unittest discover -s .github/scripts/tests -v` | release tooling | Verified: 74 tests OK (Python 3.13.12) |
197-
| `python3 -m unittest discover -s tools -p test_tv_diagnostics.py -v` | diagnostics package/APK-source options; user-scoped cold start, process filtering and fail-safe queries; isolated fake adb, no TV/build/network | Run by Android CI; see task validation for the current revision |
198+
| `python3 -m unittest discover -s tools -p test_tv_diagnostics.py -v` | diagnostics package/APK-source options; user-scoped cold start, process filtering, fail-safe queries and signing-conflict recovery; isolated fake adb, no TV/build/network | Run by Android CI; see task validation for the current revision |
198199
| `core/src/test/native/run_native_tests.sh` | engine tests, GL fade overlay, patched-projectM regressions (ASan/UBSan); needs a C++17 compiler, JDK (`jni.h`), CMake, EGL/GLES dev libs on Linux (macOS uses OpenGL) | Verified on macOS 2026-10-04 (JDK 21): engine tests and projectm-regressions pass; GL fade overlay skipped without EGL/GLES; CI runs all on Linux |
199200
| `./gradlew testReleaseUnitTest` (CI) / `./gradlew testDebugUnitTest` (PR template) | app and core JVM tests | Verified 2026-10-04: `testReleaseUnitTest` BUILD SUCCESSFUL |
200201
| `./gradlew assembleRelease` / `./gradlew :core:assembleDebug` / `./gradlew assembleProfile` | APK + AAR; patch application through CMake; profile build | CI runs `assembleRelease`; verified 2026-10-04: `:app:assembleProfile :core:assembleRelease`, and `:core:assembleDebug` from a fresh recursive clone (CMake applied the series); a new worktree needs `local.properties` copied from the primary checkout |

‎docs/DIAGNOSTICS.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ The first connection shows an *Allow debugging?* prompt on the TV; accept it wit
2222
| `--apk PATH` | Installs the supplied APK; its application ID must match `--package` (or the default ID) |
2323
| `--no-install` | Tests the version that is already installed |
2424
| `--package ID` | Application ID to test (default `nl.neerdael.projectmtv`). Alternate IDs require a matching `--apk` or `--no-install`; building and `--release` only support the default ID |
25-
| `--allow-uninstall` | If the installed app has a different signing key, uninstall it first (resets app settings) |
25+
| `--allow-uninstall` | Attempts signing-key recovery by uninstalling only for the captured Android user (resets that user's app settings); refuses if another user has the same package or that state cannot be verified |
2626
| `--sweep` | Also measures each fixed resolution (720p, 1080p, …), driving the menu with key events |
2727
| `--duration SEC` | Observation time (default 180) |
2828

@@ -34,6 +34,8 @@ tools/tv-diagnostics.sh 192.168.50.105:5555 --package nl.neerdael.projectmtv.pro
3434

3535
To install a newly built profile APK instead, replace `--no-install` with `--apk app/build/outputs/apk/profile/app-profile.apk`. The script does not inspect supplied APKs to verify their application ID; supply an APK that matches the package being tested. Incompatible build/`--release` and package combinations fail before connecting to the TV, building, downloading or installing anything. If multiple APK-source options are supplied, the last one selects the mode; the package check uses that final mode regardless of option order.
3636

37+
On a signing-key conflict, `--allow-uninstall` checks `pm list users` and each other user's `pm list packages --user <userId>` before removing any app data. Another user's installation, including a stopped user's, retains shared package code and its signing key; the script refuses recovery in that case. Failed or malformed queries also stop before uninstalling. Use `--no-install` to measure the existing app or supply an APK signed with its installed key. If Android still retains an incompatible package after an allowed user-scoped uninstall (for example a preinstalled package), the retry fails explicitly; the script never broadens removal to all users.
38+
3739
## What it collects
3840

3941
| File | Content |

‎tools/test_tv_diagnostics.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,52 @@ def run_diagnostics(self, failure="", launch_state="COLD"):
112112
def adb_calls(self):
113113
return [json.loads(line) for line in self.calls.read_text().splitlines()]
114114

115+
def run_conflicting_install(self, installed_users, failure="", mode="conflict"):
116+
state = json.loads(self.state.read_text())
117+
state.update(installed_users=installed_users, installs=0, uninstalls=0)
118+
self.state.write_text(json.dumps(state))
119+
apk = self.root / "app.apk"
120+
apk.touch()
121+
self.environment["DIAGNOSTICS_TEST_FAILURE"] = failure
122+
self.environment["DIAGNOSTICS_TEST_INSTALL"] = mode
123+
return self.run_script(["--apk", str(apk), "--allow-uninstall", "--duration", "30"])
124+
125+
def test_signing_conflict_preserves_data_when_installed_for_another_user(self):
126+
for installed_users in ([0, 10], [10, 11]): # Include a stopped user.
127+
with self.subTest(installed_users=installed_users):
128+
result = self.run_conflicting_install(installed_users)
129+
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
130+
self.assertIn("another Android user", result.stdout)
131+
state = json.loads(self.state.read_text())
132+
self.assertEqual(state["uninstalls"], 0)
133+
self.assertEqual(state["installed_users"], installed_users)
134+
self.assertEqual(state["installs"], 1)
135+
136+
def test_signing_conflict_does_not_uninstall_when_user_queries_fail(self):
137+
for failure in ("users-error", "users-malformed", "packages-error", "packages-malformed"):
138+
with self.subTest(failure=failure):
139+
result = self.run_conflicting_install([10], failure)
140+
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
141+
self.assertIn("cannot verify", result.stdout)
142+
state = json.loads(self.state.read_text())
143+
self.assertEqual(state["uninstalls"], 0)
144+
self.assertEqual(state["installed_users"], [10])
145+
146+
def test_signing_conflict_uninstalls_only_sole_installation_user(self):
147+
result = self.run_conflicting_install([10])
148+
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
149+
uninstalls = [call for call in self.adb_calls() if call[:1] == ["uninstall"]]
150+
self.assertEqual(uninstalls, [["uninstall", "--user", "10", PACKAGE]])
151+
self.assertEqual(json.loads(self.state.read_text())["installs"], 2)
152+
153+
def test_retained_signing_conflict_is_explicit_without_broader_uninstall(self):
154+
result = self.run_conflicting_install([10], mode="retained-conflict")
155+
self.assertEqual(result.returncode, 1, result.stdout + result.stderr)
156+
self.assertIn("remains after", result.stdout)
157+
uninstalls = [call for call in self.adb_calls() if call[:1] == ["uninstall"]]
158+
self.assertEqual(uninstalls, [["uninstall", "--user", "10", PACKAGE]])
159+
self.assertEqual(json.loads(self.state.read_text())["installs"], 2)
160+
115161
def test_secondary_user_process_is_measured_without_other_user_process(self):
116162
for launch_state in ("", "COLD"): # Android 9 has no LaunchState line; Android 14 does.
117163
with self.subTest(launch_state=launch_state):

‎tools/tv-diagnostics.sh‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
# --no-install test the version that is already installed
1111
# --package ID application ID to test (default nl.neerdael.projectmtv); for example
1212
# nl.neerdael.projectmtv.profile with a matching --apk or --no-install (not build/--release)
13-
# --allow-uninstall if the install fails because of a different signing key, uninstall the
14-
# existing app first (this resets the app's settings)
13+
# --allow-uninstall on a signing-key conflict, uninstall for this user (resets its settings)
14+
# only if no other Android user has the app; otherwise refuse
1515
# --sweep also measure each fixed resolution (drives the menu with key events)
1616
# --out DIR output directory (default diagnostics/<model>-<timestamp>)
1717
#
@@ -103,6 +103,26 @@ app_pids() {
103103
int($1 / 100000) == user && $3 == pkg { pid = $2; matches++ }
104104
END { if (bad || matches > 1) exit 1; if (matches == 1) print pid }'
105105
}
106+
other_package_users() {
107+
local user_table user_ids other_user packages
108+
user_table="$(ash_checked pm list users)" || return 1
109+
user_ids="$(printf '%s\n' "$user_table" | awk -v current="$ANDROID_USER" '
110+
NR == 1 { if ($0 != "Users:") { bad = 1; exit 1 }; next }
111+
/^[[:space:]]*$/ { next }
112+
!/^[[:space:]]*UserInfo\{[0-9]+:/ { bad = 1; exit 1 }
113+
{ sub(/^[[:space:]]*UserInfo\{/, ""); sub(/:.*/, "");
114+
if ($0 == current) found_current = 1; else print }
115+
END { if (bad || !found_current) exit 1 }')" || return 1
116+
# Include stopped users: their installed package still retains the shared signing key.
117+
for other_user in $user_ids; do
118+
packages="$(ash_checked pm list packages --user "$other_user" "$PKG")" || return 1
119+
printf '%s\n' "$packages" | awk '
120+
/^[[:space:]]*$/ { next }
121+
!/^package:[A-Za-z0-9_.]+$/ { exit 1 }' || return 1
122+
# The package filter is a substring match; only this exact ID blocks removal.
123+
if printf '%s\n' "$packages" | grep -qxF "package:$PKG"; then echo "$other_user"; fi
124+
done
125+
}
106126
key() { # one key at a time so focus changes keep up on slow devices
107127
for k in "$@"; do ash input keyevent "$k" >/dev/null; sleep 0.4; done
108128
}
@@ -196,12 +216,18 @@ if [ "$APK_SOURCE" != "none" ]; then
196216
result="$(a install -r --user "$ANDROID_USER" "$APK" 2>&1 | tr -d '\r')"
197217
if printf '%s' "$result" | grep -q "INSTALL_FAILED_UPDATE_INCOMPATIBLE"; then
198218
if [ "$ALLOW_UNINSTALL" = 1 ]; then
199-
log "Installed app has a different signing key; uninstalling it (--allow-uninstall)"
200-
a uninstall --user "$ANDROID_USER" "$PKG" >/dev/null 2>&1
219+
OTHER_PACKAGE_USERS="$(other_package_users)" || die "cannot verify other users' package installations; refusing --allow-uninstall and preserving this user's app data. Use --no-install or an APK with the installed signing key"
220+
[ -z "$OTHER_PACKAGE_USERS" ] || die "signing conflict: $PKG is installed for another Android user ($OTHER_PACKAGE_USERS). Refusing --allow-uninstall; no app data was removed. Use --no-install or an APK with the installed signing key"
221+
log "Installed app has a different signing key; uninstalling for Android user $ANDROID_USER (--allow-uninstall)"
222+
uninstall_result="$(a uninstall --user "$ANDROID_USER" "$PKG" 2>&1)" || die "uninstall for Android user $ANDROID_USER failed: $uninstall_result"
223+
printf '%s\n' "$uninstall_result" | tr -d '\r' | grep -qxF "Success" || die "uninstall for Android user $ANDROID_USER failed: $uninstall_result"
201224
result="$(a install -r --user "$ANDROID_USER" "$APK" 2>&1 | tr -d '\r')"
225+
if printf '%s' "$result" | grep -q "INSTALL_FAILED_UPDATE_INCOMPATIBLE"; then
226+
die "signing conflict remains after removing this user's installation; Android still retains the incompatible package. No broader uninstall will be attempted. Use an APK with the installed signing key"
227+
fi
202228
APK_SOURCE="$APK_SOURCE (previous install removed: different signing key)"
203229
else
204-
die "installed app is signed with a different key. Re-run with --allow-uninstall (resets app settings) or use --no-install"
230+
die "installed app is signed with a different key. Use --no-install or a matching-key APK; --allow-uninstall resets this user's settings only when no other user has the app"
205231
fi
206232
fi
207233
printf '%s' "$result" | grep -q "Success" || die "install failed: $result"

‎tools/tv_diagnostics_fake_adb.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,23 @@
1717
package = "nl.neerdael.projectmtv"
1818
listener = package + "/com.example.projectm.visualizer.TrackListenerService"
1919
changed = False
20+
install_mode = os.environ.get("DIAGNOSTICS_TEST_INSTALL", "")
2021

2122
if args == ["get-state"]:
2223
print("device")
24+
elif args[:1] == ["install"]:
25+
state["installs"] = state.get("installs", 0) + 1
26+
changed = True
27+
if install_mode and (state["installs"] == 1 or install_mode == "retained-conflict"
28+
or state.get("installed_users", [])):
29+
print("Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: different signing key]")
30+
else:
31+
print("Success")
32+
elif args[:1] == ["uninstall"]:
33+
state["uninstalls"] = state.get("uninstalls", 0) + 1
34+
state["installed_users"] = [user for user in state.get("installed_users", []) if user != 10]
35+
changed = True
36+
print("Success")
2337
elif args[:2] == ["logcat", "-v"]:
2438
print(f"10-05 12:00:00.000 100 100 I ActivityManager: Start proc 202:{package}/u0a123 for service")
2539
print(f"10-05 12:00:00.001 100 100 I ActivityManager: Start proc 309:{package}/u10a123 for activity")
@@ -67,6 +81,26 @@
6781
launch_state = os.environ.get("DIAGNOSTICS_TEST_LAUNCH_STATE", "COLD")
6882
if launch_state:
6983
print("LaunchState: " + launch_state)
84+
elif command == ["pm", "list", "users"]:
85+
if failure == "users-error":
86+
print("permission denied", file=sys.stderr)
87+
sys.exit(1)
88+
if failure == "users-malformed":
89+
print("Error: couldn't get users")
90+
else:
91+
print("Users:\n\tUserInfo{0:Owner:13} running\n\tUserInfo{10:TV user:10} running\n\tUserInfo{11:Stopped:10}")
92+
elif command[:3] == ["pm", "list", "packages"]:
93+
if failure == "packages-error":
94+
print("permission denied", file=sys.stderr)
95+
sys.exit(1)
96+
if failure == "packages-malformed":
97+
print("Error: Invalid user")
98+
else:
99+
user = int(command[command.index("--user") + 1])
100+
if user in state.get("installed_users", []):
101+
print("package:" + package)
102+
# FILTER is a substring match; similarly named packages are not this app.
103+
print("package:" + package + ".tools")
70104
elif command[:1] == ["settings"]:
71105
print(listener if state["listener"] else "null")
72106
elif command[:2] == ["cmd", "notification"]:

0 commit comments

Comments
 (0)