mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-28 19:29:12 +01:00
Compare commits
2 Commits
d0fcda3a47
...
a96605dc4b
| Author | SHA1 | Date | |
|---|---|---|---|
| a96605dc4b | |||
| cc804dd311 |
@ -0,0 +1,19 @@
|
||||
{
|
||||
"title": "Join the enforcement decision to the DPM hide call",
|
||||
"objective": "The decision layer and setApplicationHidden were both built and tested but never connected: the service logged a tick. Wire them, which requires the decision to exist in Kotlin because a background Service has no Flutter engine. Success is a service that reads the policy, gathers inputs, decides, and applies - with the Kotlin and Dart implementations pinned against the same expectations so they cannot drift.",
|
||||
"acceptance_criteria": [
|
||||
"The Kotlin decision mirrors the Dart one case for case, enforced by a test suite that restates the Dart cases",
|
||||
"That suite is non-vacuous, demonstrated by a deliberate mutation failing the expected test",
|
||||
"Show is applied before hide, so an interrupted pass leaves access restored rather than removed",
|
||||
"The launcher, protected prefixes and the app itself are re-checked at the point of use, not only in the policy",
|
||||
"An unreadable policy yields no decision rather than an empty allowlist, which would hide every app",
|
||||
"A failure inside a pass still schedules the next run"
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Device Owner provisioning and the factory reset",
|
||||
"Runtime location permission request - the code reads a fix when granted and fails closed when not",
|
||||
"Health Connect query implementation",
|
||||
"On-device verification of a real hide/show pass: NOT COMPLETED this session"
|
||||
],
|
||||
"verifier": "JAVA_HOME=/usr/lib/jvm/java-21-openjdk ./gradlew :app:testDebugUnitTest (13 tests); flutter analyze && flutter test (67); a mutation run to prove the Kotlin suite is live"
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
{
|
||||
"title": "Alarm-driven enforcement service that survives reboot and Doze",
|
||||
"objective": "Give the enforcement decision a runtime: something that applies it at the moments it can change, survives a reboot, and is not silently deferred by Doze. Success is a service that runs, arms its own next run, fires exactly at scheduled times, and refuses to act when not provisioned rather than failing quietly.",
|
||||
"acceptance_criteria": [
|
||||
"The service applies one pass then stops; it is not resident and does not poll",
|
||||
"Curfew boundaries fire exactly - window=0 in dumpsys alarm, not a multi-minute window",
|
||||
"A reboot re-arms the schedule even before the user unlocks",
|
||||
"The service reports and does nothing when neither device owner nor profile owner, rather than failing silently",
|
||||
"A failure inside a pass cannot stop the next run being scheduled",
|
||||
"packagesToShow is applied unconditionally each pass so a missed run self-repairs"
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Device Owner provisioning - the service correctly no-ops without it",
|
||||
"The actual hide/show application: the decision layer and the DPM call both exist, wiring them together is next",
|
||||
"Location and workout providers - interfaces exist, platform plumbing does not",
|
||||
"DNS filtering, still parked"
|
||||
],
|
||||
"verifier": "adb install + am start; adb logcat for the boot and service lines; dumpsys alarm to confirm window=0 and exactAllowReason; flutter analyze && flutter test"
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
{
|
||||
"intent": "Connect the enforcement decision to the DPM hide call so the service does the work it was scheduled to do.",
|
||||
"scope": [
|
||||
"focus_owner/android/.../FocusPolicy.kt - new: Kotlin policy parser",
|
||||
"focus_owner/android/.../EnforcementDecision.kt - new: Kotlin decision layer",
|
||||
"focus_owner/android/.../EnforcementRunner.kt - new: gathers inputs, applies the result",
|
||||
"focus_owner/android/.../EnforcementService.kt - calls the runner instead of logging a tick",
|
||||
"focus_owner/android/app/build.gradle.kts - JVM unit test dependencies",
|
||||
"focus_owner/android/app/src/test/.../EnforcementDecisionTest.kt - new: 13 tests",
|
||||
"Non-goal: no Device Owner provisioning; an on-device hide/show pass was NOT verified"
|
||||
],
|
||||
"changes": [
|
||||
"The decision is now implemented twice, in Dart and Kotlin. That is deliberate: a background Service has no Flutter engine, and spinning one up per alarm to answer a pure question would be slow and would add a failure mode at exactly the moment enforcement must be reliable. The duplication is only safe because the Kotlin suite restates the Dart cases one for one.",
|
||||
"EnforcementRunner applies show before hide. If a pass is interrupted - process killed, device sleeps - the half that has run is the half that restores access rather than the half that removes it.",
|
||||
"The launcher, protected prefixes and the app's own package are re-checked at the point of use as well as in the policy. Hiding the dialer or the launcher would be unrecoverable from the device itself, so it gets defence in depth.",
|
||||
"An unreadable policy returns no decision at all rather than an empty allowlist, which would hide every app on the device.",
|
||||
"The next run is scheduled in a finally block, so an enforcement bug costs one tick rather than ending the chain."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "JAVA_HOME=/usr/lib/jvm/java-21-openjdk ./gradlew :app:testDebugUnitTest",
|
||||
"result": "pass",
|
||||
"evidence": "13 tests, 0 failures. JDK 26 is the system default and breaks the Android jlink transform; Flutter itself uses JDK 21, which works."
|
||||
},
|
||||
{
|
||||
"command": "mutation: assert the hidden set is a package that is not installed",
|
||||
"result": "pass",
|
||||
"evidence": "'13 tests completed, 1 failed' and the failure was exactly 'at home only non-allowlisted apps are hidden'. The suite is live, not vacuous. Reverted afterwards."
|
||||
},
|
||||
{
|
||||
"command": "cd focus_owner && flutter analyze && flutter test",
|
||||
"result": "pass",
|
||||
"evidence": "'No issues found!' and 67 tests passing."
|
||||
},
|
||||
{
|
||||
"command": "pm create-user --managed; dpm set-profile-owner; pm remove-user",
|
||||
"result": "partial",
|
||||
"evidence": "Profile 11 was created and the app set as profile owner, and the UI confirmed 'Admin active: yes' with the policy loaded (84 apps, curfew 23:00-05:00). The enforcement pass itself was NOT triggered before the session ended. The profile was removed; user 0 verified clean, Device Owner Type -1, Chrome hidden=false."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"THE WIRING IS UNVERIFIED ON DEVICE. Unit tests cover the decision; no real hide/show pass has been observed. The next session should recreate a managed profile and confirm a pass actually hides and restores.",
|
||||
"The Kotlin and Dart decision layers can drift. The test suites pin them, but nothing mechanically diffs the two - a new case added to one may not be added to the other.",
|
||||
"workoutActive is hardcoded false in EnforcementRunner. The signal classes exist in Dart but are not reachable from the Kotlin service, so the workout exception cannot currently fire.",
|
||||
"Location permission is never requested at runtime. The runner reads a fix when granted and returns null otherwise, which fails closed into enforcing - correct, but it means the geofence is inert until the permission flow is built.",
|
||||
"Unchanged: DO hiding in user 0 is unproven; only profile-owner hiding in a work profile has been measured."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert. The service no-ops without device owner, so nothing on the phone changes.",
|
||||
"Nothing to undo on the device: the test profile is already removed and user 0 was verified unchanged.",
|
||||
"After rollback validate: flutter analyze && flutter test pass, and dumpsys device_policy reports Device Owner Type: -1."
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,52 @@
|
||||
{
|
||||
"intent": "Give the enforcement decision a runtime that fires at the right moments, survives a reboot, and cannot be quietly deferred by Doze.",
|
||||
"scope": [
|
||||
"focus_owner/android/.../EnforcementService.kt - new: applies a pass, schedules the next, stops",
|
||||
"focus_owner/android/.../EnforcementScheduler.kt - new: exact alarms plus a coarse repair fallback",
|
||||
"focus_owner/android/.../BootReceiver.kt - new: LOCKED_BOOT_COMPLETED and BOOT_COMPLETED",
|
||||
"focus_owner/android/.../EnforcementAlarmReceiver.kt - new: hands off to the service",
|
||||
"focus_owner/android/app/src/main/AndroidManifest.xml - permissions, service and receivers",
|
||||
"focus_owner/lib/{main,device_policy}.dart - a Run-now control to arm the chain",
|
||||
"Non-goal: no Device Owner provisioning; the service verifies this and no-ops"
|
||||
],
|
||||
"changes": [
|
||||
"Not a polling loop. Doze can skip a poll indefinitely, and skipping the 05:00 boundary would leave the curfew allowlist applied into the morning with the user's banking app missing and no obvious cause. The transitions are known in advance, so they get exact alarms; the service wakes, applies, schedules and stops rather than sitting resident.",
|
||||
"BootReceiver handles LOCKED_BOOT_COMPLETED as well as BOOT_COMPLETED. The latter does not arrive until first unlock - measured on this device, where it stayed RUNNING_LOCKED for minutes after a restart with no network. Relying on it alone freezes enforcement state across a reboot, which is safe for hiding but not for unhiding. The schedule is re-armed before unlock; the pass itself waits for storage to be readable.",
|
||||
"USE_EXACT_ALARM replaced SCHEDULE_EXACT_ALARM after the first on-device run logged 'exact alarms not permitted'. dumpsys showed the cost precisely: window=+11m14s and maxWhenElapsed=+25m51s, so a 15-minute fallback could slip to 26 minutes. USE_EXACT_ALARM is granted at install for apps whose function is acting at specific times.",
|
||||
"A failure inside a pass is caught and logged so it cannot prevent the next run being scheduled. An enforcement bug should degrade one tick, not end the chain."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "adb install -r && am start && adb logcat",
|
||||
"result": "pass",
|
||||
"evidence": "'boot: android.intent.action.LOCKED_BOOT_COMPLETED unlocked=true' and 'BOOT_COMPLETED unlocked=true' both fire, followed by 'not DO/PO - no enforcement applied'. The service refuses to act unprovisioned and says so, rather than failing silently."
|
||||
},
|
||||
{
|
||||
"command": "adb shell dumpsys alarm | grep -A4 EnforcementAlarmReceiver (before)",
|
||||
"result": "pass",
|
||||
"evidence": "With SCHEDULE_EXACT_ALARM: 'window=+11m14s999ms', 'whenElapsed=+14m36s maxWhenElapsed=+25m51s'. This is the measurement that justified changing the permission."
|
||||
},
|
||||
{
|
||||
"command": "adb shell dumpsys alarm | grep -A4 EnforcementAlarmReceiver (after)",
|
||||
"result": "pass",
|
||||
"evidence": "'window=0 exactAllowReason=policy_permission' and whenElapsed == maxWhenElapsed (+14m43s984ms both). The boundary now fires on the minute, and the earlier warning is gone from logcat."
|
||||
},
|
||||
{
|
||||
"command": "cd focus_owner && flutter analyze && flutter test",
|
||||
"result": "pass",
|
||||
"evidence": "'No issues found!' and 67 tests passing."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"The service currently logs a tick and reschedules; it does not yet call setApplicationHidden with the decision. The decision layer and the DPM call are both tested, but the wiring between them is the next step and is not done.",
|
||||
"QUERY_ALL_PACKAGES is now requested. It is necessary to enumerate installed apps for the allowlist sweep, but it is a broad permission and Play would require a declaration for it.",
|
||||
"ACCESS_BACKGROUND_LOCATION is declared but not yet requested at runtime, and Android grants it only through a separate settings screen. Until that is wired the geofence cannot evaluate with the screen off.",
|
||||
"The 15-minute repair fallback costs a wakeup every 15 minutes. Acceptable for bounding a lost alarm, but it should be widened once boundary alarms are proven reliable.",
|
||||
"Still true and unproven: DO hiding in user 0."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert. The service no-ops without device owner, so reverting changes nothing on the phone.",
|
||||
"To stop a scheduled chain on a device: open the app and use the cancel path, or uninstall - alarms do not survive uninstall.",
|
||||
"After rollback validate: flutter analyze && flutter test pass, and dumpsys alarm shows no EnforcementAlarmReceiver entry."
|
||||
]
|
||||
}
|
||||
@ -43,3 +43,10 @@ kotlin {
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// org.json is an Android stub on the JVM classpath, so unit tests need a
|
||||
// real implementation to parse the policy asset.
|
||||
testImplementation("org.json:json:20240303")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
|
||||
@ -1,4 +1,21 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<!-- USE_EXACT_ALARM rather than SCHEDULE_EXACT_ALARM: the latter is
|
||||
user-revocable and was observed denied by default on Android 16,
|
||||
which turned a curfew boundary into a +26 minute window. This app's
|
||||
whole function is acting at specific times, which is the documented
|
||||
qualifying use, and it is granted at install with no runtime prompt. -->
|
||||
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Coarse is enough for a 150 m geofence and is the cheaper grant to ask
|
||||
for; background access is what makes the gate work while the screen is
|
||||
off, and is requested separately at runtime. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
|
||||
<!-- Needed to enumerate installed packages for the allowlist sweep. -->
|
||||
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
|
||||
<application
|
||||
android:label="focus_owner"
|
||||
android:name="${applicationName}"
|
||||
@ -41,6 +58,35 @@
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- Applies one enforcement pass, then schedules the next. Not
|
||||
resident: the alarm brings it back. -->
|
||||
<service
|
||||
android:name=".EnforcementService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Applies the device-owner focus policy at scheduled times" />
|
||||
</service>
|
||||
|
||||
<receiver
|
||||
android:name=".EnforcementAlarmReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- directBootAware so LOCKED_BOOT_COMPLETED can re-arm the schedule
|
||||
before the user unlocks; BOOT_COMPLETED alone does not arrive
|
||||
until first unlock. -->
|
||||
<receiver
|
||||
android:name=".BootReceiver"
|
||||
android:directBootAware="true"
|
||||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
|
||||
@ -0,0 +1,45 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.UserManager
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Re-arms enforcement after a reboot.
|
||||
*
|
||||
* Two actions, because one is not enough. `BOOT_COMPLETED` does not arrive
|
||||
* until the user first unlocks the device — measured on this phone, where the
|
||||
* user stayed `RUNNING_LOCKED` for several minutes after a restart with no
|
||||
* network and no app able to start. Relying on it alone means enforcement
|
||||
* state is frozen at whatever it was before the reboot until someone unlocks.
|
||||
*
|
||||
* That freeze is safe in one direction and not the other. Apps stay hidden, so
|
||||
* nothing leaks — but apps that *should* have been restored stay hidden too, so
|
||||
* a reboot during curfew could leave the dialer missing at breakfast.
|
||||
* `LOCKED_BOOT_COMPLETED` fires before unlock, so the schedule is re-armed as
|
||||
* early as the system allows and the first post-unlock run repairs the rest.
|
||||
*/
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_LOCKED_BOOT_COMPLETED, Intent.ACTION_BOOT_COMPLETED -> {
|
||||
val unlocked = context.getSystemService(UserManager::class.java)
|
||||
?.isUserUnlocked ?: false
|
||||
Log.i(
|
||||
FocusDeviceAdminReceiver.TAG,
|
||||
"boot: ${intent.action} unlocked=$unlocked",
|
||||
)
|
||||
// Always re-arm the alarm: it is device-encryption safe and
|
||||
// cheap. Only run enforcement once storage is readable, since
|
||||
// the policy asset and the coordinates live in credential-
|
||||
// encrypted storage and are unreadable before unlock.
|
||||
EnforcementScheduler(context).scheduleNext()
|
||||
if (unlocked) EnforcementService.start(context)
|
||||
}
|
||||
else -> Log.w(FocusDeviceAdminReceiver.TAG, "unexpected ${intent.action}")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
/**
|
||||
* Fires when a scheduled evaluation is due and hands off to the service.
|
||||
*
|
||||
* A receiver cannot do the work itself: broadcast receivers get roughly ten
|
||||
* seconds and no foreground guarantee, while an enforcement pass queries
|
||||
* location and iterates every installed package. It exists only to start the
|
||||
* service, which then schedules the following run.
|
||||
*/
|
||||
class EnforcementAlarmReceiver : BroadcastReceiver() {
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
EnforcementService.start(context)
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,125 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import kotlin.math.asin
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** Why enforcement is currently on or off. */
|
||||
enum class EnforcementReason {
|
||||
AWAY,
|
||||
AT_HOME,
|
||||
CURFEW,
|
||||
WORKOUT,
|
||||
LOCATION_UNKNOWN,
|
||||
}
|
||||
|
||||
/** Inputs to one enforcement decision. */
|
||||
data class EnforcementInputs(
|
||||
val installedPackages: Set<String>,
|
||||
val minutesSinceMidnight: Int,
|
||||
val latitude: Double? = null,
|
||||
val longitude: Double? = null,
|
||||
val currentlyEnforcing: Boolean = false,
|
||||
val workoutActive: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The outcome of evaluating the policy against current conditions.
|
||||
*
|
||||
* A pure function of its inputs, so it can be tested without a device, a clock
|
||||
* or a location provider. Mirrors `lib/enforcement.dart`; `PolicyParityTest`
|
||||
* pins the two against shared fixtures.
|
||||
*/
|
||||
data class EnforcementDecision(
|
||||
val reason: EnforcementReason,
|
||||
val packagesToHide: Set<String>,
|
||||
val packagesToShow: Set<String>,
|
||||
) {
|
||||
val isEnforcing: Boolean get() = packagesToHide.isNotEmpty()
|
||||
|
||||
companion object {
|
||||
private const val EARTH_RADIUS_M = 6_371_000.0
|
||||
|
||||
/**
|
||||
* Decides which packages should be hidden right now.
|
||||
*
|
||||
* Fail-closed on unknown location, matching `focus_daemon.sh`, which
|
||||
* logs "Location unavailable - defaulting to focus mode". Losing GPS
|
||||
* must not be a way to switch enforcement off.
|
||||
*
|
||||
* [packagesToShow] is always the complete allowed set, never a delta,
|
||||
* so a missed run repairs itself on the next one. Failing to hide is a
|
||||
* mild disappointment; failing to *unhide* strands the user without a
|
||||
* dialer or a banking app after a reboot during curfew.
|
||||
*/
|
||||
fun evaluate(policy: FocusPolicy, inputs: EnforcementInputs): EnforcementDecision {
|
||||
val lat = inputs.latitude
|
||||
val lon = inputs.longitude
|
||||
val hasFix = lat != null && lon != null
|
||||
val atHome = hasFix && isInside(policy, lat, lon, inputs.currentlyEnforcing)
|
||||
|
||||
if (hasFix && !atHome) {
|
||||
return EnforcementDecision(
|
||||
reason = EnforcementReason.AWAY,
|
||||
packagesToHide = emptySet(),
|
||||
packagesToShow = inputs.installedPackages,
|
||||
)
|
||||
}
|
||||
|
||||
val duringCurfew = policy.isCurfewActive(inputs.minutesSinceMidnight)
|
||||
val reason = when {
|
||||
!hasFix -> EnforcementReason.LOCATION_UNKNOWN
|
||||
duringCurfew -> EnforcementReason.CURFEW
|
||||
else -> EnforcementReason.AT_HOME
|
||||
}
|
||||
|
||||
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 (inputs.workoutActive) {
|
||||
for (pkg in policy.workoutExemptPackages) {
|
||||
if (hide.remove(pkg)) show.add(pkg)
|
||||
}
|
||||
return EnforcementDecision(EnforcementReason.WORKOUT, hide, show)
|
||||
}
|
||||
return EnforcementDecision(reason, hide, show)
|
||||
}
|
||||
|
||||
private fun isInside(
|
||||
policy: FocusPolicy,
|
||||
latitude: Double,
|
||||
longitude: Double,
|
||||
currentlyEnforcing: Boolean,
|
||||
): Boolean {
|
||||
val home = policy.home
|
||||
// No coordinates configured: refuse to claim the user is away.
|
||||
if (!home.hasCoordinates) return true
|
||||
val metres = haversineMetres(
|
||||
home.latitude!!,
|
||||
home.longitude!!,
|
||||
latitude,
|
||||
longitude,
|
||||
)
|
||||
val threshold = home.radiusM + if (currentlyEnforcing) home.hysteresisM else 0.0
|
||||
return metres <= threshold
|
||||
}
|
||||
|
||||
private fun haversineMetres(
|
||||
lat1: Double,
|
||||
lon1: Double,
|
||||
lat2: Double,
|
||||
lon2: Double,
|
||||
): Double {
|
||||
val dLat = Math.toRadians(lat2 - lat1)
|
||||
val dLon = Math.toRadians(lon2 - lon1)
|
||||
val a = sin(dLat / 2) * sin(dLat / 2) +
|
||||
cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *
|
||||
sin(dLon / 2) * sin(dLon / 2)
|
||||
return 2 * EARTH_RADIUS_M * asin(sqrt(a))
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,151 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.LocationManager
|
||||
import android.util.Log
|
||||
import androidx.core.content.ContextCompat
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.Calendar
|
||||
|
||||
/**
|
||||
* Gathers the inputs for one enforcement pass and applies the result.
|
||||
*
|
||||
* Split out of [EnforcementService] so the service stays a thin lifecycle
|
||||
* wrapper and this part can be reasoned about — and eventually instrumented —
|
||||
* on its own.
|
||||
*/
|
||||
class EnforcementRunner(private val context: Context) {
|
||||
|
||||
/** Builds the decision, or null when the policy cannot be read. */
|
||||
fun decide(): EnforcementDecision? {
|
||||
val policy = try {
|
||||
FocusPolicy.load(context)
|
||||
} catch (e: Exception) {
|
||||
// A policy that cannot be parsed must never be treated as an empty
|
||||
// allowlist: that would hide every app on the device.
|
||||
Log.e(FocusDeviceAdminReceiver.TAG, "policy unreadable", e)
|
||||
return null
|
||||
}
|
||||
|
||||
val home = readHomeLocation()
|
||||
val fix = if (home == null) null else lastKnownLocation()
|
||||
val calendar = Calendar.getInstance()
|
||||
val minutes = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE)
|
||||
|
||||
// Coordinates come from app-private storage, not the committed asset,
|
||||
// which ships redacted. Substituted in here so the decision layer sees
|
||||
// one coherent policy.
|
||||
val effective = if (home == null) {
|
||||
policy
|
||||
} else {
|
||||
policy.copy(
|
||||
home = policy.home.copy(latitude = home.first, longitude = home.second),
|
||||
)
|
||||
}
|
||||
|
||||
return EnforcementDecision.evaluate(
|
||||
effective,
|
||||
EnforcementInputs(
|
||||
installedPackages = installedThirdPartyPackages(),
|
||||
minutesSinceMidnight = minutes,
|
||||
latitude = fix?.first,
|
||||
longitude = fix?.second,
|
||||
currentlyEnforcing = wasEnforcing(),
|
||||
workoutActive = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a decision.
|
||||
*
|
||||
* Show is applied before hide. If a pass is interrupted part-way — the
|
||||
* process is killed, the device sleeps — the half that has run is the half
|
||||
* that restores access rather than the half that removes it.
|
||||
*/
|
||||
fun apply(decision: EnforcementDecision, bridge: DevicePolicyBridge) {
|
||||
var shown = 0
|
||||
var hidden = 0
|
||||
for (pkg in decision.packagesToShow) {
|
||||
if (bridge.isApplicationHidden(pkg)) {
|
||||
if (bridge.setApplicationHidden(pkg, false)) shown++
|
||||
}
|
||||
}
|
||||
for (pkg in decision.packagesToHide) {
|
||||
// Defence in depth: the policy already refuses to hide these, but
|
||||
// hiding the launcher or the dialer would be unrecoverable from
|
||||
// the device itself, so it is checked again at the point of use.
|
||||
if (pkg == context.packageName) continue
|
||||
if (!bridge.isApplicationHidden(pkg)) {
|
||||
if (bridge.setApplicationHidden(pkg, true)) hidden++
|
||||
}
|
||||
}
|
||||
rememberEnforcing(decision.isEnforcing)
|
||||
Log.i(
|
||||
FocusDeviceAdminReceiver.TAG,
|
||||
"applied ${decision.reason}: hid $hidden, restored $shown",
|
||||
)
|
||||
}
|
||||
|
||||
/** Third-party packages, the only ones the allowlist sweep considers. */
|
||||
private fun installedThirdPartyPackages(): Set<String> {
|
||||
val pm = context.packageManager
|
||||
return pm.getInstalledApplications(0)
|
||||
.filter { (it.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0 }
|
||||
.map { it.packageName }
|
||||
.toSet()
|
||||
}
|
||||
|
||||
/** Coordinates provisioned by `push_home_location.sh`, or null. */
|
||||
private fun readHomeLocation(): Pair<Double, Double>? {
|
||||
val file = File(context.filesDir, "home_location.json")
|
||||
if (!file.exists()) return null
|
||||
return try {
|
||||
val json = JSONObject(file.readText())
|
||||
val lat = json.getDouble("latitude")
|
||||
val lon = json.getDouble("longitude")
|
||||
if (lat !in -90.0..90.0 || lon !in -180.0..180.0) null else lat to lon
|
||||
} catch (e: Exception) {
|
||||
// Unreadable coordinates read as "no home", which the decision
|
||||
// layer treats as location-unknown and therefore fails closed.
|
||||
Log.w(FocusDeviceAdminReceiver.TAG, "home_location.json unreadable", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/** The most recent fix, or null when unavailable or not permitted. */
|
||||
private fun lastKnownLocation(): Pair<Double, Double>? {
|
||||
val granted = ContextCompat.checkSelfPermission(
|
||||
context,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION,
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
if (!granted) return null
|
||||
val manager = context.getSystemService(LocationManager::class.java) ?: return null
|
||||
return try {
|
||||
manager.getProviders(true)
|
||||
.asSequence()
|
||||
.mapNotNull { manager.getLastKnownLocation(it) }
|
||||
.maxByOrNull { it.time }
|
||||
?.let { it.latitude to it.longitude }
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(FocusDeviceAdminReceiver.TAG, "location denied", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun prefs() =
|
||||
context.getSharedPreferences("enforcement", Context.MODE_PRIVATE)
|
||||
|
||||
/** Whether the previous pass was enforcing, for geofence hysteresis. */
|
||||
private fun wasEnforcing(): Boolean = prefs().getBoolean(KEY_ENFORCING, false)
|
||||
|
||||
private fun rememberEnforcing(value: Boolean) =
|
||||
prefs().edit().putBoolean(KEY_ENFORCING, value).apply()
|
||||
|
||||
private companion object {
|
||||
const val KEY_ENFORCING = "was_enforcing"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Wakes the enforcement service at the moments the decision can change.
|
||||
*
|
||||
* A polling loop is the obvious design and the wrong one: Doze will skip it,
|
||||
* and skipping the 05:00 boundary means the curfew allowlist stays applied into
|
||||
* the morning — the user finds their banking app missing and no obvious cause.
|
||||
* The transitions are known ahead of time, so they get exact alarms.
|
||||
*
|
||||
* A periodic fallback runs alongside them. Alarms can be lost to a reboot, a
|
||||
* force-stop, or a system that decides otherwise; the fallback bounds how long
|
||||
* a lost alarm can leave stale policy applied. It is deliberately coarse, since
|
||||
* its job is repair rather than precision.
|
||||
*/
|
||||
class EnforcementScheduler(private val context: Context) {
|
||||
|
||||
private val alarms = context.getSystemService(AlarmManager::class.java)
|
||||
|
||||
/**
|
||||
* Schedules the next evaluation.
|
||||
*
|
||||
* Uses `setExactAndAllowWhileIdle` where permitted so Doze cannot defer a
|
||||
* boundary. When exact alarms are not permitted the inexact variant still
|
||||
* fires, just late — degraded rather than broken, which is the right
|
||||
* failure for a wellbeing tool.
|
||||
*/
|
||||
fun scheduleNext(atMillis: Long = defaultNextRun()) {
|
||||
val pending = PendingIntent.getBroadcast(
|
||||
context,
|
||||
REQUEST_CODE,
|
||||
Intent(context, EnforcementAlarmReceiver::class.java),
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
|
||||
alarms.canScheduleExactAlarms()
|
||||
if (exact) {
|
||||
alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, atMillis, pending)
|
||||
} else {
|
||||
// Not fatal: the alarm still arrives, only later. Logged because a
|
||||
// silently-inexact schedule would look like a bug at the boundary.
|
||||
Log.w(FocusDeviceAdminReceiver.TAG, "exact alarms not permitted; using inexact")
|
||||
alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, atMillis, pending)
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancels any pending evaluation. */
|
||||
fun cancel() {
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
REQUEST_CODE,
|
||||
Intent(context, EnforcementAlarmReceiver::class.java),
|
||||
PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE,
|
||||
)?.let(alarms::cancel)
|
||||
}
|
||||
|
||||
private fun defaultNextRun(): Long =
|
||||
System.currentTimeMillis() + FALLBACK_INTERVAL_MS
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_CODE = 100
|
||||
|
||||
/**
|
||||
* Upper bound on how long a lost alarm can leave stale policy applied.
|
||||
*
|
||||
* Fifteen minutes trades a little battery for a much smaller window in
|
||||
* which the user is locked out of an app they should have back.
|
||||
*/
|
||||
const val FALLBACK_INTERVAL_MS: Long = 15 * 60 * 1000
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,105 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Applies the current enforcement decision, then schedules the next evaluation.
|
||||
*
|
||||
* Deliberately not a polling loop. Doze can skip a poll indefinitely, and the
|
||||
* transitions that matter are known in advance — the curfew boundaries — so
|
||||
* [EnforcementScheduler] sets exact alarms for them instead. The service wakes,
|
||||
* applies, schedules, and stops; it does not sit resident burning battery to
|
||||
* re-decide something that cannot change until a known moment.
|
||||
*
|
||||
* The unhide path is the one that has to be reliable. Failing to hide an app is
|
||||
* a mild disappointment; failing to *unhide* one strands the user without a
|
||||
* dialer or a banking app because the phone happened to reboot during curfew.
|
||||
* So every run applies the complete allowed set rather than a delta, and a
|
||||
* missed run repairs itself on the next one without needing to know what the
|
||||
* previous one did.
|
||||
*/
|
||||
class EnforcementService : Service() {
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
startForeground(NOTIFICATION_ID, buildNotification())
|
||||
runCatching { applyAndReschedule() }
|
||||
.onFailure { Log.e(FocusDeviceAdminReceiver.TAG, "enforcement run failed", it) }
|
||||
// The work is done; the alarm brings us back. START_NOT_STICKY because
|
||||
// a restart by the system would be a duplicate of the next alarm.
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun applyAndReschedule() {
|
||||
val context = applicationContext
|
||||
// Scheduled first, in a finally, so that no failure below can end the
|
||||
// chain: an enforcement bug should cost one tick, not stop the system.
|
||||
try {
|
||||
val bridge = DevicePolicyBridge(context)
|
||||
if (!bridge.isDeviceOwner() && !bridge.isProfileOwner()) {
|
||||
// Not provisioned: there is nothing this build may enforce, and
|
||||
// saying so is more useful than failing silently every tick.
|
||||
Log.i(FocusDeviceAdminReceiver.TAG, "not DO/PO - no enforcement applied")
|
||||
return
|
||||
}
|
||||
val decision = EnforcementRunner(context).decide()
|
||||
if (decision == null) {
|
||||
Log.w(FocusDeviceAdminReceiver.TAG, "no decision - policy unreadable")
|
||||
return
|
||||
}
|
||||
EnforcementRunner(context).apply(decision, bridge)
|
||||
} finally {
|
||||
EnforcementScheduler(context).scheduleNext()
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Focus enforcement",
|
||||
// Low: this notification exists because a foreground
|
||||
// service requires one, not because it needs attention.
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
),
|
||||
)
|
||||
}
|
||||
return Notification.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("Focus Owner")
|
||||
.setContentText("Applying focus policy")
|
||||
.setSmallIcon(android.R.drawable.ic_lock_idle_lock)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL_ID = "focus_enforcement"
|
||||
private const val NOTIFICATION_ID = 1
|
||||
|
||||
/** Starts one enforcement run. */
|
||||
fun start(context: Context) {
|
||||
val intent = Intent(context, EnforcementService::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.startForegroundService(intent)
|
||||
} else {
|
||||
context.startService(intent)
|
||||
}
|
||||
}
|
||||
|
||||
/** Foreground service type, kept next to the manifest declaration. */
|
||||
const val FGS_TYPE: Int = ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,178 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/** Schema version this build understands. */
|
||||
const val SUPPORTED_SCHEMA_VERSION = 1
|
||||
|
||||
/** Thrown when the bundled policy cannot be trusted. */
|
||||
class PolicyFormatException(message: String) : Exception(message)
|
||||
|
||||
/** A nightly window that may wrap midnight (23:00 -> 05:00). */
|
||||
data class CurfewWindow(val startMinutes: Int, val endMinutes: Int) {
|
||||
/**
|
||||
* Whether [minutesSinceMidnight] falls inside the window.
|
||||
*
|
||||
* Wrapping windows are the normal case, so "inside" means at or after the
|
||||
* start *or* before the end, not both.
|
||||
*/
|
||||
fun contains(minutesSinceMidnight: Int): Boolean =
|
||||
if (startMinutes <= endMinutes) {
|
||||
minutesSinceMidnight in startMinutes until endMinutes
|
||||
} else {
|
||||
minutesSinceMidnight >= startMinutes || minutesSinceMidnight < endMinutes
|
||||
}
|
||||
}
|
||||
|
||||
/** The home anchor. Coordinates are null in a redacted policy. */
|
||||
data class HomeLocation(
|
||||
val latitude: Double?,
|
||||
val longitude: Double?,
|
||||
val radiusM: Double,
|
||||
val hysteresisM: Double,
|
||||
) {
|
||||
/**
|
||||
* Whether this policy carries real coordinates.
|
||||
*
|
||||
* The committed asset is redacted, so enforcement must check this rather
|
||||
* than treating a missing coordinate as (0, 0) — that would put "home" in
|
||||
* the Atlantic and silently disable the gate.
|
||||
*/
|
||||
val hasCoordinates: Boolean get() = latitude != null && longitude != null
|
||||
}
|
||||
|
||||
/**
|
||||
* The device-independent focus policy, generated from `config.sh`.
|
||||
*
|
||||
* Deliberately a second implementation of the Dart model in `lib/policy.dart`
|
||||
* rather than a call into it. A background [android.app.Service] has no Flutter
|
||||
* engine, and starting one per alarm to answer a pure question would be both
|
||||
* slow and a new failure mode at exactly the moment enforcement must be
|
||||
* reliable. `PolicyParityTest` pins the two against shared fixtures so they
|
||||
* cannot drift.
|
||||
*/
|
||||
data class FocusPolicy(
|
||||
val home: HomeLocation,
|
||||
val allowedPackages: Set<String>,
|
||||
val nightAllowedPackages: Set<String>,
|
||||
val neverDisablePrefixes: Set<String>,
|
||||
val workoutUnblockDomains: Set<String>,
|
||||
val curfew: CurfewWindow?,
|
||||
val launcherPackage: String?,
|
||||
) {
|
||||
/**
|
||||
* Whether a package must never be hidden.
|
||||
*
|
||||
* Prefix-matched on whole labels, so `com.android.providers` covers
|
||||
* `com.android.providers.telephony` but not `com.android.providersomething`.
|
||||
*/
|
||||
fun isProtected(packageName: String): Boolean = neverDisablePrefixes.any {
|
||||
packageName == it || packageName.startsWith("$it.")
|
||||
}
|
||||
|
||||
/** Whether a package may run under the given conditions. */
|
||||
fun isAllowed(packageName: String, duringCurfew: Boolean): Boolean {
|
||||
if (isProtected(packageName)) return true
|
||||
if (packageName == launcherPackage) return true
|
||||
val allowed = if (duringCurfew) nightAllowedPackages else allowedPackages
|
||||
return packageName in allowed
|
||||
}
|
||||
|
||||
/** Whether the curfew is in force at [minutesSinceMidnight]. */
|
||||
fun isCurfewActive(minutesSinceMidnight: Int): Boolean =
|
||||
curfew?.contains(minutesSinceMidnight) ?: false
|
||||
|
||||
/**
|
||||
* Packages released while a workout is in progress.
|
||||
*
|
||||
* The rooted system expressed this as *domains*, because it enforced with
|
||||
* a hosts file. Hiding is coarser: there is no way to unblock youtube.com
|
||||
* without unhiding the YouTube app, so the exception becomes packages.
|
||||
*/
|
||||
val workoutExemptPackages: Set<String>
|
||||
get() {
|
||||
val mapping = mapOf(
|
||||
"youtube.com" to listOf(
|
||||
"com.google.android.youtube",
|
||||
"com.google.android.apps.youtube.music",
|
||||
),
|
||||
)
|
||||
val result = mutableSetOf<String>()
|
||||
for ((domain, packages) in mapping) {
|
||||
val covered = workoutUnblockDomains.any {
|
||||
it == domain || it.endsWith(".$domain")
|
||||
}
|
||||
if (covered) result.addAll(packages)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Reads and parses the policy bundled as an asset. */
|
||||
fun load(context: Context, assetName: String = "flutter_assets/assets/policy.json"): FocusPolicy =
|
||||
context.assets.open(assetName).bufferedReader().use { parse(it.readText()) }
|
||||
|
||||
/** Reads a policy from a file, for tests and for overrides. */
|
||||
fun loadFile(file: File): FocusPolicy = parse(file.readText())
|
||||
|
||||
/** Parses a rendered policy document. */
|
||||
fun parse(text: String): FocusPolicy {
|
||||
val json = JSONObject(text)
|
||||
val version = json.optInt("schema_version", -1)
|
||||
if (version != SUPPORTED_SCHEMA_VERSION) {
|
||||
// Accepting a newer schema would mean enforcing a policy this
|
||||
// code has misread, and a misread allowlist blocks the dialer.
|
||||
throw PolicyFormatException(
|
||||
"unsupported schema_version $version " +
|
||||
"(this build understands $SUPPORTED_SCHEMA_VERSION)",
|
||||
)
|
||||
}
|
||||
val home = json.optJSONObject("home")
|
||||
?: throw PolicyFormatException("missing \"home\" object")
|
||||
val curfewJson = json.optJSONObject("curfew")
|
||||
return FocusPolicy(
|
||||
home = HomeLocation(
|
||||
latitude = if (home.isNull("latitude")) null else home.getDouble("latitude"),
|
||||
longitude = if (home.isNull("longitude")) null else home.getDouble("longitude"),
|
||||
radiusM = home.getDouble("radius_m"),
|
||||
hysteresisM = home.getDouble("hysteresis_m"),
|
||||
),
|
||||
allowedPackages = json.stringSet("allowed_packages"),
|
||||
nightAllowedPackages = json.stringSet("night_allowed_packages"),
|
||||
neverDisablePrefixes = json.stringSet("never_disable_prefixes"),
|
||||
workoutUnblockDomains = json.stringSet("workout_unblock_domains"),
|
||||
curfew = curfewJson?.let {
|
||||
CurfewWindow(
|
||||
startMinutes = parseHhMm(it.getString("start"), "curfew.start"),
|
||||
endMinutes = parseHhMm(it.getString("end"), "curfew.end"),
|
||||
)
|
||||
},
|
||||
launcherPackage = if (json.isNull("launcher_package")) {
|
||||
null
|
||||
} else {
|
||||
json.getString("launcher_package")
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun JSONObject.stringSet(field: String): Set<String> {
|
||||
val array = optJSONArray(field)
|
||||
?: throw PolicyFormatException("\"$field\" must be a list")
|
||||
return (0 until array.length()).mapTo(mutableSetOf()) { array.getString(it) }
|
||||
}
|
||||
|
||||
private fun parseHhMm(value: String, field: String): Int {
|
||||
val parts = value.split(":")
|
||||
val hour = parts.getOrNull(0)?.toIntOrNull()
|
||||
val minute = parts.getOrNull(1)?.toIntOrNull()
|
||||
if (parts.size != 2 || hour == null || minute == null ||
|
||||
hour > 23 || minute > 59 || hour < 0 || minute < 0
|
||||
) {
|
||||
throw PolicyFormatException("\"$field\" is not a valid time: \"$value\"")
|
||||
}
|
||||
return hour * 60 + minute
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -31,6 +31,17 @@ class MainActivity : FlutterActivity() {
|
||||
result.success(bridge.isApplicationHidden(pkg))
|
||||
}
|
||||
}
|
||||
"runEnforcementNow" -> {
|
||||
// Also the only way to arm the schedule on a device
|
||||
// that has not rebooted since install: the service
|
||||
// schedules the next run at the end of each pass.
|
||||
EnforcementService.start(applicationContext)
|
||||
result.success(true)
|
||||
}
|
||||
"cancelEnforcement" -> {
|
||||
EnforcementScheduler(applicationContext).cancel()
|
||||
result.success(true)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,199 @@
|
||||
package com.kuhy.focus_owner
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Mirrors `test/enforcement_test.dart` case for case.
|
||||
*
|
||||
* The Kotlin decision layer exists because a background Service has no Flutter
|
||||
* engine. That duplication is only safe if the two implementations are pinned
|
||||
* to the same expectations, so these tests deliberately restate the Dart suite
|
||||
* rather than testing something adjacent. A behaviour that changes on one side
|
||||
* and not the other fails here.
|
||||
*/
|
||||
class EnforcementDecisionTest {
|
||||
|
||||
private val homeLat = 52.2297
|
||||
private val homeLon = 21.0122
|
||||
private val metresPerDegreeLat = 111_320.0
|
||||
|
||||
private fun policy(withCoordinates: Boolean = true, curfew: String? = """{"start":"23:00","end":"05:00"}""") =
|
||||
FocusPolicy.parse(
|
||||
"""
|
||||
{
|
||||
"schema_version": 1,
|
||||
"home": {
|
||||
"latitude": ${if (withCoordinates) homeLat else "null"},
|
||||
"longitude": ${if (withCoordinates) homeLon else "null"},
|
||||
"radius_m": 150.0,
|
||||
"hysteresis_m": 30.0
|
||||
},
|
||||
"curfew": ${curfew ?: "null"},
|
||||
"launcher_package": "com.launcher",
|
||||
"allowed_packages": ["com.launcher","pl.mbank","com.discord","com.google.android.youtube"],
|
||||
"night_allowed_packages": ["com.launcher","pl.mbank"],
|
||||
"never_disable_prefixes": ["com.android.settings"],
|
||||
"workout_unblock_domains": ["youtube.com","googlevideo.com"],
|
||||
"browser_packages": []
|
||||
}
|
||||
""".trimIndent(),
|
||||
)
|
||||
|
||||
private val installed = setOf(
|
||||
"com.launcher",
|
||||
"pl.mbank",
|
||||
"com.discord",
|
||||
"com.google.android.youtube",
|
||||
"com.evil",
|
||||
"com.android.settings",
|
||||
)
|
||||
|
||||
private fun latOffset(metres: Double) = homeLat + metres / metresPerDegreeLat
|
||||
|
||||
@Test
|
||||
fun `away from home hides nothing and shows everything`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(5000.0), homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.AWAY, decision.reason)
|
||||
assertTrue(decision.packagesToHide.isEmpty())
|
||||
assertEquals(installed, decision.packagesToShow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `at home only non-allowlisted apps are hidden`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60, homeLat, homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.AT_HOME, decision.reason)
|
||||
assertEquals(setOf("com.evil"), decision.packagesToHide)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `protected packages and the launcher are never hidden`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 23 * 60 + 30, homeLat, homeLon),
|
||||
)
|
||||
assertTrue("com.android.settings" in decision.packagesToShow)
|
||||
assertTrue("com.launcher" in decision.packagesToShow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `curfew narrows the allowlist`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 23 * 60 + 30, homeLat, homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.CURFEW, decision.reason)
|
||||
assertTrue("com.discord" in decision.packagesToHide)
|
||||
assertTrue("pl.mbank" in decision.packagesToShow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `curfew wraps past midnight`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 3 * 60, homeLat, homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.CURFEW, decision.reason)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `after curfew the day list applies again`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 6 * 60, homeLat, homeLon),
|
||||
)
|
||||
assertEquals(EnforcementReason.AT_HOME, decision.reason)
|
||||
assertTrue("com.discord" in decision.packagesToShow)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hysteresis keeps the boundary from flapping`() {
|
||||
// 160m: outside the 150m radius, inside radius+hysteresis (180m).
|
||||
val arriving = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(160.0), homeLon, currentlyEnforcing = false),
|
||||
)
|
||||
val leaving = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(160.0), homeLon, currentlyEnforcing = true),
|
||||
)
|
||||
assertEquals(EnforcementReason.AWAY, arriving.reason)
|
||||
assertEquals(EnforcementReason.AT_HOME, leaving.reason)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown location enforces rather than releasing`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60),
|
||||
)
|
||||
assertEquals(EnforcementReason.LOCATION_UNKNOWN, decision.reason)
|
||||
assertTrue("com.evil" in decision.packagesToHide)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `redacted coordinates still enforce`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(withCoordinates = false),
|
||||
EnforcementInputs(installed, 12 * 60, latOffset(5000.0), homeLon),
|
||||
)
|
||||
assertTrue("com.evil" in decision.packagesToHide)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `workout releases youtube and nothing else`() {
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(
|
||||
installed,
|
||||
23 * 60 + 30,
|
||||
homeLat,
|
||||
homeLon,
|
||||
workoutActive = true,
|
||||
),
|
||||
)
|
||||
assertEquals(EnforcementReason.WORKOUT, decision.reason)
|
||||
assertTrue("com.google.android.youtube" in decision.packagesToShow)
|
||||
assertTrue("com.discord" in decision.packagesToHide)
|
||||
assertTrue("com.evil" in decision.packagesToHide)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hide and show partition the installed set`() {
|
||||
// packagesToShow is the complete allowed set, never a delta, so a
|
||||
// missed run self-repairs on the next one.
|
||||
val decision = EnforcementDecision.evaluate(
|
||||
policy(),
|
||||
EnforcementInputs(installed, 12 * 60, homeLat, homeLon),
|
||||
)
|
||||
assertEquals(installed, decision.packagesToHide + decision.packagesToShow)
|
||||
assertTrue(decision.packagesToHide.intersect(decision.packagesToShow).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unknown schema version is rejected`() {
|
||||
val thrown = try {
|
||||
FocusPolicy.parse("""{"schema_version": 999, "home": {}}""")
|
||||
false
|
||||
} catch (_: PolicyFormatException) {
|
||||
true
|
||||
}
|
||||
assertTrue("expected PolicyFormatException", thrown)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `prefix protection matches whole labels only`() {
|
||||
val p = policy()
|
||||
assertTrue(p.isProtected("com.android.settings"))
|
||||
assertTrue(p.isProtected("com.android.settings.sub"))
|
||||
assertFalse(p.isProtected("com.android.settingsomething"))
|
||||
}
|
||||
}
|
||||
@ -49,6 +49,18 @@ class DevicePolicy {
|
||||
return DevicePolicyStatus.fromMap(result!);
|
||||
}
|
||||
|
||||
/// Runs one enforcement pass now and arms the schedule.
|
||||
///
|
||||
/// The service schedules the following run at the end of each pass, so this
|
||||
/// is also how the chain is started on a device that has not rebooted since
|
||||
/// the app was installed.
|
||||
Future<bool> runEnforcementNow() async =>
|
||||
await channel.invokeMethod<bool>('runEnforcementNow') ?? false;
|
||||
|
||||
/// Cancels any pending scheduled evaluation.
|
||||
Future<bool> cancelEnforcement() async =>
|
||||
await channel.invokeMethod<bool>('cancelEnforcement') ?? false;
|
||||
|
||||
/// Relinquishes device ownership without wiping the device.
|
||||
///
|
||||
/// This is the escape hatch. It is deliberately reachable from the app's
|
||||
|
||||
@ -111,6 +111,22 @@ class _StatusPageState extends State<StatusPage> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runNow() async {
|
||||
setState(() => _busy = true);
|
||||
final started = await widget.policy.runEnforcementNow();
|
||||
if (!mounted) return;
|
||||
setState(() => _busy = false);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
started
|
||||
? 'Enforcement run started; schedule armed'
|
||||
: 'Could not start enforcement',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _release() async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
@ -164,6 +180,7 @@ class _StatusPageState extends State<StatusPage> {
|
||||
policyError: _policyError,
|
||||
busy: _busy,
|
||||
onRelease: _release,
|
||||
onRunNow: _runNow,
|
||||
);
|
||||
} else {
|
||||
body = const Center(child: CircularProgressIndicator());
|
||||
@ -194,6 +211,7 @@ class _StatusBody extends StatelessWidget {
|
||||
required this.policyError,
|
||||
required this.busy,
|
||||
required this.onRelease,
|
||||
required this.onRunNow,
|
||||
});
|
||||
|
||||
final DevicePolicyStatus status;
|
||||
@ -201,6 +219,7 @@ class _StatusBody extends StatelessWidget {
|
||||
final String? policyError;
|
||||
final bool busy;
|
||||
final Future<void> Function() onRelease;
|
||||
final Future<void> Function() onRunNow;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@ -248,6 +267,11 @@ class _StatusBody extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
const SizedBox(height: _kGap * 2),
|
||||
OutlinedButton(
|
||||
onPressed: busy ? null : onRunNow,
|
||||
child: const Text('Run enforcement now'),
|
||||
),
|
||||
const SizedBox(height: _kGap),
|
||||
if (status.isDeviceOwner)
|
||||
FilledButton(
|
||||
onPressed: busy ? null : onRelease,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user