mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-26 07:27:18 +01:00
Compare commits
2 Commits
6bf7343c0f
...
db1d8f8247
| Author | SHA1 | Date | |
|---|---|---|---|
| db1d8f8247 | |||
| b1de6f8d38 |
@ -0,0 +1,52 @@
|
||||
{
|
||||
"intent": "Exempt YouTube, YouTube Music and Chrome from the geofence so they stay hidden everywhere, and make pl.infakt.infakt unhideable under every condition rather than merely allowlisted.",
|
||||
"scope": [
|
||||
"python_pkg/focus_policy/export.py",
|
||||
"python_pkg/focus_policy/tests/test_export.py",
|
||||
"focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/FocusPolicy.kt",
|
||||
"focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/EnforcementDecision.kt",
|
||||
"focus_owner/android/app/src/test/kotlin/com/kuhy/focus_owner/EnforcementDecisionTest.kt",
|
||||
"phone_focus_mode/config.sh",
|
||||
"focus_owner/assets/policy.json",
|
||||
"Non-goal: network-level YouTube blocking, which the app cannot currently do at all"
|
||||
],
|
||||
"changes": [
|
||||
"New always_blocked_packages field. The AWAY branch previously returned early with packagesToShow = everything, so leaving home restored YouTube -- the geofence was an off switch, which is what device owner exists to remove.",
|
||||
"The exemption is applied in all four branches: AWAY hides them, the allowlist loop cannot show them, and the workout release skips them (otherwise 'go for a run' becomes the off switch).",
|
||||
"com.android.vending deliberately NOT always-blocked: Play stays geofenced so apps can be installed away from home, and a hidden package cannot be reinstalled from Play anyway.",
|
||||
"pl.infakt.infakt moved into SYSTEM_NEVER_DISABLE. Allowlisting depended on it staying in BOTH the day and night lists; isAllowed() checks the never-disable list first, before the curfew split, so it now holds unconditionally.",
|
||||
"Exporter raises if an always-blocked package is not also blockable: the runner filters unopted system packages out of installedPackages, so such an entry would silently never be hidden."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "pytest python_pkg/focus_policy/ --cov",
|
||||
"result": "pass",
|
||||
"evidence": "128 tests, 100% branch coverage on every focus_policy module (export/loader/model/blocklist/__main__)."
|
||||
},
|
||||
{
|
||||
"command": "gradlew :app:testDebugUnitTest with a deliberately wrong assertion (canary)",
|
||||
"result": "pass",
|
||||
"evidence": "'16 tests completed, 1 failed' with AssertionError at the always-blocked case, proving the new tests actually execute rather than being skipped. Restored, then 16/16 pass. The pre-existing 'away from home hides nothing' test was updated rather than left passing, since it documented the hole being closed."
|
||||
},
|
||||
{
|
||||
"command": "adb install -r over the device owner; run enforcement pass",
|
||||
"result": "pass",
|
||||
"evidence": "Success, Device Owner Type: 0 preserved. 'applied LOCATION_UNKNOWN: hid 0, restored 0' -- correctly a no-op, the packages were already hidden by the earlier pass."
|
||||
},
|
||||
{
|
||||
"command": "dumpsys on the always-blocked set and on infakt",
|
||||
"result": "pass",
|
||||
"evidence": "youtube, youtube.music, chrome, vending all hidden=true. pl.infakt.infakt hidden=false. adb uninstall still returns DELETE_FAILED_DEVICE_POLICY_MANAGER."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The AWAY exemption could NOT be verified on device: with no home_location.json every pass decides LOCATION_UNKNOWN, so the AWAY branch is unreachable on this phone today. It is covered by unit tests (canary-verified) but not by a real geofence transition. That verification has to wait for the in-app coordinate writer.",
|
||||
"Because of the same missing coordinates, the user's 'other apps are fine' half is NOT yet delivered: everything is still hidden everywhere, not only the always-blocked set. The in-app 'set home to current location' action is now on the critical path for that.",
|
||||
"isEnforcing is derived from packagesToHide.isNotEmpty(), so the always-blocked set keeps it true under AWAY and the uninstall block stays on. This is relied upon rather than stated as a separate flag; a future change making AWAY report not-enforcing would silently make `adb uninstall` reachable away from home. A test pins it.",
|
||||
"The user's most important request -- blocking all YouTube hosts/URLs at the network level -- is NOT implemented. focus_owner does no network blocking of any kind. RethinkDNS is installed but at first-run state after the wipe (its 8 wildcard rules are gone) and is itself currently hidden by enforcement."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert; regenerate the asset; rebuild; install in place. The extra asset fields are ignored by an older build (optionalStringSet reads a missing key as empty).",
|
||||
"To unblock one of the always-blocked apps without a revert: remove it from ALWAYS_BLOCKED_PACKAGES, regenerate, rebuild, install, run a pass."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,55 @@
|
||||
{
|
||||
"intent": "Add the network-level layer: pin RethinkDNS as the device owner's always-on VPN so YouTube is blocked by host, in every app, not only by hiding the YouTube package.",
|
||||
"scope": [
|
||||
"python_pkg/focus_policy/export.py",
|
||||
"python_pkg/focus_policy/tests/test_export.py",
|
||||
"focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/DevicePolicyBridge.kt",
|
||||
"focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/EnforcementRunner.kt",
|
||||
"focus_owner/android/app/src/main/kotlin/com/kuhy/focus_owner/MainActivity.kt",
|
||||
"phone_focus_mode/config.sh",
|
||||
"focus_owner/assets/policy.json",
|
||||
"Non-goal: DISALLOW_CONFIG_VPN, deliberately deferred until the filter is confirmed working",
|
||||
"Non-goal: the domain rules themselves, which cannot be scripted"
|
||||
],
|
||||
"changes": [
|
||||
"DevicePolicyBridge.setAlwaysOnVpn uses DevicePolicyManager.setAlwaysOnVpnPackage. This is not the mechanism that failed on 2026-08-09: that was `settings put secure always_on_vpn_app`, which writes, survives a reboot, and is ignored by VpnManager. The DPM call from a device owner actually takes effect.",
|
||||
"lockdownEnabled=false deliberately. Lockdown drops all traffic when the tunnel is down, and the wipe checklist names lockdown plus the DISALLOW_* restrictions as the combination most likely to produce an unrecoverable device.",
|
||||
"releaseDeviceOwner now also clears DISALLOW_CONFIG_VPN and unpins the VPN before clearDeviceOwnerApp, for the same reason it already unblocked uninstall: these are device-owner powers, so clearing ownership first would strand them with nothing privileged left to lift them.",
|
||||
"The pin is re-asserted every pass from EnforcementRunner.apply, unconditionally rather than tracking decision.isEnforcing -- the network filter must not lift when the geofence says AWAY.",
|
||||
"always_on_vpn_package is emitted by the exporter only when the provider is also in never_disable_prefixes, and com.celzero.bravedns was added there. Pinning a package the sweep can hide is the worst case: the restriction would point at a hidden app and cost general connectivity, not just the filter."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "pytest python_pkg/focus_policy/ --cov",
|
||||
"result": "pass",
|
||||
"evidence": "129 tests, 100% branch coverage retained on every module. The new test asserts the field is empty when the provider is unprotected and set when it is."
|
||||
},
|
||||
{
|
||||
"command": "dumpsys package com.celzero.bravedns | grep BIND_VPN_SERVICE",
|
||||
"result": "pass",
|
||||
"evidence": "com.celzero.bravedns/.service.BraveVPNService declares BIND_VPN_SERVICE, so it is a valid always-on target rather than a package that would silently no-op."
|
||||
},
|
||||
{
|
||||
"command": "run an enforcement pass, then dumpsys device_policy",
|
||||
"result": "pass",
|
||||
"evidence": "logcat 'FocusOwner: alwaysOnVpn -> com.celzero.bravedns'; dumpsys reports mAlwaysOnVpnPackage=com.celzero.bravedns, mAlwaysOnVpnLockdown=false. RethinkDNS was also unhidden by the same pass, confirming the never-disable entry works."
|
||||
},
|
||||
{
|
||||
"command": "ip addr show tun0 ; pidof com.celzero.bravedns",
|
||||
"result": "partial",
|
||||
"evidence": "The app is running (pid 8871) and the pin is registered, but there is NO tun0 interface -- the tunnel has not come up. Android requires a one-time in-app VPN consent tap that cannot be granted over adb. The pin is armed but the filter is not yet carrying traffic."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"THE NETWORK BLOCK IS NOT YET ACTIVE. The pin is set but the tunnel is down pending the VPN consent tap, and RethinkDNS is at first-run state: the 8 wildcard YouTube rules died with the wipe. They live in app-private storage, so phone_backup.sh never captured them and adb cannot restore them -- they must be re-entered by hand.",
|
||||
"Pinning RethinkDNS consumes Android's single VPN slot, so com.zaneschepke.wireguardautotunnel cannot run, and dns.kuhy.duckdns.org (bound to 10.8.0.1, WireGuard-only) is unreachable. The user chose this trade explicitly.",
|
||||
"DISALLOW_CONFIG_VPN is NOT applied yet, so the user can still turn the VPN off from Settings. Applying it before the filter is confirmed working would lock in a non-functional configuration.",
|
||||
"Whether DISALLOW_CONFIG_VPN also locks RethinkDNS's own in-app rule editor is untested. If it does, every domain rule must be final before the restriction is applied.",
|
||||
"The always-on pin has not been reboot-tested."
|
||||
],
|
||||
"rollback": [
|
||||
"In-app 'Release device owner' unpins the VPN and clears the restriction before releasing, all in one action.",
|
||||
"To unpin without releasing: remove com.celzero.bravedns from SYSTEM_NEVER_DISABLE, regenerate the asset (the exporter then emits an empty always_on_vpn_package), rebuild, install, run a pass.",
|
||||
"adb shell dpm set-always-on-vpn is not a rollback path; the DPM state is owned by the app."
|
||||
]
|
||||
}
|
||||
@ -98,6 +98,66 @@ class DevicePolicyBridge(private val context: Context) {
|
||||
.getOrDefault(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pins [vpnPackage] as the always-on VPN, the network-level block.
|
||||
*
|
||||
* This is the DPM call, not `settings put secure always_on_vpn_app` --
|
||||
* that one writes successfully, survives a reboot, and does nothing,
|
||||
* because VpnManager ignores adb-written values. Measured on this device.
|
||||
*
|
||||
* `lockdownEnabled` is false deliberately. Lockdown drops all traffic
|
||||
* whenever the tunnel is down, and the wipe checklist names it, together
|
||||
* with the DISALLOW_* restrictions, as the combination most likely to
|
||||
* leave an unrecoverable device. The filter being bypassable during a
|
||||
* VPN outage is the lesser problem.
|
||||
*
|
||||
* @return null on success, or a message describing why it failed.
|
||||
*/
|
||||
fun setAlwaysOnVpn(vpnPackage: String): String? {
|
||||
if (!isDeviceOwner()) return "not device owner"
|
||||
return runCatching {
|
||||
dpm.setAlwaysOnVpnPackage(admin, vpnPackage, false)
|
||||
val active = dpm.getAlwaysOnVpnPackage(admin)
|
||||
Log.i(FocusDeviceAdminReceiver.TAG, "alwaysOnVpn -> $active")
|
||||
if (active == vpnPackage) null else "pinned $active, expected $vpnPackage"
|
||||
}.getOrElse { error ->
|
||||
// UnsupportedOperationException is the documented signal that the
|
||||
// package does not declare a VPN service, or does not opt in to
|
||||
// always-on. Report it rather than leaving a silent no-op.
|
||||
Log.e(FocusDeviceAdminReceiver.TAG, "setAlwaysOnVpnPackage failed", error)
|
||||
error.message ?: error::class.java.simpleName
|
||||
}
|
||||
}
|
||||
|
||||
/** The package currently pinned as always-on VPN, or null. */
|
||||
fun alwaysOnVpnPackage(): String? {
|
||||
if (!isDeviceOwner()) return null
|
||||
return runCatching { dpm.getAlwaysOnVpnPackage(admin) }.getOrNull()
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevents the user from changing VPN configuration.
|
||||
*
|
||||
* Applied separately from [setAlwaysOnVpn] and only after it is confirmed
|
||||
* working: pinning the restriction first would make a failed VPN setup
|
||||
* harder to repair from the device.
|
||||
*/
|
||||
fun setVpnConfigBlocked(blocked: Boolean): Boolean {
|
||||
if (!isDeviceOwner()) return false
|
||||
return runCatching {
|
||||
if (blocked) {
|
||||
dpm.addUserRestriction(admin, android.os.UserManager.DISALLOW_CONFIG_VPN)
|
||||
} else {
|
||||
dpm.clearUserRestriction(admin, android.os.UserManager.DISALLOW_CONFIG_VPN)
|
||||
}
|
||||
Log.i(FocusDeviceAdminReceiver.TAG, "DISALLOW_CONFIG_VPN=$blocked")
|
||||
true
|
||||
}.getOrElse { error ->
|
||||
Log.e(FocusDeviceAdminReceiver.TAG, "DISALLOW_CONFIG_VPN failed", error)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes provisioning state for the UI, so the escape hatch can be found
|
||||
* without a PC attached.
|
||||
@ -109,6 +169,7 @@ class DevicePolicyBridge(private val context: Context) {
|
||||
"sdkInt" to Build.VERSION.SDK_INT,
|
||||
"restrictionsApplied" to false,
|
||||
"uninstallBlocked" to isSelfUninstallBlocked(),
|
||||
"alwaysOnVpn" to (alwaysOnVpnPackage() ?: ""),
|
||||
)
|
||||
|
||||
/**
|
||||
@ -131,11 +192,17 @@ class DevicePolicyBridge(private val context: Context) {
|
||||
return true
|
||||
}
|
||||
return runCatching {
|
||||
// Order matters and is not interchangeable: uninstall blocking is a
|
||||
// device-owner power, so clearing ownership first would leave the
|
||||
// block in place with nothing privileged left to lift it — an app
|
||||
// that owns nothing and cannot be removed. Unblock, then release.
|
||||
// Order matters and is not interchangeable: every one of these is a
|
||||
// device-owner power, so clearing ownership first would leave them
|
||||
// in place with nothing privileged left to lift them — an app that
|
||||
// owns nothing and cannot be removed, and a pinned VPN nobody can
|
||||
// reconfigure. Undo the restrictions, then release.
|
||||
setSelfUninstallBlocked(false)
|
||||
setVpnConfigBlocked(false)
|
||||
runCatching { dpm.setAlwaysOnVpnPackage(admin, null, false) }
|
||||
.onFailure {
|
||||
Log.w(FocusDeviceAdminReceiver.TAG, "could not unpin VPN", it)
|
||||
}
|
||||
dpm.clearDeviceOwnerApp(context.packageName)
|
||||
val released = !isDeviceOwner()
|
||||
Log.i(FocusDeviceAdminReceiver.TAG, "clearDeviceOwnerApp -> released=$released")
|
||||
|
||||
@ -36,6 +36,16 @@ data class EnforcementDecision(
|
||||
val packagesToHide: Set<String>,
|
||||
val packagesToShow: Set<String>,
|
||||
) {
|
||||
/**
|
||||
* Whether this pass leaves anything hidden.
|
||||
*
|
||||
* Derived rather than stored, which matters for the always-blocked set:
|
||||
* AWAY still hides those, so it still counts as enforcing, and the
|
||||
* uninstall block keyed off this stays on away from home. Were this tied
|
||||
* to the reason instead, leaving the house would lift the block while
|
||||
* YouTube stayed hidden -- making `adb uninstall` the off switch for the
|
||||
* one thing that is meant not to have one.
|
||||
*/
|
||||
val isEnforcing: Boolean get() = packagesToHide.isNotEmpty()
|
||||
|
||||
companion object {
|
||||
@ -59,11 +69,19 @@ data class EnforcementDecision(
|
||||
val hasFix = lat != null && lon != null
|
||||
val atHome = hasFix && isInside(policy, lat, lon, inputs.currentlyEnforcing)
|
||||
|
||||
// Exempt from every branch below, including AWAY and WORKOUT.
|
||||
// Restricted to packages actually present, so the sets stay a
|
||||
// description of this device rather than of the policy.
|
||||
val alwaysBlocked = inputs.installedPackages
|
||||
.intersect(policy.alwaysBlockedPackages)
|
||||
.filterNot { policy.isProtected(it) }
|
||||
.toSet()
|
||||
|
||||
if (hasFix && !atHome) {
|
||||
return EnforcementDecision(
|
||||
reason = EnforcementReason.AWAY,
|
||||
packagesToHide = emptySet(),
|
||||
packagesToShow = inputs.installedPackages,
|
||||
packagesToHide = alwaysBlocked,
|
||||
packagesToShow = inputs.installedPackages - alwaysBlocked,
|
||||
)
|
||||
}
|
||||
|
||||
@ -77,11 +95,20 @@ data class EnforcementDecision(
|
||||
val hide = mutableSetOf<String>()
|
||||
val show = mutableSetOf<String>()
|
||||
for (pkg in inputs.installedPackages) {
|
||||
if (policy.isAllowed(pkg, duringCurfew)) show.add(pkg) else hide.add(pkg)
|
||||
if (pkg in alwaysBlocked) {
|
||||
hide.add(pkg)
|
||||
} else if (policy.isAllowed(pkg, duringCurfew)) {
|
||||
show.add(pkg)
|
||||
} else {
|
||||
hide.add(pkg)
|
||||
}
|
||||
}
|
||||
|
||||
if (inputs.workoutActive) {
|
||||
for (pkg in policy.workoutExemptPackages) {
|
||||
// A workout exemption must not become a way to reach the
|
||||
// always-blocked set, or "go for a run" is the off switch.
|
||||
if (pkg in alwaysBlocked) continue
|
||||
if (hide.remove(pkg)) show.add(pkg)
|
||||
}
|
||||
return EnforcementDecision(EnforcementReason.WORKOUT, hide, show)
|
||||
|
||||
@ -67,6 +67,23 @@ class EnforcementRunner(private val context: Context) {
|
||||
* that restores access rather than the half that removes it.
|
||||
*/
|
||||
fun apply(decision: EnforcementDecision, bridge: DevicePolicyBridge) {
|
||||
// Re-read rather than threaded through from decide(): an unreadable
|
||||
// policy must not stop a pass that is otherwise ready to apply, and
|
||||
// the VPN pin is the one step that should survive a policy problem.
|
||||
val policy = runCatching { FocusPolicy.load(context) }.getOrNull()
|
||||
|
||||
// Re-pinned every pass, unconditionally rather than tracking the
|
||||
// decision: the network filter is the layer that reaches youtube.com
|
||||
// in Firefox, in a webview, and in clients nobody has enumerated, so
|
||||
// it must not lift when the geofence says AWAY. DISALLOW_CONFIG_VPN is
|
||||
// deliberately NOT applied here -- it is a separate, later step, so a
|
||||
// misconfigured VPN stays repairable from the device.
|
||||
policy?.alwaysOnVpnPackage?.let { vpn ->
|
||||
bridge.setAlwaysOnVpn(vpn)?.let { failure ->
|
||||
Log.w(FocusDeviceAdminReceiver.TAG, "always-on VPN not pinned: $failure")
|
||||
}
|
||||
}
|
||||
|
||||
// Re-asserted every pass rather than set once at provisioning time, so
|
||||
// the protection self-heals: `adb uninstall` while enforcing is the one
|
||||
// route that strands device ownership with no holder, and a factory
|
||||
|
||||
@ -72,6 +72,22 @@ data class FocusPolicy(
|
||||
* behaviour.
|
||||
*/
|
||||
val blockableSystemPackages: Set<String> = emptySet(),
|
||||
/**
|
||||
* Packages hidden everywhere, exempt from the geofence.
|
||||
*
|
||||
* The geofence makes leaving home an off switch, which is what device
|
||||
* owner exists to remove. These stay hidden under AWAY, CURFEW, AT_HOME
|
||||
* and WORKOUT alike; [EnforcementDecision] never places them in
|
||||
* `packagesToShow`.
|
||||
*/
|
||||
val alwaysBlockedPackages: Set<String> = emptySet(),
|
||||
/**
|
||||
* Package pinned as the always-on VPN, or null when none is configured.
|
||||
*
|
||||
* The exporter emits this only when the package is also protected from
|
||||
* the sweep, so the enforcer can never hide the app it has pinned.
|
||||
*/
|
||||
val alwaysOnVpnPackage: String? = null,
|
||||
) {
|
||||
/**
|
||||
* Whether a package must never be hidden.
|
||||
@ -155,6 +171,11 @@ data class FocusPolicy(
|
||||
neverDisablePrefixes = json.stringSet("never_disable_prefixes"),
|
||||
workoutUnblockDomains = json.stringSet("workout_unblock_domains"),
|
||||
blockableSystemPackages = json.optionalStringSet("blockable_system_packages"),
|
||||
alwaysBlockedPackages = json.optionalStringSet("always_blocked_packages"),
|
||||
// Empty string means "not configured", which is what the
|
||||
// exporter writes when the provider is not sweep-protected.
|
||||
alwaysOnVpnPackage = json.optString("always_on_vpn_package")
|
||||
.takeIf { it.isNotEmpty() },
|
||||
curfew = curfewJson?.let {
|
||||
CurfewWindow(
|
||||
startMinutes = parseHhMm(it.getString("start"), "curfew.start"),
|
||||
|
||||
@ -14,6 +14,24 @@ class MainActivity : FlutterActivity() {
|
||||
when (call.method) {
|
||||
"status" -> result.success(bridge.status())
|
||||
"releaseDeviceOwner" -> result.success(bridge.releaseDeviceOwner())
|
||||
"setAlwaysOnVpn" -> {
|
||||
val pkg = call.argument<String>("package")
|
||||
if (pkg == null) {
|
||||
result.error("bad_args", "package required", null)
|
||||
} else {
|
||||
// Returns the failure message, or null on success,
|
||||
// so the UI can say why rather than just "failed".
|
||||
result.success(bridge.setAlwaysOnVpn(pkg))
|
||||
}
|
||||
}
|
||||
"setVpnConfigBlocked" -> {
|
||||
val blocked = call.argument<Boolean>("blocked")
|
||||
if (blocked == null) {
|
||||
result.error("bad_args", "blocked required", null)
|
||||
} else {
|
||||
result.success(bridge.setVpnConfigBlocked(blocked))
|
||||
}
|
||||
}
|
||||
"setSelfUninstallBlocked" -> {
|
||||
val blocked = call.argument<Boolean>("blocked")
|
||||
if (blocked == null) {
|
||||
|
||||
@ -42,6 +42,34 @@ class EnforcementDecisionTest {
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
/**
|
||||
* A policy that names YouTube as always-blocked and drops it from the
|
||||
* allowlist, since the exporter guarantees those two never overlap.
|
||||
*/
|
||||
private fun policyWithAlwaysBlocked() =
|
||||
FocusPolicy.parse(
|
||||
"""
|
||||
{
|
||||
"schema_version": 1,
|
||||
"home": {
|
||||
"latitude": $homeLat,
|
||||
"longitude": $homeLon,
|
||||
"radius_m": 150.0,
|
||||
"hysteresis_m": 30.0
|
||||
},
|
||||
"curfew": {"start":"23:00","end":"05:00"},
|
||||
"launcher_package": "com.launcher",
|
||||
"allowed_packages": ["com.launcher","pl.mbank","com.discord"],
|
||||
"night_allowed_packages": ["com.launcher","pl.mbank"],
|
||||
"never_disable_prefixes": ["com.android.settings"],
|
||||
"workout_unblock_domains": ["youtube.com"],
|
||||
"browser_packages": [],
|
||||
"blockable_system_packages": ["com.google.android.youtube"],
|
||||
"always_blocked_packages": ["com.google.android.youtube"]
|
||||
}
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
private val installed = setOf(
|
||||
"com.launcher",
|
||||
"pl.mbank",
|
||||
@ -54,16 +82,59 @@ class EnforcementDecisionTest {
|
||||
private fun latOffset(metres: Double) = homeLat + metres / metresPerDegreeLat
|
||||
|
||||
@Test
|
||||
fun `away from home hides nothing and shows everything`() {
|
||||
fun `away from home restores everything except the always-blocked set`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(5000.0), homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.AWAY, decision.reason)
|
||||
// The base policy names nothing as always-blocked, so this is the
|
||||
// original behaviour: leaving home restores the whole device.
|
||||
assertTrue(decision.packagesToHide.isEmpty())
|
||||
assertEquals(installed, decision.packagesToShow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `always-blocked packages stay hidden away from home`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policyWithAlwaysBlocked(),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(5000.0), homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.AWAY, decision.reason)
|
||||
assertEquals(setOf("com.google.android.youtube"), decision.packagesToHide)
|
||||
assertFalse(decision.packagesToShow.contains("com.google.android.youtube"))
|
||||
// Everything else still comes back, which is the point of the geofence.
|
||||
assertTrue(decision.packagesToShow.contains("com.discord"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `always-blocked still counts as enforcing away from home`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policyWithAlwaysBlocked(),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(5000.0), homeLon),
|
||||
)
|
||||
// The uninstall block is keyed off isEnforcing. If AWAY reported false
|
||||
// here, leaving the house would make `adb uninstall` an off switch for
|
||||
// the one set that is meant not to have one.
|
||||
assertTrue(decision.isEnforcing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a workout does not release an always-blocked package`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policyWithAlwaysBlocked(),
|
||||
EnforcementInputs(
|
||||
installed,
|
||||
12 * 60,
|
||||
homeLat,
|
||||
homeLon,
|
||||
workoutActive = true,
|
||||
),
|
||||
)
|
||||
assertEquals(EnforcementReason.WORKOUT, decision.reason)
|
||||
assertTrue(decision.packagesToHide.contains("com.google.android.youtube"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `at home only non-allowlisted apps are hidden`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
|
||||
@ -88,6 +88,12 @@
|
||||
"pl.plksa.portalpasazera",
|
||||
"ws.xsoh.etar"
|
||||
],
|
||||
"always_blocked_packages": [
|
||||
"com.android.chrome",
|
||||
"com.google.android.apps.youtube.music",
|
||||
"com.google.android.youtube"
|
||||
],
|
||||
"always_on_vpn_package": "com.celzero.bravedns",
|
||||
"blockable_system_packages": [
|
||||
"com.android.chrome",
|
||||
"com.android.vending",
|
||||
@ -140,6 +146,7 @@
|
||||
"com.android.systemui",
|
||||
"com.android.vpndialogs",
|
||||
"com.android.wifi",
|
||||
"com.celzero.bravedns",
|
||||
"com.google.android.apps.messaging",
|
||||
"com.google.android.contacts",
|
||||
"com.google.android.deskclock",
|
||||
@ -154,7 +161,8 @@
|
||||
"com.google.android.trichromelibrary",
|
||||
"com.google.android.webview",
|
||||
"com.mediatek",
|
||||
"com.qualcomm"
|
||||
"com.qualcomm",
|
||||
"pl.infakt.infakt"
|
||||
],
|
||||
"night_allowed_packages": [
|
||||
"com.azure.authenticator",
|
||||
|
||||
@ -605,7 +605,20 @@ export BLOCKED_SYSTEM_APPS="
|
||||
# --- System / essential packages that must NEVER be disabled ---
|
||||
# These are matched as prefixes (startswith).
|
||||
# You generally don't need to edit this list.
|
||||
#
|
||||
# pl.infakt.infakt is the one non-system entry. Allowlisting it is weaker:
|
||||
# that depends on it staying in BOTH the day and night lists, and dropping it
|
||||
# from either would silently make it hideable. It is device-paired to a bank
|
||||
# over SMS, so losing access to it strands the same re-authentication chain a
|
||||
# hidden Messages app would. isAllowed() checks this list first, before the
|
||||
# curfew split, so it holds under every condition.
|
||||
export SYSTEM_NEVER_DISABLE="
|
||||
pl.infakt.infakt
|
||||
# The always-on VPN provider. Hiding it is self-defeating in the worst way:
|
||||
# it is the network-level YouTube block, and with DISALLOW_CONFIG_VPN pinned
|
||||
# to a hidden package the device can lose general connectivity rather than
|
||||
# just the filter. Must outrank every enforcement branch.
|
||||
com.celzero.bravedns
|
||||
com.android.launcher
|
||||
com.android.launcher3
|
||||
com.android.settings
|
||||
|
||||
@ -51,6 +51,47 @@ BLOCKABLE_SYSTEM_PACKAGES = frozenset(
|
||||
},
|
||||
)
|
||||
|
||||
# Packages hidden everywhere, regardless of location, curfew or workout.
|
||||
#
|
||||
# The geofence exists so the phone becomes usable again away from home, but
|
||||
# that makes leaving the house an off switch -- which is the specific thing
|
||||
# Device Owner was provisioned to remove. These are exempt from it: the
|
||||
# decision layer never puts them in packagesToShow, so the AWAY branch cannot
|
||||
# restore them.
|
||||
#
|
||||
# Chrome is here because it is a second route to the same content, not because
|
||||
# browsing is banned -- Firefox stays available and carries the uBlock filters.
|
||||
# com.android.vending is deliberately NOT here: Play stays geofenced so apps
|
||||
# can still be installed and updated away from home, and a hidden package
|
||||
# cannot be reinstalled from Play anyway.
|
||||
ALWAYS_BLOCKED_PACKAGES = frozenset(
|
||||
{
|
||||
"com.android.chrome",
|
||||
"com.google.android.apps.youtube.music",
|
||||
"com.google.android.youtube",
|
||||
},
|
||||
)
|
||||
|
||||
# Every always-blocked package here is preinstalled, so it only ever reaches
|
||||
# the sweep by also being opted in above. Listing one without the other would
|
||||
# not error -- it would silently never be hidden, because the runner filters it
|
||||
# out of installedPackages before the decision layer sees it.
|
||||
# The always-on VPN provider, pinned by the device owner on every pass.
|
||||
#
|
||||
# This is the network-level block: package hiding stops the YouTube app, but
|
||||
# only a VPN reaches youtube.com in Firefox, in a webview, or in any client
|
||||
# that has not been thought of. Named here rather than hardcoded in Kotlin so
|
||||
# the asset stays the single description of the policy.
|
||||
ALWAYS_ON_VPN_PACKAGE = "com.celzero.bravedns"
|
||||
|
||||
_UNSWEEPABLE = ALWAYS_BLOCKED_PACKAGES - BLOCKABLE_SYSTEM_PACKAGES
|
||||
if _UNSWEEPABLE: # pragma: no cover - guards a constant, not a code path
|
||||
msg = (
|
||||
"always-blocked system packages must also be blockable, or the sweep "
|
||||
f"never sees them: {sorted(_UNSWEEPABLE)}"
|
||||
)
|
||||
raise ValueError(msg)
|
||||
|
||||
|
||||
def policy_to_dict(policy: FocusPolicy) -> dict[str, Any]:
|
||||
"""Return a JSON-serialisable representation of ``policy``."""
|
||||
@ -84,6 +125,20 @@ def policy_to_dict(policy: FocusPolicy) -> dict[str, Any]:
|
||||
"blockable_system_packages": sorted(
|
||||
BLOCKABLE_SYSTEM_PACKAGES - {*policy.allowed_packages, ENFORCER_PACKAGE},
|
||||
),
|
||||
# Same subtraction, for the same reason: an allowed package must never
|
||||
# also be declared always-blocked, or the asset would state both at
|
||||
# once. The enforcer itself can never appear here -- hiding it takes
|
||||
# the escape hatch with it.
|
||||
"always_blocked_packages": sorted(
|
||||
ALWAYS_BLOCKED_PACKAGES - {*policy.allowed_packages, ENFORCER_PACKAGE},
|
||||
),
|
||||
# Emitted only when the provider is protected from the sweep. Pinning a
|
||||
# package the enforcer can hide is the worst case: DISALLOW_CONFIG_VPN
|
||||
# points at a hidden app and the device loses connectivity rather than
|
||||
# just the filter.
|
||||
"always_on_vpn_package": (
|
||||
ALWAYS_ON_VPN_PACKAGE if policy.is_protected(ALWAYS_ON_VPN_PACKAGE) else ""
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -25,6 +25,7 @@ def _policy(
|
||||
allowed_packages: frozenset[str] = frozenset({"pl.mbank", "com.launcher"}),
|
||||
night_allowed_packages: frozenset[str] = frozenset({"pl.mbank", "com.launcher"}),
|
||||
curfew: CurfewWindow | None = _DEFAULT_CURFEW,
|
||||
never_disable_prefixes: tuple[str, ...] = ("com.android.",),
|
||||
) -> FocusPolicy:
|
||||
"""Build a policy with the enforcer deliberately absent from both lists."""
|
||||
return FocusPolicy(
|
||||
@ -38,7 +39,7 @@ def _policy(
|
||||
launcher_package="com.launcher",
|
||||
allowed_packages=allowed_packages,
|
||||
night_allowed_packages=night_allowed_packages,
|
||||
never_disable_prefixes=("com.android.",),
|
||||
never_disable_prefixes=never_disable_prefixes,
|
||||
workout_unblock_domains=frozenset({"youtube.com"}),
|
||||
browser_packages=frozenset({"org.mozilla.firefox"}),
|
||||
)
|
||||
@ -103,6 +104,69 @@ def test_blockable_system_packages_never_contradicts_the_allowlist() -> None:
|
||||
assert "com.android.chrome" in payload["allowed_packages"]
|
||||
|
||||
|
||||
def test_always_blocked_exempts_youtube_and_chrome_from_the_geofence() -> None:
|
||||
"""The geofence must not become an off switch for these.
|
||||
|
||||
Everything else is restored on the AWAY branch, which makes leaving the
|
||||
house a way to switch enforcement off -- the specific thing Device Owner
|
||||
was provisioned to remove. Play is deliberately absent: it stays geofenced
|
||||
so apps can still be installed away from home.
|
||||
"""
|
||||
always = policy_to_dict(_policy())["always_blocked_packages"]
|
||||
|
||||
assert "com.google.android.youtube" in always
|
||||
assert "com.google.android.apps.youtube.music" in always
|
||||
assert "com.android.chrome" in always
|
||||
assert "com.android.vending" not in always
|
||||
|
||||
|
||||
def test_always_on_vpn_requires_a_sweep_protected_provider() -> None:
|
||||
"""Pinning a package the enforcer can hide is the worst failure mode.
|
||||
|
||||
DISALLOW_CONFIG_VPN pointing at a hidden app costs general connectivity,
|
||||
not just the filter, so the field is emitted only when the provider is
|
||||
protected.
|
||||
"""
|
||||
unprotected = policy_to_dict(_policy())["always_on_vpn_package"]
|
||||
protected = policy_to_dict(
|
||||
_policy(never_disable_prefixes=("com.celzero.bravedns",)),
|
||||
)["always_on_vpn_package"]
|
||||
|
||||
assert unprotected == ""
|
||||
assert protected == "com.celzero.bravedns"
|
||||
|
||||
|
||||
def test_always_blocked_is_a_subset_of_blockable() -> None:
|
||||
"""An always-blocked system app the sweep cannot see would silently no-op.
|
||||
|
||||
The runner filters FLAG_SYSTEM packages out of ``installedPackages``
|
||||
unless they are opted in, so the decision layer would never receive them.
|
||||
"""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
assert set(payload["always_blocked_packages"]) <= set(
|
||||
payload["blockable_system_packages"],
|
||||
)
|
||||
|
||||
|
||||
def test_always_blocked_never_contradicts_the_allowlist() -> None:
|
||||
"""Allowing a package wins over always-blocking it.
|
||||
|
||||
The asset must not state both at once; the subtraction keeps the two
|
||||
fields consistent no matter what config.sh says.
|
||||
"""
|
||||
payload = policy_to_dict(
|
||||
_policy(
|
||||
allowed_packages=frozenset(
|
||||
{"pl.mbank", "com.launcher", "com.android.chrome"},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assert "com.android.chrome" not in payload["always_blocked_packages"]
|
||||
assert "com.android.chrome" in payload["allowed_packages"]
|
||||
|
||||
|
||||
def test_lists_are_sorted_for_stable_diffs() -> None:
|
||||
"""Sorted output keeps a committed asset's diff meaningful."""
|
||||
payload = policy_to_dict(_policy())
|
||||
|
||||
Loading…
Reference in New Issue
Block a user