Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

launcher: accept the secure-settings marker only as a returned line

Rasmus Kjær Damgaard3b2f41e102e1
diff --git a/launcher/build-and-install.ps1 b/launcher/build-and-install.ps1
index 6dd519db5..051a58216 100644
--- a/launcher/build-and-install.ps1
+++ b/launcher/build-and-install.ps1
@@ -163,10 +163,11 @@ $secure = 'android.permission.WRITE_SECURE_SETTINGS'
if ($RestoreKeyServices) {
$step = "pm grant com.gathin.tvhome $secure && echo restore-granted"; $mark = 'restore-granted'
} else {
- $step = "pm revoke com.gathin.tvhome $secure; s=`$(dumpsys package com.gathin.tvhome); case `"`$s`" in *`"${secure}: granted=true`"*) ;; *`"$secure`"*) echo secure-settings-revoked ;; esac"
+ $step = "pm revoke com.gathin.tvhome $secure; s=`$(dumpsys package com.gathin.tvhome) && case `"`$s`" in *`"${secure}: granted=true`"*) ;; *`"$secure`"*) echo secure-settings-revoked ;; esac"
$mark = 'secure-settings-revoked'
}
$out = ($step | & $py -I ..\tools\tv.py --batch) -join "`n"
Write-Host $out
-if ($out -notmatch [regex]::Escape($mark)) { throw "WRITE_SECURE_SETTINGS is not in the state this install asked for ($mark missing)" }
+# Only a line that is the marker and nothing else counts: tv.py --batch echoes the step, which contains it too.
+if (($out -split '\r?\n') -notcontains $mark) { throw "WRITE_SECURE_SETTINGS is not in the state this install asked for ($mark missing)" }
Write-Host 'Installed. Press Home on the remote to see it.'
diff --git a/launcher/build-and-install.sh b/launcher/build-and-install.sh
index ba29e618e..4601d149d 100755
--- a/launcher/build-and-install.sh
+++ b/launcher/build-and-install.sh
@@ -233,10 +233,17 @@ SECURE=android.permission.WRITE_SECURE_SETTINGS
if [ "${RESTORE_KEY_SERVICES:-0}" = 1 ]; then
STEP="pm grant com.gathin.tvhome $SECURE && echo restore-granted"; MARK=restore-granted
else
- STEP="pm revoke com.gathin.tvhome $SECURE; s=\$(dumpsys package com.gathin.tvhome); case \"\$s\" in *\"$SECURE: granted=true\"*) ;; *\"$SECURE\"*) echo secure-settings-revoked ;; esac"
+ STEP="pm revoke com.gathin.tvhome $SECURE; s=\$(dumpsys package com.gathin.tvhome) && case \"\$s\" in *\"$SECURE: granted=true\"*) ;; *\"$SECURE\"*) echo secure-settings-revoked ;; esac"
MARK=secure-settings-revoked
fi
OUT=$("$PY" -I ../tools/tv.py "$STEP")
echo "$OUT"
-case "$OUT" in *"$MARK"*) ;; *) echo "ERROR: WRITE_SECURE_SETTINGS is not in the state this install asked for ($MARK missing)" >&2; exit 1 ;; esac
+# Only a line that is the marker and nothing else counts: the step's own text contains it too.
+ACK_FOUND=0
+while IFS= read -r line; do
+ if [ "${line%$'\r'}" = "$MARK" ]; then ACK_FOUND=1; break; fi
+done <<< "$OUT"
+if [ "$ACK_FOUND" != 1 ]; then
+ echo "ERROR: WRITE_SECURE_SETTINGS is not in the state this install asked for ($MARK missing)" >&2; exit 1
+fi
echo "Installed. Press Home on the remote to see it."
diff --git a/tests/test_launcher_min_sdk.py b/tests/test_launcher_min_sdk.py
index fb4b0785d..efac9d7a5 100644
--- a/tests/test_launcher_min_sdk.py
+++ b/tests/test_launcher_min_sdk.py
@@ -78,7 +78,14 @@ case "$1" in
esac
exit 0
"""
+# A readback that fails part way has printed the requested-permissions list, which names the
+# permission without its state.
DUMPSYS = """#!/bin/sh
+if [ "$(cat "$FAKE_SECURE.readback")" = fail ]; then
+ echo " requested permissions:"
+ echo " android.permission.WRITE_SECURE_SETTINGS"
+ exit 1
+fi
g=false; [ "$(cat "$FAKE_SECURE")" = granted ] && g=true
echo " android.permission.WRITE_SECURE_SETTINGS: granted=$g"
"""
@@ -97,6 +104,8 @@ def secure_step(command):
f.write(state["secure"] + "\n")
with open(secure + ".works", "w") as f:
f.write("1\n" if state["revoke_works"] else "0\n")
+ with open(secure + ".readback", "w") as f:
+ f.write("fail\n" if state["readback_fails"] else "ok\n")
env = dict(os.environ, PATH=shims + ":" + os.environ["PATH"], FAKE_SECURE=secure)
out = subprocess.run(["sh", "-c", command], env=env, capture_output=True, text=True).stdout
with open(secure) as f:
@@ -118,6 +127,9 @@ def main():
commands = []
for command in commands:
state["commands"].append(command)
+ if "--batch" in args:
+ # As tools/tv.py does: a batch echoes each command before its output.
+ sys.stdout.write(f"$ {command}\n")
sys.stdout.write(run(command))
sys.stdout.flush()
save()
@@ -164,6 +176,7 @@ class MinSdkGuardTest(unittest.TestCase):
"install_output": "Success\n",
"secure": "denied",
"revoke_works": True,
+ "readback_fails": False,
"commands": [],
}
state.update(overrides)
@@ -210,6 +223,12 @@ class MinSdkGuardTest(unittest.TestCase):
self.assertIn("secure-settings-revoked missing", result.stderr)
self.assertEqual(state["secure"], "granted")
+ def test_a_failed_readback_stops_the_install(self):
+ result, state = self.install(secure="granted", revoke_works=False, readback_fails=True)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("secure-settings-revoked missing", result.stderr)
+ self.assertEqual(state["secure"], "granted")
+
def test_a_granted_tv_is_revoked(self):
result, state = self.install(secure="granted")
self.assertEqual(result.returncode, 0, result.stderr)
diff --git a/tests/test_launcher_secure_ack.py b/tests/test_launcher_secure_ack.py
new file mode 100644
index 000000000..f7a4a02f4
--- /dev/null
+++ b/tests/test_launcher_secure_ack.py
@@ -0,0 +1,85 @@
+"""The launcher installers accept the WRITE_SECURE_SETTINGS marker only as a line the TV sent back.
+
+tools/tv.py does not hand back the TV shell's exit status, so build-and-install.sh and .ps1 decide by
+the marker. `tv.py --batch` echoes each command as `$ <command>`, and the command itself contains
+`echo <marker>`, so a check that finds the marker anywhere in the output passes on the echo alone, with
+a grant that failed or a revoke the TV ignored. Both acknowledgement checks are run here, taken from
+the scripts as written, against client output that holds the echo, a prefix, a suffix or CRLF.
+
+Run from the repository root: python3 -m unittest discover -s tests -v
+The PowerShell cases need `pwsh` on PATH and skip without it; CI's Ubuntu runner has it.
+"""
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+SH = ROOT / "launcher" / "build-and-install.sh"
+PS1 = ROOT / "launcher" / "build-and-install.ps1"
+PWSH = shutil.which("pwsh")
+REVOKE = "secure-settings-revoked"
+GRANT = "restore-granted"
+
+# (output from tv.py, marker, accepted)
+CASES = [
+ (f"{REVOKE}\n", REVOKE, True),
+ (f"{REVOKE}\r\n", REVOKE, True),
+ (f"Success\n{GRANT}\n", GRANT, True),
+ (f"$ pm revoke x; s=$(dumpsys package x) && case \"$s\" in *) echo {REVOKE} ;; esac\n", REVOKE, False),
+ (f"$ pm grant x && echo {GRANT}\nException occurred while executing 'grant'\n", GRANT, False),
+ (f"not-{REVOKE}\n", REVOKE, False),
+ (f"{REVOKE}-later\n", REVOKE, False),
+ (f"{GRANT}\n", REVOKE, False),
+ ("", GRANT, False),
+]
+
+
+def bash_check():
+ """The lines of build-and-install.sh from ACK_FOUND=0 to the fi that closes the error branch."""
+ lines = SH.read_text(encoding="utf-8").splitlines()
+ start = lines.index("ACK_FOUND=0")
+ end = next(i for i in range(start, len(lines)) if lines[i] == "fi")
+ return "\n".join(lines[start:end + 1])
+
+
+def ps_check():
+ """The line of build-and-install.ps1 that throws when the marker is missing."""
+ return next(line for line in PS1.read_text(encoding="utf-8").splitlines()
+ if "$mark missing" in line and line.lstrip().startswith("if"))
+
+
+class SecureAckTest(unittest.TestCase):
+ def test_bash_accepts_only_a_whole_returned_line(self):
+ if not shutil.which("bash"):
+ raise unittest.SkipTest("needs bash")
+ check = bash_check()
+ for out, mark, accepted in CASES:
+ with self.subTest(out=out, mark=mark):
+ result = subprocess.run(
+ ["bash", "-c", f'OUT="$1"; MARK="$2"\n{check}\necho accepted', "ack", out, mark],
+ capture_output=True, text=True, timeout=30,
+ )
+ self.assertEqual(result.returncode == 0 and "accepted" in result.stdout, accepted,
+ result.stderr)
+
+ def test_powershell_accepts_only_a_whole_returned_line(self):
+ if not PWSH:
+ raise unittest.SkipTest("build-and-install.ps1 needs pwsh on PATH")
+ check = ps_check()
+ for out, mark, accepted in CASES:
+ with self.subTest(out=out, mark=mark):
+ script = ("$out = [Environment]::GetEnvironmentVariable('ACK_OUT'); "
+ "$mark = [Environment]::GetEnvironmentVariable('ACK_MARK')\n"
+ f"{check}\nWrite-Output accepted")
+ env = dict(os.environ, ACK_OUT=out, ACK_MARK=mark)
+ result = subprocess.run([PWSH, "-NoProfile", "-Command", script],
+ capture_output=True, text=True, timeout=60, env=env)
+ self.assertEqual(result.returncode == 0 and "accepted" in result.stdout, accepted,
+ result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()