Выпуск WDTT Plus v15
This commit is contained in:
1 parent
3d2c277b06
commit
947551c176
65 files changed
+12788
-1338
No files matched your search
@@ -50,4 +50,141 @@ class DeviceCompatibilityTest {
|
||||
directory.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeWorkersDoNotHideConfirmedTrafficFailure() {
|
||||
val item = tunnelHealthItem(
|
||||
running = true,
|
||||
activeWorkers = 36,
|
||||
issue = null,
|
||||
confirmedNetworkFailure = true,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertTrue(item.status.contains("нет ответа"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recoveryIssueDoesNotLookHealthyWhileWorkersRemainActive() {
|
||||
val item = tunnelHealthItem(
|
||||
running = true,
|
||||
activeWorkers = 36,
|
||||
issue = ConnectionIssue("Перезапускаю VPN", "Ожидается восстановление"),
|
||||
confirmedNetworkFailure = false,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertEquals("обнаружена проблема", item.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeWorkersWithoutFailureRemainHealthy() {
|
||||
val item = tunnelHealthItem(
|
||||
running = true,
|
||||
activeWorkers = 9,
|
||||
issue = null,
|
||||
confirmedNetworkFailure = false,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Ok, item.severity)
|
||||
assertEquals("активно", item.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun timedSleepResumeWarnsWhenAndroidBatteryRestrictionsRemain() {
|
||||
val item = sleepBatteryModeItem(
|
||||
enabled = true,
|
||||
mode = SleepBatteryMode.TIMED_PAUSE,
|
||||
pauseDelayMinutes = 5,
|
||||
resumeDelayMinutes = 60,
|
||||
runtime = SleepBatteryRuntimeState(SleepBatteryRuntimePhase.WAITING_TO_RESUME, 123L),
|
||||
notificationsGranted = true,
|
||||
batteryOptimizationsIgnored = false,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertEquals(DeviceCheckAction.BatterySettings, item.action)
|
||||
assertTrue(item.status.contains("1 ч"))
|
||||
assertTrue(item.details.contains("ожидается таймер"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun zeroTimedSleepModeExplainsThatVpnStaysActive() {
|
||||
val item = sleepBatteryModeItem(
|
||||
enabled = true,
|
||||
mode = SleepBatteryMode.TIMED_PAUSE,
|
||||
pauseDelayMinutes = 5,
|
||||
resumeDelayMinutes = 0,
|
||||
runtime = SleepBatteryRuntimeState(),
|
||||
notificationsGranted = true,
|
||||
batteryOptimizationsIgnored = false,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Ok, item.severity)
|
||||
assertTrue(item.status.contains("VPN остаётся активным"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trustedWifiWarnsWhenEnabledWithoutSavedNetworks() {
|
||||
val item = trustedWifiModeItem(
|
||||
enabled = true,
|
||||
savedNetworkCount = 0,
|
||||
waiting = false,
|
||||
waitingSsid = "",
|
||||
accessProblem = null,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertTrue(item.status.contains("сети не сохранены"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trustedWifiWaitingIsReportedAsIntentionalVpnPause() {
|
||||
val item = trustedWifiModeItem(
|
||||
enabled = true,
|
||||
savedNetworkCount = 2,
|
||||
waiting = true,
|
||||
waitingSsid = "Home",
|
||||
accessProblem = null,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Ok, item.severity)
|
||||
assertTrue(item.details.contains("намеренно выключен"))
|
||||
assertTrue(item.details.contains("Home"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyWhitelistWarnsThatItBlocksApplicationTraffic() {
|
||||
val item = vpnRoutingModeItem(
|
||||
snapshot = VpnRoutingSettingsSnapshot(
|
||||
profileIndex = 1,
|
||||
isWhitelist = true,
|
||||
appPackages = "",
|
||||
addressRules = emptyList(),
|
||||
),
|
||||
installedPackages = setOf("com.wdtt.plus"),
|
||||
ownPackageName = "com.wdtt.plus",
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Warning, item.severity)
|
||||
assertTrue(item.details.contains("не пропускает"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addressOnlyWhitelistIsRecognizedAsValid() {
|
||||
val item = vpnRoutingModeItem(
|
||||
snapshot = VpnRoutingSettingsSnapshot(
|
||||
profileIndex = 0,
|
||||
isWhitelist = true,
|
||||
appPackages = "",
|
||||
addressRules = listOf(VpnAddressRule(VpnAddressType.DOMAIN, "example.org")),
|
||||
),
|
||||
installedPackages = setOf("com.wdtt.plus"),
|
||||
ownPackageName = "com.wdtt.plus",
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Ok, item.severity)
|
||||
assertTrue(item.details.contains("ко всем приложениям"))
|
||||
assertTrue(item.status.contains("доменов: 1"))
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,22 @@ class ServerMigrationTest {
|
||||
assertEquals(14, latestServerMigrationLevel(14))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateFrom14To15RequiresServerMigration() {
|
||||
val result = resolveServerMigrationInitialization(
|
||||
currentVersionCode = 15,
|
||||
isUpdatedInstall = true,
|
||||
storedLastSeenAppVersionCode = 14,
|
||||
storedPendingLevel = 14,
|
||||
storedAcknowledgedLevel = 14,
|
||||
legacyAcknowledgedLevel = 5
|
||||
)
|
||||
|
||||
assertEquals(15, result.pendingLevel)
|
||||
assertEquals(14, result.acknowledgedLevel)
|
||||
assertEquals(15, latestServerMigrationLevel(15))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stateSeparatesReadNoticeFromCompletedDeployment() {
|
||||
val state = ServerMigrationState(
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import com.wdtt.plus.ui.adjustSleepTimerHours
|
||||
import com.wdtt.plus.ui.formatSleepTimerDuration
|
||||
import com.wdtt.plus.ui.replaceSleepTimerMinuteComponent
|
||||
import com.wdtt.plus.ui.sleepBatteryModeDiagnosticText
|
||||
import com.wdtt.plus.ui.sleepBatteryRuntimeDiagnosticText
|
||||
import com.wdtt.plus.ui.updateSleepTimerFromDialDrag
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SleepTimerPolicyTest {
|
||||
@Test
|
||||
fun shortPauseAndResumeTimersKeepOnlyABoundedWakeGuard() {
|
||||
assertEquals(
|
||||
70_000L,
|
||||
shortSleepResumeGuardDurationMs(deadlineWallMs = 160_000L, nowMs = 100_000L),
|
||||
)
|
||||
assertEquals(
|
||||
null,
|
||||
shortSleepResumeGuardDurationMs(
|
||||
deadlineWallMs = 100_000L + 2 * 60_000L + 1L,
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
null,
|
||||
shortSleepResumeGuardDurationMs(deadlineWallMs = 100_000L, nowMs = 100_000L),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun timerBoundsAreAlwaysEnforced() {
|
||||
assertEquals(5, DEFAULT_SLEEP_PAUSE_DELAY_MINUTES)
|
||||
assertEquals(0, normalizeSleepPauseDelayMinutes(-1))
|
||||
assertEquals(0, normalizeSleepPauseDelayMinutes(0))
|
||||
assertEquals(24 * 60, normalizeSleepPauseDelayMinutes(Int.MAX_VALUE))
|
||||
assertEquals(90, adjustSleepTimerHours(totalMinutes = 30, hoursDelta = 1))
|
||||
assertEquals(0, adjustSleepTimerHours(totalMinutes = 30, hoursDelta = -1))
|
||||
assertEquals(0, adjustSleepTimerHours(totalMinutes = 60, hoursDelta = -1))
|
||||
assertEquals(24 * 60, adjustSleepTimerHours(totalMinutes = 23 * 60 + 30, hoursDelta = 1))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dialReplacesMinutesAndCountsFullTurnsAsHours() {
|
||||
assertEquals(165, replaceSleepTimerMinuteComponent(totalMinutes = 125, minute = 45))
|
||||
assertEquals(
|
||||
60,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 59,
|
||||
previousMinute = 59,
|
||||
nextMinute = 0,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
59,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 60,
|
||||
previousMinute = 0,
|
||||
nextMinute = 59,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
24 * 60,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 24 * 60,
|
||||
previousMinute = 0,
|
||||
nextMinute = 1,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
24 * 60 - 1,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 24 * 60,
|
||||
previousMinute = 0,
|
||||
nextMinute = 59,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
0,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 0,
|
||||
previousMinute = 0,
|
||||
nextMinute = 59,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
0,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 0,
|
||||
previousMinute = 59,
|
||||
nextMinute = 58,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
1,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 0,
|
||||
previousMinute = 58,
|
||||
nextMinute = 59,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
24 * 60,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 24 * 60,
|
||||
previousMinute = 1,
|
||||
nextMinute = 2,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
24 * 60 - 1,
|
||||
updateSleepTimerFromDialDrag(
|
||||
totalMinutes = 24 * 60,
|
||||
previousMinute = 2,
|
||||
nextMinute = 1,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun durationUsesCompactRussianLabels() {
|
||||
assertEquals("0 мин", formatSleepTimerDuration(0))
|
||||
assertEquals("2 мин", formatSleepTimerDuration(2))
|
||||
assertEquals("1 ч", formatSleepTimerDuration(60))
|
||||
assertEquals("2 ч 5 мин", formatSleepTimerDuration(125))
|
||||
assertEquals("24 ч", formatSleepTimerDuration(24 * 60))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sleepBatteryDiagnosticsDescribeConfiguredModeAndRuntime() {
|
||||
assertEquals(
|
||||
"отключить VPN после задержки до включения экрана",
|
||||
sleepBatteryModeDiagnosticText(SleepBatteryMode.DELAYED_PAUSE),
|
||||
)
|
||||
assertEquals(
|
||||
"VPN отключён, ожидается включение по таймеру, осталось 2 мин",
|
||||
sleepBatteryRuntimeDiagnosticText(
|
||||
runtime = SleepBatteryRuntimeState(
|
||||
phase = SleepBatteryRuntimePhase.WAITING_TO_RESUME,
|
||||
deadlineMs = 220_000L,
|
||||
),
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sleepModesHaveStablePersistedValuesAndSafeFallback() {
|
||||
assertEquals(
|
||||
SleepBatteryMode.DELAYED_PAUSE,
|
||||
SleepBatteryMode.fromStoredValue("delayed_pause"),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryMode.TIMED_PAUSE,
|
||||
SleepBatteryMode.fromStoredValue("timed_pause"),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryMode.DELAYED_PAUSE,
|
||||
SleepBatteryMode.fromStoredValue("unknown"),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryPlan(pauseAfterMinutes = 5, resumeAfterMinutes = null),
|
||||
buildSleepBatteryPlan(
|
||||
mode = SleepBatteryMode.DELAYED_PAUSE,
|
||||
pauseDelayMinutes = 5,
|
||||
resumeDelayMinutes = 90,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryPlan(pauseAfterMinutes = 0, resumeAfterMinutes = 90),
|
||||
buildSleepBatteryPlan(
|
||||
mode = SleepBatteryMode.TIMED_PAUSE,
|
||||
pauseDelayMinutes = 5,
|
||||
resumeDelayMinutes = 90,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun screenOnAlwaysDisarmsTheCurrentSleepCycle() {
|
||||
assertEquals(
|
||||
SleepBatteryRuntimePhase.IDLE,
|
||||
sleepRuntimePhaseAfterPauseAttempt(deviceInteractive = true, paused = true),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryRuntimePhase.IDLE,
|
||||
sleepRuntimePhaseAfterResume(deviceInteractive = true),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wakeNotificationExplainsWhatTheSleepTimerDid() {
|
||||
assertEquals(
|
||||
"Таймер отменён: экран включён до отключения VPN",
|
||||
sleepWakeNotificationText(SleepBatteryRuntimePhase.WAITING_TO_PAUSE),
|
||||
)
|
||||
assertEquals(
|
||||
"VPN включается после сна · во сне был выключен",
|
||||
sleepWakeNotificationText(SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON),
|
||||
)
|
||||
assertEquals(
|
||||
"VPN включается раньше таймера · экран включён",
|
||||
sleepWakeNotificationText(SleepBatteryRuntimePhase.WAITING_TO_RESUME),
|
||||
)
|
||||
assertEquals(
|
||||
"VPN был включён по таймеру во время сна",
|
||||
sleepWakeNotificationText(SleepBatteryRuntimePhase.RESUMED_UNTIL_SCREEN_ON),
|
||||
)
|
||||
assertEquals(null, sleepWakeNotificationText(SleepBatteryRuntimePhase.IDLE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completedActionsAreNotRearmedBeforeTheNextScreenOff() {
|
||||
assertEquals(
|
||||
SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON,
|
||||
sleepRuntimePhaseAfterPauseAttempt(deviceInteractive = false, paused = true),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryRuntimePhase.RESUMED_UNTIL_SCREEN_ON,
|
||||
sleepRuntimePhaseAfterPauseAttempt(deviceInteractive = false, paused = false),
|
||||
)
|
||||
assertEquals(
|
||||
SleepBatteryRuntimePhase.RESUMED_UNTIL_SCREEN_ON,
|
||||
sleepRuntimePhaseAfterResume(deviceInteractive = false),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun screenOnDoesNotRestartVpnWhileDelayedPauseIsOnlyWaiting() {
|
||||
assertEquals(
|
||||
SleepResumeAction.KEEP_CURRENT_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.SCREEN_ON,
|
||||
runtimePhase = SleepBatteryRuntimePhase.WAITING_TO_PAUSE,
|
||||
tunnelRunning = true,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun screenOnResumesOnlyACommittedSleepPause() {
|
||||
assertEquals(
|
||||
SleepResumeAction.KEEP_CURRENT_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.SCREEN_ON,
|
||||
runtimePhase = SleepBatteryRuntimePhase.IDLE,
|
||||
tunnelRunning = true,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SleepResumeAction.RESUME_PAUSED_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.SCREEN_ON,
|
||||
runtimePhase = SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON,
|
||||
tunnelRunning = true,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun timedResumeCannotBeReusedForAnotherSleepPhase() {
|
||||
assertEquals(
|
||||
SleepResumeAction.RESUME_PAUSED_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.TIMER,
|
||||
runtimePhase = SleepBatteryRuntimePhase.WAITING_TO_RESUME,
|
||||
tunnelRunning = true,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SleepResumeAction.KEEP_CURRENT_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.TIMER,
|
||||
runtimePhase = SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON,
|
||||
tunnelRunning = true,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun timerRestoresACommittedPauseAfterAndroidRecreatesTheProcess() {
|
||||
assertEquals(
|
||||
SleepResumeAction.RESTORE_PAUSED_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.TIMER,
|
||||
runtimePhase = SleepBatteryRuntimePhase.WAITING_TO_RESUME,
|
||||
tunnelRunning = false,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
SleepResumeAction.KEEP_CURRENT_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.TIMER,
|
||||
runtimePhase = SleepBatteryRuntimePhase.WAITING_TO_RESUME,
|
||||
tunnelRunning = false,
|
||||
blockedByAnotherPolicy = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun alarmFailureRestoresACommittedPauseInsteadOfLeavingVpnOff() {
|
||||
assertEquals(
|
||||
SleepResumeAction.RESTORE_PAUSED_TUNNEL,
|
||||
decideSleepResumeAction(
|
||||
trigger = SleepResumeTrigger.FAILSAFE,
|
||||
runtimePhase = SleepBatteryRuntimePhase.WAITING_TO_RESUME,
|
||||
tunnelRunning = false,
|
||||
blockedByAnotherPolicy = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun runtimePhasesHaveStablePersistedValuesAndSafeFallback() {
|
||||
SleepBatteryRuntimePhase.entries.forEach { phase ->
|
||||
assertEquals(phase, SleepBatteryRuntimePhase.fromStoredValue(phase.storedValue))
|
||||
}
|
||||
assertEquals(
|
||||
SleepBatteryRuntimePhase.IDLE,
|
||||
SleepBatteryRuntimePhase.fromStoredValue("unknown"),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,9 @@ class TransferCodecTest {
|
||||
vkHashes = "hash-value",
|
||||
profileName = "Домашний сервер",
|
||||
workersPerHash = 24,
|
||||
noDns = true
|
||||
noDns = true,
|
||||
vpnDnsSelectionId = "quad9",
|
||||
vpnDnsStored = true,
|
||||
)
|
||||
assertEquals(
|
||||
listOf(
|
||||
@@ -170,11 +172,14 @@ class TransferCodecTest {
|
||||
"--vk-hashes", "hash-value",
|
||||
"--profile-name", "Домашний сервер",
|
||||
"--workers", "24",
|
||||
"--no-dns"
|
||||
"--no-dns",
|
||||
"--vpn-dns-selection", "quad9",
|
||||
"--vpn-dns-custom", "",
|
||||
),
|
||||
buildAdminProfilePatchArgs(custom)
|
||||
)
|
||||
assertTrue(hasMeaningfulAdminProfileFields(custom))
|
||||
assertFalse(buildAdminProfilePatchArgs(custom, includeVpnDns = false).contains("--vpn-dns-selection"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -318,4 +323,28 @@ class TransferCodecTest {
|
||||
|
||||
WdttTransferCodec.decryptAdminSettings(encrypted, "wrong-password".toCharArray())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverBackup_isEncryptedAndUsesSeparateEnvelopeKind() {
|
||||
val plain = JSONObject()
|
||||
.put("format", "wdtt-server-backup")
|
||||
.put("version", 2)
|
||||
.put("secret", "owner-and-client-passwords")
|
||||
.toString()
|
||||
val password = "отдельный пароль 123".toCharArray()
|
||||
|
||||
val encrypted = WdttTransferCodec.encryptServerBackup(plain, password)
|
||||
|
||||
assertTrue(WdttTransferCodec.isEncryptedServerBackup(encrypted))
|
||||
assertFalse(WdttTransferCodec.isAdminTransfer(encrypted))
|
||||
assertFalse(encrypted.contains("owner-and-client-passwords"))
|
||||
assertEquals(plain, WdttTransferCodec.decryptServerBackup(encrypted, password))
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun serverBackup_rejectsWrongPassword() {
|
||||
val encrypted = WdttTransferCodec.encryptServerBackup("{}", "correct-password".toCharArray())
|
||||
|
||||
WdttTransferCodec.decryptServerBackup(encrypted, "wrong-password".toCharArray())
|
||||
}
|
||||
}
|
||||
@@ -157,14 +157,14 @@ class TrustedWifiTest {
|
||||
|
||||
@Test
|
||||
fun `lost trusted wifi is not reused as validated resume network`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "home", validated = true, wifi = true)
|
||||
val networks = TrustedWifiResumeNetworkTracker<String>()
|
||||
networks.update(network = "home", internetCapable = true, validated = true, wifi = true)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
|
||||
networks.forgetWifi()
|
||||
assertFalse(networks.hasUsableNetwork())
|
||||
|
||||
networks.update(network = "cellular", validated = true, wifi = false)
|
||||
networks.update(network = "cellular", internetCapable = true, validated = true, wifi = false)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
|
||||
networks.lost("cellular")
|
||||
@@ -173,9 +173,9 @@ class TrustedWifiTest {
|
||||
|
||||
@Test
|
||||
fun `trusted wifi loss preserves an already validated cellular network`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "home", validated = true, wifi = true)
|
||||
networks.update(network = "cellular", validated = true, wifi = false)
|
||||
val networks = TrustedWifiResumeNetworkTracker<String>()
|
||||
networks.update(network = "home", internetCapable = true, validated = true, wifi = true)
|
||||
networks.update(network = "cellular", internetCapable = true, validated = true, wifi = false)
|
||||
|
||||
networks.forgetWifi()
|
||||
|
||||
@@ -183,20 +183,62 @@ class TrustedWifiTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `internet capability without validation is not enough to resume`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "cellular", validated = false, wifi = false)
|
||||
fun `limited cellular network can resume after trusted wifi`() {
|
||||
val networks = TrustedWifiResumeNetworkTracker<String>()
|
||||
networks.update(network = "cellular", internetCapable = true, validated = false, wifi = false)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
|
||||
networks.update(network = "cellular", internetCapable = false, validated = false, wifi = false)
|
||||
assertFalse(networks.hasUsableNetwork())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unvalidated wifi cannot resume through a captive portal`() {
|
||||
val networks = TrustedWifiResumeNetworkTracker<String>()
|
||||
networks.update(network = "hotel", internetCapable = true, validated = false, wifi = true)
|
||||
assertFalse(networks.hasUsableNetwork())
|
||||
|
||||
networks.update(network = "cellular", validated = true, wifi = false)
|
||||
networks.update(network = "hotel", internetCapable = true, validated = true, wifi = true)
|
||||
assertTrue(networks.hasUsableNetwork())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `trusted wifi resume fallback accepts validated networks and limited cellular only`() {
|
||||
assertTrue(
|
||||
isUsableTrustedWifiResumeNetwork(
|
||||
internetCapable = true,
|
||||
validated = true,
|
||||
wifi = true,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
isUsableTrustedWifiResumeNetwork(
|
||||
internetCapable = true,
|
||||
validated = false,
|
||||
wifi = true,
|
||||
)
|
||||
)
|
||||
assertTrue(
|
||||
isUsableTrustedWifiResumeNetwork(
|
||||
internetCapable = true,
|
||||
validated = false,
|
||||
wifi = false,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
isUsableTrustedWifiResumeNetwork(
|
||||
internetCapable = false,
|
||||
validated = true,
|
||||
wifi = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `losing trusted wifi does not discard a newly validated untrusted wifi`() {
|
||||
val networks = TrustedWifiValidatedNetworkTracker<String>()
|
||||
networks.update(network = "home", validated = true, wifi = true)
|
||||
networks.update(network = "office", validated = true, wifi = true)
|
||||
val networks = TrustedWifiResumeNetworkTracker<String>()
|
||||
networks.update(network = "home", internetCapable = true, validated = true, wifi = true)
|
||||
networks.update(network = "office", internetCapable = true, validated = true, wifi = true)
|
||||
|
||||
networks.lost("home")
|
||||
|
||||
|
||||
@@ -2,8 +2,127 @@ package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.util.TimeZone
|
||||
|
||||
class TunnelRecoveryPolicyTest {
|
||||
@Test
|
||||
fun vkCallsFloodCooldownSurvivesFastNativeRestarts() {
|
||||
assertEquals(
|
||||
false,
|
||||
shouldUseVkCallsPreflight(
|
||||
enabledByUser = true,
|
||||
cooldownUntilMs = 160_000L,
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldUseVkCallsPreflight(
|
||||
enabledByUser = true,
|
||||
cooldownUntilMs = 160_000L,
|
||||
nowMs = 160_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldUseVkCallsPreflight(
|
||||
enabledByUser = false,
|
||||
cooldownUntilMs = 0L,
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun vkCallsPreflightFailuresKeepTheirCooldownAcrossNativeRestarts() {
|
||||
assertEquals(60_000L, vkCallsPreflightCooldownForLog("[VKCalls] VK временно ограничил анонимный вход"))
|
||||
assertEquals(120_000L, vkCallsPreflightCooldownForLog("[VKCalls] VKCalls запросил CAPTCHA; временно не повторяем preflight"))
|
||||
assertEquals(45_000L, vkCallsPreflightCooldownForLog("[VKCalls] preflight не сработал: timeout; временно не повторяем его"))
|
||||
assertEquals(0L, vkCallsPreflightCooldownForLog("[VKCalls] TURN credentials получены"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staleVkCallsCooldownIsNeverRestoredAfterTheAppRestarts() {
|
||||
assertEquals(
|
||||
160_000L,
|
||||
boundedVkCallsPreflightCooldownUntil(
|
||||
untilMs = 160_000L,
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
0L,
|
||||
boundedVkCallsPreflightCooldownUntil(
|
||||
untilMs = 220_001L,
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
0L,
|
||||
boundedVkCallsPreflightCooldownUntil(
|
||||
untilMs = 100_000L,
|
||||
nowMs = 100_000L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sleepLogsIncludePhoneTimeAfterTheFirstEventPhrase() {
|
||||
val utc = TimeZone.getTimeZone("UTC")
|
||||
val nowMs = 56_342_000L
|
||||
|
||||
assertEquals(
|
||||
"[СОН] Экран включён в 15:39:02. Проверяем VPN.",
|
||||
addPhoneTimeToSleepLog(
|
||||
message = "[СОН] Экран включён. Проверяем VPN.",
|
||||
nowMs = nowMs,
|
||||
timeZone = utc,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"[СОН] Устройство проснулось в 15:39:02; ждём стабилизации.",
|
||||
addPhoneTimeToSleepLog(
|
||||
message = "[СОН] Устройство проснулось; ждём стабилизации.",
|
||||
nowMs = nowMs,
|
||||
timeZone = utc,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
"[СЕТЬ] Сеть изменилась.",
|
||||
addPhoneTimeToSleepLog(
|
||||
message = "[СЕТЬ] Сеть изменилась.",
|
||||
nowMs = nowMs,
|
||||
timeZone = utc,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun timerResumeRequiresAnActualServerOrUserTrafficResponse() {
|
||||
assertEquals(
|
||||
true,
|
||||
hasFreshTransportPath(
|
||||
running = true,
|
||||
activeWorkers = 36,
|
||||
lastInboundTrafficAtMs = 0L,
|
||||
lastKeepaliveResponseAtMs = 120_000L,
|
||||
sinceMs = 100_000L,
|
||||
nowMs = 150_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
hasFreshTransportPath(
|
||||
running = true,
|
||||
activeWorkers = 36,
|
||||
lastInboundTrafficAtMs = 0L,
|
||||
lastKeepaliveResponseAtMs = 0L,
|
||||
sinceMs = 100_000L,
|
||||
nowMs = 175_000L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstRecoveryIsTransportOnly() {
|
||||
assertEquals(
|
||||
@@ -36,6 +155,7 @@ class TunnelRecoveryPolicyTest {
|
||||
deviceInteractive = false,
|
||||
startupWindow = false,
|
||||
captchaActive = false,
|
||||
vpnSlotYieldRequested = false,
|
||||
missingForMs = 120_000L,
|
||||
validatedNetworkAvailable = true,
|
||||
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||
@@ -47,6 +167,7 @@ class TunnelRecoveryPolicyTest {
|
||||
deviceInteractive = true,
|
||||
startupWindow = false,
|
||||
captchaActive = false,
|
||||
vpnSlotYieldRequested = false,
|
||||
missingForMs = 120_000L,
|
||||
validatedNetworkAvailable = false,
|
||||
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||
@@ -58,6 +179,7 @@ class TunnelRecoveryPolicyTest {
|
||||
deviceInteractive = true,
|
||||
startupWindow = false,
|
||||
captchaActive = false,
|
||||
vpnSlotYieldRequested = false,
|
||||
missingForMs = 120_000L,
|
||||
validatedNetworkAvailable = true,
|
||||
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||
@@ -69,6 +191,7 @@ class TunnelRecoveryPolicyTest {
|
||||
deviceInteractive = true,
|
||||
startupWindow = false,
|
||||
captchaActive = false,
|
||||
vpnSlotYieldRequested = false,
|
||||
missingForMs = 30_000L,
|
||||
validatedNetworkAvailable = true,
|
||||
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||
@@ -80,6 +203,7 @@ class TunnelRecoveryPolicyTest {
|
||||
deviceInteractive = true,
|
||||
startupWindow = false,
|
||||
captchaActive = false,
|
||||
vpnSlotYieldRequested = false,
|
||||
missingForMs = 120_000L,
|
||||
validatedNetworkAvailable = true,
|
||||
sinceLastAttemptMs = 60_000L,
|
||||
@@ -87,6 +211,66 @@ class TunnelRecoveryPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun externalVpnDropYieldsSlotInsteadOfRecoveringInterface() {
|
||||
assertEquals(
|
||||
false,
|
||||
shouldAttemptVpnInterfaceRecovery(
|
||||
deviceInteractive = true,
|
||||
startupWindow = false,
|
||||
captchaActive = false,
|
||||
vpnSlotYieldRequested = true,
|
||||
missingForMs = 120_000L,
|
||||
validatedNetworkAvailable = true,
|
||||
sinceLastAttemptMs = Long.MAX_VALUE,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldYieldVpnSlot(
|
||||
vpnSlotYieldRequested = true,
|
||||
tunnelRunning = true,
|
||||
stopRequested = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldYieldVpnSlot(
|
||||
vpnSlotYieldRequested = false,
|
||||
tunnelRunning = true,
|
||||
stopRequested = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldYieldVpnSlot(
|
||||
vpnSlotYieldRequested = true,
|
||||
tunnelRunning = true,
|
||||
stopRequested = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldYieldVpnSlot(
|
||||
vpnSlotYieldRequested = true,
|
||||
tunnelRunning = false,
|
||||
stopRequested = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldBlockVpnStart(
|
||||
vpnSlotYieldRequested = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldBlockVpnStart(
|
||||
vpnSlotYieldRequested = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sleepBatteryModePausesOnlyAnActiveTunnel() {
|
||||
assertEquals(
|
||||
@@ -163,14 +347,208 @@ class TunnelRecoveryPolicyTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshActiveHeartbeatDoesNotRequireTrafficGrowth() {
|
||||
fun networkReturnNeverResumesATunnelPausedBySleepPolicy() {
|
||||
assertEquals(
|
||||
true,
|
||||
shouldResumeVpnAfterNetworkReturn(
|
||||
networkPausedByLoss = true,
|
||||
sleepPausedByPolicy = false,
|
||||
tunnelRunning = true,
|
||||
usableNetworkAvailable = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldResumeVpnAfterNetworkReturn(
|
||||
networkPausedByLoss = true,
|
||||
sleepPausedByPolicy = true,
|
||||
tunnelRunning = true,
|
||||
usableNetworkAvailable = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldResumeVpnAfterNetworkReturn(
|
||||
networkPausedByLoss = false,
|
||||
sleepPausedByPolicy = false,
|
||||
tunnelRunning = true,
|
||||
usableNetworkAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun validatedNetworkTransitionHandlesBothCallbackOrders() {
|
||||
assertEquals(
|
||||
ValidatedNetworkTransition.HANDOVER,
|
||||
classifyValidatedNetworkTransition(
|
||||
previousNetwork = "wifi",
|
||||
currentNetwork = "cellular",
|
||||
previousNetworkWasLost = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
ValidatedNetworkTransition.HANDOVER,
|
||||
classifyValidatedNetworkTransition(
|
||||
previousNetwork = null,
|
||||
currentNetwork = "cellular",
|
||||
previousNetworkWasLost = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
ValidatedNetworkTransition.INITIAL,
|
||||
classifyValidatedNetworkTransition(
|
||||
previousNetwork = null,
|
||||
currentNetwork = "cellular",
|
||||
previousNetworkWasLost = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
ValidatedNetworkTransition.UNCHANGED,
|
||||
classifyValidatedNetworkTransition(
|
||||
previousNetwork = "cellular",
|
||||
currentNetwork = "cellular",
|
||||
previousNetworkWasLost = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun availableNetworkCanRecoverHandoverWithoutAndroidValidation() {
|
||||
assertEquals(
|
||||
true,
|
||||
shouldScheduleAvailableNetworkHandover(
|
||||
previousNetworkWasLost = true,
|
||||
availableRealNetworkCount = 1,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldScheduleAvailableNetworkHandover(
|
||||
previousNetworkWasLost = true,
|
||||
availableRealNetworkCount = 0,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldScheduleAvailableNetworkHandover(
|
||||
previousNetworkWasLost = false,
|
||||
availableRealNetworkCount = 1,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handoverTrackingIsLimitedToTheActiveTunnelAndDoesNotExtendPendingCheck() {
|
||||
assertEquals(
|
||||
true,
|
||||
shouldTrackUnderlyingNetworkLoss(
|
||||
tunnelRunning = true,
|
||||
tunnelPaused = false,
|
||||
trustedWifiWaiting = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldTrackUnderlyingNetworkLoss(
|
||||
tunnelRunning = false,
|
||||
tunnelPaused = false,
|
||||
trustedWifiWaiting = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldTrackUnderlyingNetworkLoss(
|
||||
tunnelRunning = true,
|
||||
tunnelPaused = true,
|
||||
trustedWifiWaiting = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldTrackUnderlyingNetworkLoss(
|
||||
tunnelRunning = true,
|
||||
tunnelPaused = false,
|
||||
trustedWifiWaiting = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldStartUnderlyingNetworkCheck(
|
||||
checkPending = true,
|
||||
currentJobActive = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldStartUnderlyingNetworkCheck(
|
||||
checkPending = true,
|
||||
currentJobActive = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
130_000L,
|
||||
updatedUnderlyingNetworkEvidenceSince(
|
||||
currentEvidenceSinceMs = 100_000L,
|
||||
networkEventAtMs = 130_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
130_000L,
|
||||
updatedUnderlyingNetworkEvidenceSince(
|
||||
currentEvidenceSinceMs = 130_000L,
|
||||
networkEventAtMs = 120_000L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handoverReconnectDoesNotOverlapOtherTunnelPolicies() {
|
||||
fun reconnectAllowed(
|
||||
tunnelRunning: Boolean = true,
|
||||
tunnelPaused: Boolean = false,
|
||||
trustedWifiWaiting: Boolean = false,
|
||||
sleepPausedByPolicy: Boolean = false,
|
||||
stopRequested: Boolean = false,
|
||||
interactiveAtSchedule: Boolean = true,
|
||||
deviceInteractive: Boolean = true,
|
||||
wakeRecoveryGraceActive: Boolean = false,
|
||||
realNetworkAvailable: Boolean = true,
|
||||
captchaActive: Boolean = false,
|
||||
): Boolean = shouldRunUnderlyingNetworkReconnect(
|
||||
tunnelRunning = tunnelRunning,
|
||||
tunnelPaused = tunnelPaused,
|
||||
trustedWifiWaiting = trustedWifiWaiting,
|
||||
sleepPausedByPolicy = sleepPausedByPolicy,
|
||||
stopRequested = stopRequested,
|
||||
interactiveAtSchedule = interactiveAtSchedule,
|
||||
deviceInteractive = deviceInteractive,
|
||||
wakeRecoveryGraceActive = wakeRecoveryGraceActive,
|
||||
realNetworkAvailable = realNetworkAvailable,
|
||||
captchaActive = captchaActive,
|
||||
)
|
||||
|
||||
assertEquals(true, reconnectAllowed())
|
||||
assertEquals(false, reconnectAllowed(tunnelRunning = false))
|
||||
assertEquals(false, reconnectAllowed(tunnelPaused = true))
|
||||
assertEquals(false, reconnectAllowed(trustedWifiWaiting = true))
|
||||
assertEquals(false, reconnectAllowed(sleepPausedByPolicy = true))
|
||||
assertEquals(false, reconnectAllowed(stopRequested = true))
|
||||
assertEquals(false, reconnectAllowed(interactiveAtSchedule = false))
|
||||
assertEquals(false, reconnectAllowed(deviceInteractive = false))
|
||||
assertEquals(false, reconnectAllowed(wakeRecoveryGraceActive = true))
|
||||
assertEquals(false, reconnectAllowed(realNetworkAvailable = false))
|
||||
assertEquals(false, reconnectAllowed(captchaActive = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun freshInboundTrafficConfirmsWakeRecovery() {
|
||||
assertEquals(
|
||||
true,
|
||||
hasFreshTransportHeartbeat(
|
||||
running = true,
|
||||
activeWorkers = 9,
|
||||
lastActiveAtMs = 120_000L,
|
||||
lastStatsAtMs = 120_000L,
|
||||
lastInboundTrafficAtMs = 120_000L,
|
||||
sinceMs = 100_000L,
|
||||
nowMs = 130_000L,
|
||||
),
|
||||
@@ -184,8 +562,7 @@ class TunnelRecoveryPolicyTest {
|
||||
hasFreshTransportHeartbeat(
|
||||
running = true,
|
||||
activeWorkers = 9,
|
||||
lastActiveAtMs = 90_000L,
|
||||
lastStatsAtMs = 90_000L,
|
||||
lastInboundTrafficAtMs = 90_000L,
|
||||
sinceMs = 100_000L,
|
||||
nowMs = 130_000L,
|
||||
),
|
||||
@@ -195,14 +572,122 @@ class TunnelRecoveryPolicyTest {
|
||||
hasFreshTransportHeartbeat(
|
||||
running = true,
|
||||
activeWorkers = 0,
|
||||
lastActiveAtMs = 120_000L,
|
||||
lastStatsAtMs = 120_000L,
|
||||
lastInboundTrafficAtMs = 120_000L,
|
||||
sinceMs = 100_000L,
|
||||
nowMs = 130_000L,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmedUserTrafficFailureUsesShortRecoveryWindow() {
|
||||
assertEquals(true, isConfirmedUserTrafficFailure(userTrafficStalled = true))
|
||||
assertEquals(false, isConfirmedUserTrafficFailure(userTrafficStalled = false))
|
||||
assertEquals(
|
||||
true,
|
||||
isTransportHealthRecovery("пользовательский трафик снова получает ответы"),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
isTransportHealthRecovery("пользовательский трафик не получает ответы"),
|
||||
)
|
||||
assertEquals(30_000L, stableRecoveryGraceMs(hardFailure = true))
|
||||
assertEquals(2 * 60_000L, stableRecoveryRetryMs(hardFailure = true))
|
||||
assertEquals(10 * 60_000L, stableRecoveryGraceMs(hardFailure = false))
|
||||
assertEquals(10 * 60_000L, stableRecoveryRetryMs(hardFailure = false))
|
||||
assertEquals(
|
||||
false,
|
||||
shouldDeferConnectionIssueNotification(
|
||||
confirmedUserTrafficFailure = true,
|
||||
recoverableNetworkErrorAtMs = 100_000L,
|
||||
recoveryAttempts = 0,
|
||||
nowMs = 100_001L,
|
||||
firstGraceMs = 30_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldDeferConnectionIssueNotification(
|
||||
confirmedUserTrafficFailure = false,
|
||||
recoverableNetworkErrorAtMs = 100_000L,
|
||||
recoveryAttempts = 0,
|
||||
nowMs = 100_001L,
|
||||
firstGraceMs = 30_000L,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.SoftRestart,
|
||||
confirmedFailureRecoveryAction(hardFailure = true, completedAttempts = 0),
|
||||
)
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.StopVpn,
|
||||
confirmedFailureRecoveryAction(hardFailure = true, completedAttempts = 1),
|
||||
)
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.SoftRestart,
|
||||
confirmedFailureRecoveryAction(hardFailure = false, completedAttempts = 0),
|
||||
)
|
||||
assertEquals(
|
||||
NetworkRecoveryAction.SoftRestart,
|
||||
confirmedFailureRecoveryAction(hardFailure = false, completedAttempts = 3),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmedFailureTimestampMustExistAndMatchRequestedWindow() {
|
||||
assertEquals(false, hasConfirmedNetworkFailureAtOrAfter(true, 0L, 0L))
|
||||
assertEquals(false, hasConfirmedNetworkFailureAtOrAfter(false, 120_000L, 100_000L))
|
||||
assertEquals(false, hasConfirmedNetworkFailureAtOrAfter(true, 99_999L, 100_000L))
|
||||
assertEquals(true, hasConfirmedNetworkFailureAtOrAfter(true, 100_000L, 100_000L))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun confirmedFailureIsClearedOnlyByRealDownstreamTraffic() {
|
||||
assertEquals(
|
||||
false,
|
||||
shouldResetNetworkRecoveryFromStats(
|
||||
downstreamChanged = false,
|
||||
hardNetworkFailure = true,
|
||||
trafficChanged = true,
|
||||
statsTrafficStagnant = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldResetNetworkRecoveryFromStats(
|
||||
downstreamChanged = true,
|
||||
hardNetworkFailure = true,
|
||||
trafficChanged = true,
|
||||
statsTrafficStagnant = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldResetNetworkRecoveryFromStats(
|
||||
downstreamChanged = false,
|
||||
hardNetworkFailure = false,
|
||||
trafficChanged = true,
|
||||
statsTrafficStagnant = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wakeRecoveryReconnectsForZeroWorkersOrConfirmedFailure() {
|
||||
assertEquals(
|
||||
true,
|
||||
shouldReconnectTunnelAfterWake(activeWorkers = 0, confirmedNetworkFailure = false),
|
||||
)
|
||||
assertEquals(
|
||||
true,
|
||||
shouldReconnectTunnelAfterWake(activeWorkers = 9, confirmedNetworkFailure = true),
|
||||
)
|
||||
assertEquals(
|
||||
false,
|
||||
shouldReconnectTunnelAfterWake(activeWorkers = 9, confirmedNetworkFailure = false),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tunnelHealthIsNotJudgedDuringSleepOrWakeStabilization() {
|
||||
assertEquals(
|
||||
@@ -228,6 +713,42 @@ class TunnelRecoveryPolicyTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun passiveVpnRefreshesStatusRarelyButTransitionsStayResponsive() {
|
||||
assertEquals(
|
||||
30_000L,
|
||||
tunnelStatusRefreshIntervalMs(
|
||||
deviceInteractive = false,
|
||||
transitionWakeLockHeld = false,
|
||||
trustedWifiTransitionInProgress = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
2_000L,
|
||||
tunnelStatusRefreshIntervalMs(
|
||||
deviceInteractive = true,
|
||||
transitionWakeLockHeld = false,
|
||||
trustedWifiTransitionInProgress = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
2_000L,
|
||||
tunnelStatusRefreshIntervalMs(
|
||||
deviceInteractive = false,
|
||||
transitionWakeLockHeld = true,
|
||||
trustedWifiTransitionInProgress = false,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
2_000L,
|
||||
tunnelStatusRefreshIntervalMs(
|
||||
deviceInteractive = false,
|
||||
transitionWakeLockHeld = false,
|
||||
trustedWifiTransitionInProgress = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun phantomVpnCleanupDoesNotRaceExpectedRestore() {
|
||||
assertEquals(false, shouldClearPhantomVpn(activeTunnelProfile = 0))
|
||||
|
||||
@@ -4,6 +4,36 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelSessionTrafficTest {
|
||||
@Test
|
||||
fun notificationUsesGigabytesAfterOneGigabyte() {
|
||||
assertEquals(
|
||||
"Активных: 18 | ↓1.50 ГБ / ↑1.00 ГБ",
|
||||
formatTunnelTrafficForNotification(
|
||||
"Активных: 18 | ↓1536.00 МБ / ↑1024.00 МБ",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationKeepsSmallerDirectionInMegabytes() {
|
||||
assertEquals(
|
||||
"Активных: 18 | ↓1.25 ГБ / ↑512.25 МБ",
|
||||
formatTunnelTrafficForNotification(
|
||||
"Активных: 18 | ↓1280,00 МБ / ↑512.25 МБ",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun notificationKeepsTrafficBelowOneGigabyteInMegabytes() {
|
||||
assertEquals(
|
||||
"Активных: 9 | ↓1023.99 МБ / ↑10.00 МБ",
|
||||
formatTunnelTrafficForNotification(
|
||||
"Активных: 9 | ↓1023.99 МБ / ↑10.00 МБ",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trafficSurvivesAnIntentionalTransportRestart() {
|
||||
val accumulator = TunnelSessionTrafficAccumulator()
|
||||
@@ -46,4 +76,36 @@ class TunnelSessionTrafficTest {
|
||||
accumulator.accumulate("Активных: 9 | ↓0.25 МБ / ↑0.10 МБ"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun restoredServiceContinuesTheSameTrafficSession() {
|
||||
val beforeProcessRestart = TunnelSessionTrafficAccumulator()
|
||||
beforeProcessRestart.accumulate("Активных: 9 | ↓12.50 МБ / ↑3.25 МБ")
|
||||
|
||||
val afterProcessRestart = TunnelSessionTrafficAccumulator()
|
||||
afterProcessRestart.restore(beforeProcessRestart.snapshot())
|
||||
|
||||
assertEquals(
|
||||
"Активных: 9 | ↓13.00 МБ / ↑3.35 МБ",
|
||||
afterProcessRestart.accumulate("Активных: 9 | ↓0.50 МБ / ↑0.10 МБ"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidPersistedTrafficSnapshotIsIgnored() {
|
||||
val accumulator = TunnelSessionTrafficAccumulator()
|
||||
accumulator.restore(
|
||||
TunnelSessionTrafficSnapshot(
|
||||
downloadOffsetMb = Double.NaN,
|
||||
uploadOffsetMb = 1.0,
|
||||
lastRawDownloadMb = 2.0,
|
||||
lastRawUploadMb = 3.0,
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"Активных: 9 | ↓0.25 МБ / ↑0.10 МБ",
|
||||
accumulator.accumulate("Активных: 9 | ↓0.25 МБ / ↑0.10 МБ"),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -17,4 +17,56 @@ class TunnelWorkerPolicyTest {
|
||||
assertEquals(108, normalizeTunnelWorkerCount(108))
|
||||
assertEquals(108, normalizeTunnelWorkerCount(500))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun managedProfileRisesOnceWhenItsCeilingRises() {
|
||||
assertEquals(
|
||||
18,
|
||||
reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers = 9,
|
||||
previousProfileMaxWorkers = 9,
|
||||
currentProfileMaxWorkers = 18,
|
||||
remoteManaged = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualChoiceIsKeptAfterNewCeilingWasSeen() {
|
||||
assertEquals(
|
||||
9,
|
||||
reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers = 9,
|
||||
previousProfileMaxWorkers = 18,
|
||||
currentProfileMaxWorkers = 18,
|
||||
remoteManaged = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstRunAfterAnOlderAppReceivedTheLimitUsesTheNewCeiling() {
|
||||
assertEquals(
|
||||
18,
|
||||
reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers = 9,
|
||||
previousProfileMaxWorkers = null,
|
||||
currentProfileMaxWorkers = 18,
|
||||
remoteManaged = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ordinaryProfileDoesNotAutoPromote() {
|
||||
assertEquals(
|
||||
9,
|
||||
reconcileTunnelWorkerCountForProfileLimit(
|
||||
selectedWorkers = 9,
|
||||
previousProfileMaxWorkers = 9,
|
||||
currentProfileMaxWorkers = 18,
|
||||
remoteManaged = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.json.JSONObject
|
||||
|
||||
class VpnAddressRoutingTest {
|
||||
@Test
|
||||
fun addressListsAreRegisteredAsPerProfilePreferences() {
|
||||
assertTrue(
|
||||
SettingsStore.resettableProfilePreferenceNames().containsAll(
|
||||
setOf("blacklist_addresses", "whitelist_addresses")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizesDomainUrlIpAndSubnet() {
|
||||
assertEquals(
|
||||
VpnAddressRule(VpnAddressType.DOMAIN, "xn--e1afmkfd.xn--p1ai"),
|
||||
normalizeVpnAddressRule("https://Пример.рф/path?q=1"),
|
||||
)
|
||||
assertEquals(
|
||||
VpnAddressRule(VpnAddressType.IP, "1.2.3.4"),
|
||||
normalizeVpnAddressRule("1.2.3.4"),
|
||||
)
|
||||
assertEquals(
|
||||
VpnAddressRule(VpnAddressType.IP, "1.2.3.4"),
|
||||
normalizeVpnAddressRule("https://1.2.3.4/status"),
|
||||
)
|
||||
assertEquals(
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.168.1.0/24"),
|
||||
normalizeVpnAddressRule("192.168.1.77/24"),
|
||||
)
|
||||
assertEquals(
|
||||
VpnAddressRule(VpnAddressType.DOMAIN, "example.org"),
|
||||
normalizeVpnAddressRule("example.org:443"),
|
||||
)
|
||||
assertEquals(
|
||||
VpnAddressRule(VpnAddressType.IP, "1.2.3.4"),
|
||||
normalizeVpnAddressRule("1.2.3.4:53"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizesMultilineInputAndIpv4Ranges() {
|
||||
assertEquals(
|
||||
listOf(
|
||||
VpnAddressRule(VpnAddressType.DOMAIN, "example.org"),
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.0.2.1/32"),
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.0.2.2/31"),
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.0.2.4/31"),
|
||||
VpnAddressRule(VpnAddressType.SUBNET, "192.0.2.6/32"),
|
||||
VpnAddressRule(VpnAddressType.IP, "8.8.8.8"),
|
||||
),
|
||||
normalizeVpnAddressRules(
|
||||
"""
|
||||
example.org
|
||||
192.0.2.1 - 192.0.2.6
|
||||
8.8.8.8 - 8.8.8.8
|
||||
""".trimIndent()
|
||||
),
|
||||
)
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeVpnAddressRules("192.0.2.10 - 192.0.2.1")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsWildcardIpv6AndMalformedIpv4() {
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeVpnAddressRule("*.example.org")
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeVpnAddressRule("2001:db8::1")
|
||||
}
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeVpnAddressRule("01.2.3.4", VpnAddressType.IP)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun codecPreservesValidatedRules() {
|
||||
val rules = listOf(
|
||||
normalizeVpnAddressRule("example.org"),
|
||||
normalizeVpnAddressRule("1.1.1.1"),
|
||||
normalizeVpnAddressRule("10.10.15.8/16"),
|
||||
)
|
||||
|
||||
assertEquals(rules, decodeVpnAddressRulesStrict(encodeVpnAddressRules(rules)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentRoundTripPreservesBothModesAndCategories() {
|
||||
val document = VpnRoutingDocument(
|
||||
isWhitelist = true,
|
||||
blacklistApps = listOf("android", "app.black"),
|
||||
whitelistApps = listOf("app.white"),
|
||||
blacklistAddresses = listOf(normalizeVpnAddressRule("black.example")),
|
||||
whitelistAddresses = listOf(normalizeVpnAddressRule("10.20.30.0/24")),
|
||||
)
|
||||
|
||||
assertEquals(document, decodeVpnRoutingDocument(encodeVpnRoutingDocument(document)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingDocumentRejectsInvalidPackagesAndMissingLists() {
|
||||
val valid = JSONObject(encodeVpnRoutingDocument(
|
||||
VpnRoutingDocument(false, emptyList(), emptyList(), emptyList(), emptyList())
|
||||
))
|
||||
valid.getJSONArray("blacklistApps").put("not a package")
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
decodeVpnRoutingDocument(valid.toString())
|
||||
}
|
||||
|
||||
val missingAddresses = JSONObject()
|
||||
.put("format", "wdtt-plus-routing")
|
||||
.put("version", 1)
|
||||
.put("blacklistApps", org.json.JSONArray())
|
||||
.put("whitelistApps", org.json.JSONArray())
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
decodeVpnRoutingDocument(missingAddresses.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyAddressListKeepsTheDefaultRouteInBothModes() {
|
||||
assertEquals(
|
||||
listOf("0.0.0.0/0"),
|
||||
resolveVpnAddressRouting(false, emptyList()) { emptyList() }.allowedIps,
|
||||
)
|
||||
assertEquals(
|
||||
listOf("0.0.0.0/0"),
|
||||
resolveVpnAddressRouting(true, emptyList()) { emptyList() }.allowedIps,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blacklistSubtractsIpAndSubnetFromDefaultRoute() {
|
||||
val blockedIp = ipv4("1.1.1.1")
|
||||
val blockedSubnetIp = ipv4("10.20.30.40")
|
||||
val regularIp = ipv4("8.8.8.8")
|
||||
val rules = listOf(
|
||||
normalizeVpnAddressRule("1.1.1.1"),
|
||||
normalizeVpnAddressRule("10.0.0.0/8"),
|
||||
)
|
||||
|
||||
val routes = resolveVpnAddressRouting(false, rules) { emptyList() }.allowedIps
|
||||
|
||||
assertFalse(routes.any { cidrContains(it, blockedIp) })
|
||||
assertFalse(routes.any { cidrContains(it, blockedSubnetIp) })
|
||||
assertTrue(routes.any { cidrContains(it, regularIp) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun completeBlacklistAndWhitelistHaveOppositeBoundaryRoutes() {
|
||||
val allIpv4 = listOf(normalizeVpnAddressRule("0.0.0.0/0"))
|
||||
|
||||
assertTrue(resolveVpnAddressRouting(false, allIpv4) { emptyList() }.allowedIps.isEmpty())
|
||||
assertEquals(
|
||||
listOf("0.0.0.0/0"),
|
||||
resolveVpnAddressRouting(true, allIpv4) { emptyList() }.allowedIps,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun adjacentPrefixesCollapseWithoutChangingTheirCoverage() {
|
||||
val allIpv4AsTwoHalves = listOf(
|
||||
normalizeVpnAddressRule("0.0.0.0/1"),
|
||||
normalizeVpnAddressRule("128.0.0.0/1"),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("0.0.0.0/0"),
|
||||
resolveVpnAddressRouting(true, allIpv4AsTwoHalves) { emptyList() }.allowedIps,
|
||||
)
|
||||
assertTrue(
|
||||
resolveVpnAddressRouting(false, allIpv4AsTwoHalves) { emptyList() }
|
||||
.allowedIps
|
||||
.isEmpty()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun overlappingBlacklistRulesDoNotCreateHolesOutsideTheSelection() {
|
||||
val routes = resolveVpnAddressRouting(
|
||||
isWhitelist = false,
|
||||
rules = listOf(
|
||||
normalizeVpnAddressRule("10.0.0.0/8"),
|
||||
normalizeVpnAddressRule("10.20.0.0/16"),
|
||||
normalizeVpnAddressRule("10.20.30.40"),
|
||||
normalizeVpnAddressRule("255.255.255.255"),
|
||||
),
|
||||
domainResolver = { emptyList() },
|
||||
).allowedIps
|
||||
|
||||
listOf("10.0.0.0", "10.20.30.40", "10.255.255.255", "255.255.255.255")
|
||||
.forEach { excluded -> assertFalse(routes.any { cidrContains(it, ipv4(excluded)) }) }
|
||||
listOf("0.0.0.0", "9.255.255.255", "11.0.0.0", "255.255.255.254")
|
||||
.forEach { included -> assertTrue(routes.any { cidrContains(it, ipv4(included)) }) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whitelistUsesOnlySelectedAndResolvedAddresses() {
|
||||
val rules = listOf(
|
||||
normalizeVpnAddressRule("example.org"),
|
||||
normalizeVpnAddressRule("192.168.7.0/24"),
|
||||
)
|
||||
|
||||
val result = resolveVpnAddressRouting(true, rules) { domain ->
|
||||
if (domain == "example.org") listOf("93.184.216.34", "2001:db8::1") else emptyList()
|
||||
}
|
||||
|
||||
assertEquals(setOf("93.184.216.34/32", "192.168.7.0/24"), result.allowedIps.toSet())
|
||||
assertTrue(result.unresolvedDomains.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unresolvedDomainIsReportedAndDoesNotBroadenWhitelist() {
|
||||
val result = resolveVpnAddressRouting(
|
||||
isWhitelist = true,
|
||||
rules = listOf(normalizeVpnAddressRule("offline.example")),
|
||||
domainResolver = { emptyList() },
|
||||
)
|
||||
|
||||
assertTrue(result.allowedIps.isEmpty())
|
||||
assertEquals(listOf("offline.example"), result.unresolvedDomains)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blacklistSplitRouteKeepsIpv6FromFallingThroughOutsideVpn() {
|
||||
val splitBlacklist = resolveVpnAddressRouting(
|
||||
isWhitelist = false,
|
||||
rules = listOf(normalizeVpnAddressRule("1.1.1.1")),
|
||||
domainResolver = { emptyList() },
|
||||
)
|
||||
|
||||
val effective = effectiveWireGuardAllowedIps(
|
||||
isWhitelist = false,
|
||||
addressRulesConfigured = true,
|
||||
addressRouting = splitBlacklist,
|
||||
vpnDnsIpv4 = listOf("8.8.8.8"),
|
||||
)
|
||||
|
||||
assertTrue("::/1" in effective)
|
||||
assertTrue("8000::/1" in effective)
|
||||
assertFalse("::/0" in effective)
|
||||
assertTrue("8.8.8.8/32" in effective)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whitelistAddsVpnDnsButAllowsUnselectedFamiliesToFallThrough() {
|
||||
val addressWhitelist = resolveVpnAddressRouting(
|
||||
isWhitelist = true,
|
||||
rules = listOf(normalizeVpnAddressRule("1.1.1.1")),
|
||||
domainResolver = { emptyList() },
|
||||
)
|
||||
|
||||
val effective = effectiveWireGuardAllowedIps(
|
||||
isWhitelist = true,
|
||||
addressRulesConfigured = true,
|
||||
addressRouting = addressWhitelist,
|
||||
vpnDnsIpv4 = listOf("8.8.8.8", "invalid"),
|
||||
)
|
||||
|
||||
assertEquals(setOf("1.1.1.1/32", "8.8.8.8/32"), effective.toSet())
|
||||
assertFalse("::/0" in effective)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unresolvedBlacklistDomainDoesNotUnnecessarilyChangeIpv6Policy() {
|
||||
val unresolvedBlacklist = resolveVpnAddressRouting(
|
||||
isWhitelist = false,
|
||||
rules = listOf(normalizeVpnAddressRule("offline.example")),
|
||||
domainResolver = { emptyList() },
|
||||
)
|
||||
|
||||
val effective = effectiveWireGuardAllowedIps(
|
||||
isWhitelist = false,
|
||||
addressRulesConfigured = true,
|
||||
addressRouting = unresolvedBlacklist,
|
||||
vpnDnsIpv4 = emptyList(),
|
||||
)
|
||||
|
||||
assertEquals(listOf("0.0.0.0/0"), effective)
|
||||
}
|
||||
|
||||
private fun ipv4(value: String): Long = value.split('.').fold(0L) { result, part ->
|
||||
(result shl 8) or part.toLong()
|
||||
}
|
||||
|
||||
private fun cidrContains(cidr: String, address: Long): Boolean {
|
||||
val (networkValue, lengthValue) = cidr.split('/')
|
||||
val network = ipv4(networkValue)
|
||||
val length = lengthValue.toInt()
|
||||
val mask = if (length == 0) 0L else (0xffff_ffffL shl (32 - length)) and 0xffff_ffffL
|
||||
return address and mask == network
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ class VpnAppRoutingTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun emptyWhitelistExplicitlyExcludesAllApps() {
|
||||
fun emptyWhitelistRemovesAllPeerRoutes() {
|
||||
val routing = resolveVpnAppRouting(
|
||||
isWhitelist = true,
|
||||
selectedPackages = emptySet(),
|
||||
@@ -53,6 +53,73 @@ class VpnAppRoutingTest {
|
||||
)
|
||||
|
||||
assertTrue(routing.included.isEmpty())
|
||||
assertEquals(installed, routing.excluded)
|
||||
assertTrue(routing.excluded.isEmpty())
|
||||
assertTrue(routing.blocksAllApps)
|
||||
assertTrue(
|
||||
applyVpnAppRoutingToAllowedIps(routing, listOf("0.0.0.0/0")).isEmpty()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addressOnlyWhitelistLeavesAppsEligibleButKeepsRequiredBypasses() {
|
||||
val routing = resolveVpnAppRouting(
|
||||
isWhitelist = true,
|
||||
selectedPackages = emptySet(),
|
||||
installedPackages = installed,
|
||||
ownPackageName = ownPackage,
|
||||
addressWhitelistConfigured = true,
|
||||
)
|
||||
|
||||
assertTrue(routing.included.isEmpty())
|
||||
assertEquals(
|
||||
setOf(ownPackage, "com.vkontakte.android", "com.vk.calls"),
|
||||
routing.excluded,
|
||||
)
|
||||
assertTrue(!routing.blocksAllApps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingConfiguredWhitelistAppDoesNotBroadenAddressRulesToEveryApp() {
|
||||
val routing = resolveVpnAppRouting(
|
||||
isWhitelist = true,
|
||||
selectedPackages = setOf("app.from.other.phone"),
|
||||
installedPackages = installed,
|
||||
ownPackageName = ownPackage,
|
||||
addressWhitelistConfigured = true,
|
||||
)
|
||||
|
||||
assertTrue(routing.included.isEmpty())
|
||||
assertTrue(routing.excluded.isEmpty())
|
||||
assertTrue(routing.blocksAllApps)
|
||||
assertTrue(
|
||||
applyVpnAppRoutingToAllowedIps(routing, listOf("10.0.0.0/8")).isEmpty()
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun importedRoutingCannotKeepHiddenRequiredBypassPackages() {
|
||||
assertEquals(
|
||||
listOf("app.one", "app.two"),
|
||||
sanitizeVpnRoutingPackages(
|
||||
packageNames = listOf(
|
||||
ownPackage,
|
||||
"com.vkontakte.android",
|
||||
"com.vk.calls",
|
||||
"app.two",
|
||||
" app.one ",
|
||||
"app.two",
|
||||
),
|
||||
ownPackageName = ownPackage,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routingReloadOnlyTargetsTheActuallyRunningProfile() {
|
||||
assertTrue(shouldReloadWireGuardRouting(true, activeTunnelProfile = 1, changedProfile = 1))
|
||||
assertTrue(!shouldReloadWireGuardRouting(true, activeTunnelProfile = 1, changedProfile = 0))
|
||||
assertTrue(!shouldReloadWireGuardRouting(false, activeTunnelProfile = 1, changedProfile = 1))
|
||||
assertTrue(!shouldReloadWireGuardRouting(true, activeTunnelProfile = null, changedProfile = 1))
|
||||
assertTrue(!shouldReloadWireGuardRouting(true, activeTunnelProfile = 2, changedProfile = 99))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VpnDnsTest {
|
||||
@Test
|
||||
fun presetsHaveStableUniqueIdsAndExpectedAddresses() {
|
||||
assertEquals(
|
||||
mapOf(
|
||||
"cloudflare" to listOf("1.1.1.1", "1.0.0.1"),
|
||||
"google" to listOf("8.8.8.8", "8.8.4.4"),
|
||||
"quad9" to listOf("9.9.9.9", "149.112.112.112"),
|
||||
"adguard" to listOf("94.140.14.14", "94.140.15.15"),
|
||||
"xbox" to listOf("111.88.96.50", "111.88.96.51"),
|
||||
"comss" to listOf("83.220.169.155", "212.109.195.93"),
|
||||
),
|
||||
vpnDnsPresets.associate { it.id to it.servers },
|
||||
)
|
||||
assertEquals(vpnDnsPresets.size, vpnDnsPresets.map { it.id }.distinct().size)
|
||||
assertTrue(vpnDnsPresets.flatMap { it.servers }.all(::isIpv4Literal))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidSelectionSafelyNormalizesToProfileDns() {
|
||||
assertEquals(VPN_DNS_PROFILE_ID, normalizeVpnDnsSelectionId(null))
|
||||
assertEquals(VPN_DNS_PROFILE_ID, normalizeVpnDnsSelectionId("unknown"))
|
||||
assertEquals("quad9", normalizeVpnDnsSelectionId(" QUAD9 "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun customDnsAcceptsOneOrTwoNumericIpv4Addresses() {
|
||||
assertEquals(listOf("10.0.0.53"), normalizeCustomVpnDnsServers("10.0.0.53"))
|
||||
assertEquals(
|
||||
listOf("1.1.1.1", "8.8.8.8"),
|
||||
normalizeCustomVpnDnsServers("1.1.1.1; 8.8.8.8"),
|
||||
)
|
||||
assertEquals(
|
||||
listOf("1.1.1.1"),
|
||||
normalizeCustomVpnDnsServers("1.1.1.1, 1.1.1.1"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun customDnsRejectsUnsafeOrUnsupportedValues() {
|
||||
listOf(
|
||||
"",
|
||||
"dns.example",
|
||||
"1.1.1.1, 8.8.8.8, 9.9.9.9",
|
||||
"2001:4860:4860::8888",
|
||||
"01.1.1.1",
|
||||
"0.0.0.0",
|
||||
"127.0.0.1",
|
||||
"224.0.0.1",
|
||||
"255.255.255.255",
|
||||
).forEach { value ->
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
normalizeCustomVpnDnsServers(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun effectiveDnsUsesProfilePresetAndCustomSelections() {
|
||||
val profileServers = listOf("10.66.66.1")
|
||||
|
||||
assertEquals(
|
||||
profileServers,
|
||||
resolveEffectiveVpnDns(
|
||||
VpnDnsSettingsSnapshot(profileIndex = 0),
|
||||
profileServers,
|
||||
).servers,
|
||||
)
|
||||
assertEquals(
|
||||
listOf("8.8.8.8", "8.8.4.4"),
|
||||
resolveEffectiveVpnDns(
|
||||
VpnDnsSettingsSnapshot(profileIndex = 0, selectionId = "google"),
|
||||
profileServers,
|
||||
).servers,
|
||||
)
|
||||
assertEquals(
|
||||
listOf("10.0.0.53"),
|
||||
resolveEffectiveVpnDns(
|
||||
VpnDnsSettingsSnapshot(
|
||||
profileIndex = 0,
|
||||
selectionId = VPN_DNS_CUSTOM_ID,
|
||||
customServers = listOf("10.0.0.53"),
|
||||
),
|
||||
profileServers,
|
||||
).servers,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun missingCustomDnsFallsBackToWireGuardProfile() {
|
||||
val effective = resolveEffectiveVpnDns(
|
||||
VpnDnsSettingsSnapshot(
|
||||
profileIndex = 1,
|
||||
selectionId = VPN_DNS_CUSTOM_ID,
|
||||
customServers = emptyList(),
|
||||
),
|
||||
profileServers = listOf("10.66.66.1"),
|
||||
)
|
||||
|
||||
assertTrue(effective.fellBackToProfile)
|
||||
assertEquals(VPN_DNS_PROFILE_ID, effective.selectionId)
|
||||
assertEquals(listOf("10.66.66.1"), effective.servers)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun appliedLogUsesProfileNameAndHumanDnsText() {
|
||||
val profileDns = resolveEffectiveVpnDns(
|
||||
VpnDnsSettingsSnapshot(profileIndex = 0),
|
||||
profileServers = listOf("1.1.1.1", "1.0.0.1"),
|
||||
)
|
||||
val fallbackDns = resolveEffectiveVpnDns(
|
||||
VpnDnsSettingsSnapshot(
|
||||
profileIndex = 0,
|
||||
selectionId = VPN_DNS_CUSTOM_ID,
|
||||
customServers = emptyList(),
|
||||
),
|
||||
profileServers = listOf("9.9.9.9"),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"«Дом»: DNS из WireGuard-профиля используется внутри VPN: 1.1.1.1, 1.0.0.1.",
|
||||
vpnDnsAppliedLogMessage("Дом", profileDns),
|
||||
)
|
||||
assertTrue(
|
||||
vpnDnsAppliedLogMessage("Дом", fallbackDns)
|
||||
.contains("Свой DNS был некорректен"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dnsValuesAreRegisteredAsPerProfilePreferences() {
|
||||
assertTrue(
|
||||
SettingsStore.resettableProfilePreferenceNames().containsAll(
|
||||
setOf("vpn_dns_selection", "vpn_dns_custom")
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smartDnsAndInvalidCustomAreVisibleInDeviceDiagnostics() {
|
||||
val smart = vpnDnsModeItem(
|
||||
settings = VpnDnsSettingsSnapshot(profileIndex = 0, selectionId = "xbox"),
|
||||
tunnelRunning = true,
|
||||
runningProfile = 0,
|
||||
)
|
||||
val invalidCustom = vpnDnsModeItem(
|
||||
settings = VpnDnsSettingsSnapshot(
|
||||
profileIndex = 1,
|
||||
selectionId = VPN_DNS_CUSTOM_ID,
|
||||
),
|
||||
tunnelRunning = false,
|
||||
runningProfile = null,
|
||||
)
|
||||
|
||||
assertEquals(DeviceCheckSeverity.Info, smart.severity)
|
||||
assertTrue(smart.details.contains("сторонний Smart DNS"))
|
||||
assertEquals(DeviceCheckSeverity.Warning, invalidCustom.severity)
|
||||
assertFalse(invalidCustom.recommendation.isBlank())
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import com.wireguard.config.Config
|
||||
import com.wireguard.config.Peer
|
||||
import com.wireguard.crypto.Key
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -40,6 +41,34 @@ class WireGuardRuntimeConfigTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun changedApplicationRoutingReplacesVpnInterface() {
|
||||
val current = config(endpointPort = 9000, excludedApplication = "app.one")
|
||||
val updated = config(endpointPort = 9000, excludedApplication = "app.two")
|
||||
|
||||
assertFalse(
|
||||
shouldReuseRunningWireGuard(
|
||||
tunnelUp = true,
|
||||
currentConfigFingerprint = wireGuardConfigFingerprint(current),
|
||||
updatedConfig = updated,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun changedDnsReplacesVpnInterface() {
|
||||
val current = config(endpointPort = 9000, dns = "1.1.1.1")
|
||||
val updated = config(endpointPort = 9000, dns = "8.8.8.8")
|
||||
|
||||
assertFalse(
|
||||
shouldReuseRunningWireGuard(
|
||||
tunnelUp = true,
|
||||
currentConfigFingerprint = wireGuardConfigFingerprint(current),
|
||||
updatedConfig = updated,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stoppedVpnInterfaceIsNeverReused() {
|
||||
val config = config(endpointPort = 9000)
|
||||
@@ -53,13 +82,30 @@ class WireGuardRuntimeConfigTest {
|
||||
)
|
||||
}
|
||||
|
||||
private fun config(endpointPort: Int): Config {
|
||||
@Test
|
||||
fun peerWithoutAllowedIpsIsValidForAnEmptyAddressWhitelist() {
|
||||
val peer = Peer.Builder()
|
||||
.parsePublicKey(publicKey)
|
||||
.build()
|
||||
|
||||
assertTrue(peer.allowedIps.isEmpty())
|
||||
}
|
||||
|
||||
private fun config(
|
||||
endpointPort: Int,
|
||||
excludedApplication: String? = null,
|
||||
dns: String = "1.1.1.1",
|
||||
): Config {
|
||||
val appRouting = excludedApplication
|
||||
?.let { "ExcludedApplications = $it" }
|
||||
.orEmpty()
|
||||
val text = """
|
||||
[Interface]
|
||||
PrivateKey = $privateKey
|
||||
Address = 10.0.0.2/32
|
||||
DNS = 1.1.1.1
|
||||
DNS = $dns
|
||||
MTU = 1280
|
||||
$appRouting
|
||||
|
||||
[Peer]
|
||||
PublicKey = $publicKey
|
||||
|
||||
@@ -31,5 +31,6 @@ class OutboundFormsStoreTest {
|
||||
assertTrue(OutboundFormsStore.isSecretPlainKey("profile_1_wg_exit_password"))
|
||||
assertTrue(OutboundFormsStore.isSecretPlainKey("local_proxy_password"))
|
||||
assertFalse(OutboundFormsStore.isSecretPlainKey("profile_1_external_proxy_host"))
|
||||
assertFalse(OutboundFormsStore.isSecretPlainKey("profile_1_tun_interface"))
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,14 @@ class OutboundProfileComparisonTest {
|
||||
assertTrue(outboundProfilesDiffer(server, local))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun configuredTunInterfaceChange_isReported() {
|
||||
val server = snapshot(mode = "tun_interface", tunInterface = "xray0")
|
||||
val local = forms(tunInterface = "singtun0")
|
||||
|
||||
assertTrue(outboundProfilesDiffer(server, local))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun orphanedWarpInterface_isAttributedOnlyToWarpAndCanBeDisabledThere() {
|
||||
val server = snapshot(
|
||||
@@ -169,7 +177,8 @@ class OutboundProfileComparisonTest {
|
||||
wireGuardExitPassword: String = "",
|
||||
wireGuardExitPort: String = "51820",
|
||||
wireGuardExitDns: String = "1.1.1.1,8.8.8.8",
|
||||
importedWireGuardConfig: String = ""
|
||||
importedWireGuardConfig: String = "",
|
||||
tunInterface: String = ""
|
||||
) = OutboundProfileForms(
|
||||
localProxyPort = localProxyPort,
|
||||
localProxyLogin = localProxyLogin,
|
||||
@@ -185,7 +194,8 @@ class OutboundProfileComparisonTest {
|
||||
wireGuardExitPassword = wireGuardExitPassword,
|
||||
wireGuardExitPort = wireGuardExitPort,
|
||||
wireGuardExitDns = wireGuardExitDns,
|
||||
importedWireGuardConfig = importedWireGuardConfig
|
||||
importedWireGuardConfig = importedWireGuardConfig,
|
||||
tunInterface = tunInterface
|
||||
)
|
||||
|
||||
private fun snapshot(
|
||||
@@ -212,7 +222,8 @@ class OutboundProfileComparisonTest {
|
||||
warpPresent: Boolean = false,
|
||||
externalProxyServiceActive: Boolean = false,
|
||||
externalProxyRouteActive: Boolean = false,
|
||||
wireGuardOwnerMode: String = ""
|
||||
wireGuardOwnerMode: String = "",
|
||||
tunInterface: String = ""
|
||||
) = OutboundServerSnapshot(
|
||||
mode = mode,
|
||||
detail = "",
|
||||
@@ -244,6 +255,8 @@ class OutboundProfileComparisonTest {
|
||||
checkedAtMillis = 0L,
|
||||
externalProxyServiceActive = externalProxyServiceActive,
|
||||
externalProxyRouteActive = externalProxyRouteActive,
|
||||
wireGuardOwnerMode = wireGuardOwnerMode
|
||||
wireGuardOwnerMode = wireGuardOwnerMode,
|
||||
tunInterface = tunInterface,
|
||||
tunPresent = tunInterface.isNotBlank()
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class OutboundTunInterfaceTest {
|
||||
@Test
|
||||
fun interfaceNameValidation_acceptsLinuxNameAndRejectsUnsafeOrReservedValues() {
|
||||
assertNull(tunInterfaceNameIssue("xray0"))
|
||||
assertNull(tunInterfaceNameIssue("sing-box_1"))
|
||||
assertTrue(tunInterfaceNameIssue("wdtt0") != null)
|
||||
assertTrue(tunInterfaceNameIssue("wg-wdtt-exit") != null)
|
||||
assertTrue(tunInterfaceNameIssue("xray0; reboot") != null)
|
||||
assertTrue(tunInterfaceNameIssue("-xray0") != null)
|
||||
assertTrue(tunInterfaceNameIssue("..") != null)
|
||||
assertTrue(tunInterfaceNameIssue("interface-name-is-too-long") != null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun interfaceSelection_blocksAKnownStoppedCandidateButAllowsManualNames() {
|
||||
val candidates = listOf(
|
||||
TunInterfaceCandidate("xray0", false),
|
||||
TunInterfaceCandidate("singtun0", true),
|
||||
)
|
||||
|
||||
assertTrue(tunInterfaceSelectionIssue("xray0", candidates)?.contains("остановлен") == true)
|
||||
assertNull(tunInterfaceSelectionIssue("singtun0", candidates))
|
||||
assertNull(tunInterfaceSelectionIssue("manualtun0", candidates))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tunStatePolling_runsOnlyWhileItsServerUiIsVisible() {
|
||||
assertTrue(
|
||||
shouldPollTunOutboundState(
|
||||
visible = false,
|
||||
expanded = false,
|
||||
dialog = OutboundDialog.TunInterface,
|
||||
mode = null,
|
||||
hasSshAuthentication = true,
|
||||
)
|
||||
)
|
||||
assertTrue(
|
||||
shouldPollTunOutboundState(
|
||||
visible = true,
|
||||
expanded = true,
|
||||
dialog = null,
|
||||
mode = "tun_interface",
|
||||
hasSshAuthentication = true,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
shouldPollTunOutboundState(
|
||||
visible = true,
|
||||
expanded = true,
|
||||
dialog = null,
|
||||
mode = "direct",
|
||||
hasSshAuthentication = true,
|
||||
)
|
||||
)
|
||||
assertFalse(
|
||||
shouldPollTunOutboundState(
|
||||
visible = true,
|
||||
expanded = true,
|
||||
dialog = OutboundDialog.TunInterface,
|
||||
mode = "tun_interface",
|
||||
hasSshAuthentication = false,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun candidateParser_keepsSafeCandidatesAndShowsUpStateFirst() {
|
||||
val parsed = parseTunInterfaceCandidates(
|
||||
"""
|
||||
noise
|
||||
WDTT_TUN_CANDIDATE=tun9|0
|
||||
WDTT_TUN_CANDIDATE=xray0|1
|
||||
WDTT_TUN_CANDIDATE=wdtt0|1
|
||||
WDTT_TUN_CANDIDATE=xray0|1
|
||||
""".trimIndent()
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
TunInterfaceCandidate("xray0", true),
|
||||
TunInterfaceCandidate("tun9", false)
|
||||
),
|
||||
parsed
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun candidateDiscovery_readsKernelTunDevicesWithoutSelectingOne() {
|
||||
val script = tunInterfaceCandidatesScript()
|
||||
|
||||
assertTrue("/sys/class/net/*" in script)
|
||||
assertTrue("tun_flags" in script)
|
||||
assertTrue("WDTT_TUN_CANDIDATE=" in script)
|
||||
assertFalse("TUN_INTERFACE_B64" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun enableScript_isScopedFailClosedAndChecksRealWdttTraffic() {
|
||||
val script = buildTunInterfaceExitScript("xray0")
|
||||
|
||||
assertTrue("wdtt_clear_external_out" in script)
|
||||
assertTrue("trap tun_rollback EXIT" in script)
|
||||
assertTrue("rollback after TUN setup error" in script)
|
||||
assertTrue("TUN_COMMITTED=1" in script)
|
||||
assertTrue("trap - EXIT" in script)
|
||||
assertTrue("WDTT_TUN_TABLE=110" in script)
|
||||
assertTrue("WDTT_TUN_PRIORITY=90" in script)
|
||||
assertTrue("WDTT_TUN_EXIT" in script)
|
||||
assertTrue("wdtt-tun-exit.service" in script)
|
||||
assertTrue("tun-exit-watch" in script)
|
||||
assertTrue("STATE_FILE=/run/wdtt-tun-exit.state" in script)
|
||||
assertTrue("report_state blocked" in script)
|
||||
assertTrue("logger -t wdtt-tun-exit" in script)
|
||||
assertTrue("ip route replace unreachable default" in script)
|
||||
assertTrue("blocked_status && return 0" in script)
|
||||
assertTrue(
|
||||
script.indexOf("ip route replace unreachable default table") <
|
||||
script.indexOf("ip route replace default dev \"${'$'}TUN_IFACE\"")
|
||||
)
|
||||
assertFalse("block() {\n cleanup" in script)
|
||||
assertTrue("${'$'}ROUTE_HELPER\" block" in script)
|
||||
assertTrue("curl -4fsS --interface \"${'$'}TEST_SOURCE\"" in script)
|
||||
assertTrue("wdtt_write_mode \"tun_interface\"" in script)
|
||||
assertTrue("tun_interface_is_primary" in script)
|
||||
assertTrue("WDTT_TUN_EXIT_V1" in script)
|
||||
assertTrue("tun_exit_ownership_conflict" in script)
|
||||
assertTrue("/proc/sys/net/ipv4/ip_forward" in script)
|
||||
assertTrue("tun_ip_forward_failed" in script)
|
||||
assertTrue("rollback after TUN traffic test error" in script)
|
||||
assertFalse("ip link delete \"${'$'}TUN_IFACE\"" in script)
|
||||
assertFalse("--comment WDTT_MANAGED -j" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun enableScript_rejectsShellMetacharacters() {
|
||||
buildTunInterfaceExitScript("xray0;reboot")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directAndDeleteScripts_removeOnlyWdttOwnedTunState() {
|
||||
val direct = disableOutboundExitScript()
|
||||
val delete = deleteTunInterfaceExitScript()
|
||||
|
||||
assertTrue("wdtt_clear_tun_out" in direct)
|
||||
assertTrue("WDTT_TUN_TABLE" in direct)
|
||||
assertTrue("WDTT_TUN_EXIT" in direct)
|
||||
assertTrue("TUN_OWNED" in direct)
|
||||
assertTrue("wdtt_require_tun_cleanup_ownership" in direct)
|
||||
assertTrue("WDTT_ERROR=tun_exit_not_owned" in direct)
|
||||
assertTrue("wdtt-tun-exit.service" in delete)
|
||||
assertTrue(
|
||||
delete.indexOf("wdtt_require_tun_cleanup_ownership ||") <
|
||||
delete.indexOf("Останавливаю управляемый TUN-выход")
|
||||
)
|
||||
assertTrue("TUN_INTERFACE_B64" in delete)
|
||||
assertTrue("/run/wdtt-tun-exit.state" in delete)
|
||||
assertTrue("Сам TUN-интерфейс" in delete)
|
||||
assertFalse("ip link delete \"${'$'}TUN_IFACE\"" in delete)
|
||||
assertFalse("systemctl disable --now xray" in delete)
|
||||
assertFalse("systemctl disable --now 3x-ui" in delete)
|
||||
assertShellSyntax(direct)
|
||||
assertShellSyntax(delete)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun checkScript_requiresOwnedHelperAndProbesRealWdttTraffic() {
|
||||
val script = checkTunInterfaceExitScript("xray0")
|
||||
|
||||
assertTrue("WDTT_TUN_EXIT_V1" in script)
|
||||
assertTrue("WDTT_ERROR=tun_exit_not_owned" in script)
|
||||
assertTrue("WDTT_ERROR=tun_interface_mismatch" in script)
|
||||
assertTrue("tun-exit-route status" in script)
|
||||
assertTrue("curl -4fsS --interface \"${'$'}TEST_SOURCE\"" in script)
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun snapshotStatusAndDiagnostics_reportTunComponents() {
|
||||
val snapshot = outboundSnapshotScript()
|
||||
val status = outboundStatusScript()
|
||||
val diagnostics = serverDiagnosticsScript()
|
||||
|
||||
assertTrue("WDTT_TUN_INTERFACE_B64" in snapshot)
|
||||
assertTrue("WDTT_TUN_POLICY_RULE_ACTIVE" in snapshot)
|
||||
assertTrue("WDTT_TUN_FORWARD_RULES_ACTIVE" in snapshot)
|
||||
assertTrue("WDTT_TUN_IP_FORWARD_ACTIVE" in snapshot)
|
||||
assertTrue("WDTT_TUN_FAIL_CLOSED_ACTIVE" in snapshot)
|
||||
assertTrue("[ -e \"${'$'}WDTT_TUN_OWNER_FILE\" ]" in snapshot)
|
||||
assertTrue("[ -e \"${'$'}WDTT_TUN_CONFIG_FILE\" ]" in snapshot)
|
||||
assertTrue("Автозапуск TUN-выхода" in status)
|
||||
assertTrue("Пересылка IPv4-пакетов" in status)
|
||||
assertTrue("Аварийная блокировка прямого выхода" in status)
|
||||
assertTrue("Маршрут по умолчанию через TUN" in status)
|
||||
assertTrue("TUN-выход запущен не полностью" in diagnostics)
|
||||
assertTrue("table 110" in diagnostics)
|
||||
assertShellSyntax(snapshot)
|
||||
assertShellSyntax(status)
|
||||
assertShellSyntax(diagnostics)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tunMode_conflictsWithAnotherRouteAndCanAlwaysBeCleaned() {
|
||||
val tunOnly = snapshot(
|
||||
mode = "tun_interface",
|
||||
tunPresent = true,
|
||||
tunInterfaceActive = true,
|
||||
tunServiceActive = true,
|
||||
tunServiceEnabled = true,
|
||||
tunPolicyRuleActive = true,
|
||||
tunDefaultRouteActive = true,
|
||||
tunForwardRulesActive = true,
|
||||
tunIpForwardActive = true,
|
||||
tunFailClosedActive = false
|
||||
)
|
||||
assertEquals(
|
||||
OutboundModeIndicator(OutboundModeVisualState.Active, "активен"),
|
||||
outboundModeIndicator(tunOnly, OutboundDialog.TunInterface)
|
||||
)
|
||||
assertTrue(canDisableOutboundDialog(tunOnly, OutboundDialog.TunInterface))
|
||||
assertTrue(canReturnDirect(tunOnly))
|
||||
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Error,
|
||||
outboundModeIndicator(
|
||||
tunOnly.copy(tunIpForwardActive = false),
|
||||
OutboundDialog.TunInterface
|
||||
).state
|
||||
)
|
||||
|
||||
val blocked = tunOnly.copy(
|
||||
tunInterfaceActive = false,
|
||||
tunDefaultRouteActive = false,
|
||||
tunForwardRulesActive = false,
|
||||
tunFailClosedActive = true
|
||||
)
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Error,
|
||||
outboundModeIndicator(blocked, OutboundDialog.TunInterface).state
|
||||
)
|
||||
|
||||
val conflict = tunOnly.copy(
|
||||
externalProxyRouteActive = true,
|
||||
externalProxyServiceActive = true
|
||||
)
|
||||
assertTrue(conflict.hasRouteConflict)
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Error,
|
||||
outboundModeIndicator(conflict, OutboundDialog.TunInterface).state
|
||||
)
|
||||
assertEquals(
|
||||
OutboundModeVisualState.Error,
|
||||
outboundModeIndicator(conflict, OutboundDialog.ExternalProxy).state
|
||||
)
|
||||
}
|
||||
|
||||
private fun snapshot(
|
||||
mode: String,
|
||||
tunPresent: Boolean,
|
||||
tunInterfaceActive: Boolean,
|
||||
tunServiceActive: Boolean,
|
||||
tunServiceEnabled: Boolean,
|
||||
tunPolicyRuleActive: Boolean,
|
||||
tunDefaultRouteActive: Boolean,
|
||||
tunForwardRulesActive: Boolean,
|
||||
tunIpForwardActive: Boolean,
|
||||
tunFailClosedActive: Boolean
|
||||
) = OutboundServerSnapshot(
|
||||
mode = mode,
|
||||
detail = "xray0",
|
||||
updatedAt = "",
|
||||
hasProfile = true,
|
||||
localProxyPresent = false,
|
||||
localProxyActive = false,
|
||||
localProxyPort = "",
|
||||
localProxyLogin = "",
|
||||
localProxyPassword = "",
|
||||
externalProxyPresent = false,
|
||||
externalProxyActive = false,
|
||||
externalProxyKindName = "",
|
||||
externalProxyHost = "",
|
||||
externalProxyPort = "",
|
||||
externalProxyLogin = "",
|
||||
externalProxyPassword = "",
|
||||
wireGuardPresent = false,
|
||||
wireGuardActive = false,
|
||||
wireGuardExitHost = "",
|
||||
wireGuardExitSshPort = "",
|
||||
wireGuardExitUser = "",
|
||||
wireGuardExitPassword = "",
|
||||
wireGuardExitPort = "",
|
||||
wireGuardExitDns = "",
|
||||
warpPresent = false,
|
||||
warpMtu = "",
|
||||
importedWireGuardConfig = "",
|
||||
tunInterface = "xray0",
|
||||
tunPresent = tunPresent,
|
||||
tunInterfaceActive = tunInterfaceActive,
|
||||
tunServiceActive = tunServiceActive,
|
||||
tunServiceEnabled = tunServiceEnabled,
|
||||
tunPolicyRuleActive = tunPolicyRuleActive,
|
||||
tunDefaultRouteActive = tunDefaultRouteActive,
|
||||
tunForwardRulesActive = tunForwardRulesActive,
|
||||
tunIpForwardActive = tunIpForwardActive,
|
||||
tunFailClosedActive = tunFailClosedActive
|
||||
)
|
||||
|
||||
private fun assertShellSyntax(script: String) {
|
||||
val file = File.createTempFile("wdtt-tun-exit-", ".sh")
|
||||
try {
|
||||
file.writeText(script)
|
||||
listOf("sh", "bash").forEach { shell ->
|
||||
val process = ProcessBuilder(shell, "-n", file.absolutePath)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
val output = process.inputStream.bufferedReader().readText()
|
||||
val code = process.waitFor()
|
||||
assertTrue("$shell -n завершился с кодом $code: $output", code == 0)
|
||||
}
|
||||
} finally {
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import java.util.Base64
|
||||
|
||||
class OutboundWireGuardTest {
|
||||
private val safeConfig = """
|
||||
@@ -69,6 +72,138 @@ class OutboundWireGuardTest {
|
||||
assertShellSyntax(script)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun localProxyFirewallHelper_preservesRuntimeActionAndRepairsIssue16() {
|
||||
val helper = localProxyFirewallScript(10808)
|
||||
val installScript = buildLocalProxyInstallScript(
|
||||
port = 10808,
|
||||
login = "proxy-user",
|
||||
proxyPassword = "safe-test-password",
|
||||
)
|
||||
|
||||
assertTrue("action=\"${'$'}{1:-}\"" in helper)
|
||||
assertFalse("action=\"\"" in helper)
|
||||
assertTrue("systemctl reset-failed wdtt-3proxy" in installScript)
|
||||
assertFalse("local-proxy-firewall <<EOF" in installScript)
|
||||
val encodedHelper = Regex(
|
||||
"printf '%s' '([A-Za-z0-9+/=]+)' \\| base64 -d >/usr/local/lib/wdtt/local-proxy-firewall"
|
||||
).find(installScript)?.groupValues?.get(1).orEmpty()
|
||||
assertTrue("helper должен встраиваться без shell-подстановок", encodedHelper.isNotBlank())
|
||||
assertEquals(
|
||||
helper,
|
||||
String(Base64.getDecoder().decode(encodedHelper), Charsets.UTF_8),
|
||||
)
|
||||
assertShellSyntax(helper, shell = "sh")
|
||||
assertShellSyntax(installScript)
|
||||
|
||||
val tempDir = Files.createTempDirectory("wdtt-proxy-firewall-").toFile()
|
||||
try {
|
||||
val calls = File(tempDir, "iptables-calls")
|
||||
val existingRule = File(tempDir, "iptables-existing").apply { writeText("present") }
|
||||
val fakeIptables = File(tempDir, "iptables").apply {
|
||||
writeText(
|
||||
"""
|
||||
#!/bin/sh
|
||||
if [ "${'$'}{1:-}" = "-S" ]; then
|
||||
if [ -f "${'$'}IPTABLES_EXISTING" ]; then
|
||||
echo '-A INPUT -p tcp --dport 9999 -m comment --comment WDTT_LOCAL_PROXY -j ACCEPT'
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
printf '%s\n' "${'$'}*" >>"${'$'}IPTABLES_CALLS"
|
||||
if [ "${'$'}{1:-}" = "-D" ]; then
|
||||
rm -f "${'$'}IPTABLES_EXISTING"
|
||||
fi
|
||||
""".trimIndent() + "\n"
|
||||
)
|
||||
setExecutable(true)
|
||||
}
|
||||
assertTrue(fakeIptables.canExecute())
|
||||
val helperFile = File(tempDir, "local-proxy-firewall").apply {
|
||||
writeText(helper)
|
||||
setExecutable(true)
|
||||
}
|
||||
fun run(action: String): Int = ProcessBuilder("sh", helperFile.absolutePath, action)
|
||||
.apply {
|
||||
environment()["PATH"] = tempDir.absolutePath + File.pathSeparator +
|
||||
System.getenv("PATH").orEmpty()
|
||||
environment()["IPTABLES_CALLS"] = calls.absolutePath
|
||||
environment()["IPTABLES_EXISTING"] = existingRule.absolutePath
|
||||
}
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
.let { process ->
|
||||
process.inputStream.bufferedReader().readText()
|
||||
process.waitFor()
|
||||
}
|
||||
|
||||
assertEquals(0, run("up"))
|
||||
val appliedRules = calls.readLines()
|
||||
assertTrue(appliedRules.any { it.startsWith("-D INPUT") && "--dport 9999" in it })
|
||||
assertTrue(appliedRules.any { "--dport 10808" in it })
|
||||
assertTrue(appliedRules.any { "--dport 10809" in it })
|
||||
assertTrue(appliedRules.any { "--dport 10810" in it })
|
||||
assertEquals(0, run("down"))
|
||||
assertEquals(2, run("invalid"))
|
||||
} finally {
|
||||
tempDir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun externalProxyRoutesHelper_preservesRuntimeArguments() {
|
||||
val helper = externalProxyRoutesScript()
|
||||
|
||||
assertTrue("action=\"${'$'}{1:-}\"" in helper)
|
||||
assertTrue("PROXY_IP=\"${'$'}{2:-}\"" in helper)
|
||||
assertFalse("action=\"\"" in helper)
|
||||
assertShellSyntax(helper, shell = "sh")
|
||||
|
||||
val tempDir = Files.createTempDirectory("wdtt-proxy-routes-").toFile()
|
||||
try {
|
||||
val calls = File(tempDir, "iptables-calls")
|
||||
File(tempDir, "iptables").apply {
|
||||
writeText(
|
||||
"""
|
||||
#!/bin/sh
|
||||
printf '%s\n' "${'$'}*" >>"${'$'}IPTABLES_CALLS"
|
||||
case " ${'$'}* " in
|
||||
*" -D "*) exit 1 ;;
|
||||
esac
|
||||
exit 0
|
||||
""".trimIndent() + "\n"
|
||||
)
|
||||
setExecutable(true)
|
||||
}
|
||||
val helperFile = File(tempDir, "redsocks-routes").apply {
|
||||
writeText(helper)
|
||||
setExecutable(true)
|
||||
}
|
||||
fun run(vararg arguments: String): Int = ProcessBuilder(
|
||||
listOf("sh", helperFile.absolutePath) + arguments
|
||||
)
|
||||
.apply {
|
||||
environment()["PATH"] = tempDir.absolutePath + File.pathSeparator +
|
||||
System.getenv("PATH").orEmpty()
|
||||
environment()["IPTABLES_CALLS"] = calls.absolutePath
|
||||
}
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
.let { process ->
|
||||
process.inputStream.bufferedReader().readText()
|
||||
process.waitFor()
|
||||
}
|
||||
|
||||
assertEquals(0, run("up", "203.0.113.9"))
|
||||
assertTrue(calls.readLines().any { "-d 203.0.113.9 -j RETURN" in it })
|
||||
assertEquals(0, run("down", "203.0.113.9"))
|
||||
assertEquals(2, run("up"))
|
||||
assertEquals(2, run("invalid", "203.0.113.9"))
|
||||
} finally {
|
||||
tempDir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun directExitScript_forceCleansPartiallyStartedWireGuard() {
|
||||
val script = disableOutboundExitScript()
|
||||
@@ -113,7 +248,13 @@ class OutboundWireGuardTest {
|
||||
@Test
|
||||
fun protocolErrorMarker_isNotCopiedRawToUserLog() {
|
||||
assertFalse(shouldWriteRemoteErrorToUserLog("WDTT_ERROR=local_proxy_check_failed"))
|
||||
assertFalse(shouldWriteRemoteErrorToUserLog("WDTT_TUN_FAIL_CLOSED_ACTIVE=0"))
|
||||
assertFalse(shouldWriteRemoteErrorToUserLog("CHECK_FAILED=0"))
|
||||
assertTrue(shouldWriteRemoteErrorToUserLog("FAIL: служба не запустилась"))
|
||||
assertEquals(
|
||||
"Ошибка на сервере: служба не запустилась",
|
||||
remoteErrorMessageForUserLog("FAIL: служба не запустилась"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -149,6 +290,16 @@ class OutboundWireGuardTest {
|
||||
assertTrue("WG_DEFAULT_ROUTE_ACTIVE" in script)
|
||||
assertTrue("WG_NAT_ACTIVE" in script)
|
||||
assertTrue("WireGuard-выход запущен не полностью" in script)
|
||||
assertTrue("внешний TCP-прокси запущен не полностью" in script)
|
||||
assertTrue("конфликт маршрутов внешнего выхода" in script)
|
||||
assertTrue("остались компоненты WireGuard-выхода" in script)
|
||||
assertTrue("остались компоненты TUN-выхода" in script)
|
||||
assertTrue("неизвестный режим выхода" in script)
|
||||
assertTrue("Прокси на этом VPS (3proxy)" in script)
|
||||
assertTrue("автозапуск включён, служба не работает" in script)
|
||||
assertTrue("Учётные данные диагностикой не читаются" in script)
|
||||
assertTrue("EXTERNAL_PROXY_REDIRECT_ACTIVE" in script)
|
||||
assertTrue("LOCAL_PROXY_LISTEN_ACTIVE" in script)
|
||||
assertTrue("FIREWALL_SEVERITY=\"ERROR\"" in script)
|
||||
assertTrue("NAT прямого выхода отсутствует" in script)
|
||||
assertTrue("WDTT_EXPECTED_DTLS_PORT" in script)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import com.wdtt.plus.ServerAdminProfileInfo
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -356,6 +357,62 @@ class ServerMigrationTest {
|
||||
assertTrue(prepared.getJSONObject("passwords").has("client-a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exportUsesCurrentOwnerProfileWhenTunnelPointsToSourceServer() {
|
||||
val source = database("client-a", "Телефон")
|
||||
source.getJSONObject("admin_profile")
|
||||
.put("vk_hashes", "old-owner-hash")
|
||||
.put("device_ids", JSONArray().put("owner-phone"))
|
||||
|
||||
val prepared = prepareServerDatabaseForBackup(
|
||||
sourceJson = source.toString(),
|
||||
localOwnerProfile = ServerAdminProfileInfo(
|
||||
vkHashes = "new-owner-hash-1,new-owner-hash-2",
|
||||
secondaryVkHash = "new-reserve-hash",
|
||||
profileName = "Новый сервер",
|
||||
workersPerHash = 24,
|
||||
protocol = "tcp",
|
||||
listenPort = 9100,
|
||||
sni = "example.org",
|
||||
noDns = true,
|
||||
vpnDnsSelectionId = "custom",
|
||||
vpnDnsCustomServers = listOf("10.0.0.53"),
|
||||
vpnDnsStored = true,
|
||||
ports = "56100,56101,9100"
|
||||
),
|
||||
localPeer = "OLD.EXAMPLE.ORG.",
|
||||
sourceHost = "old.example.org"
|
||||
)
|
||||
|
||||
val profile = JSONObject(prepared.json).getJSONObject("admin_profile")
|
||||
assertTrue(prepared.ownerProfileFromApp)
|
||||
assertEquals("new-owner-hash-1,new-owner-hash-2", profile.getString("vk_hashes"))
|
||||
assertEquals("new-reserve-hash", profile.getString("secondary_vk_hash"))
|
||||
assertEquals("56100,56101,9100", profile.getString("ports"))
|
||||
assertEquals("owner-phone", profile.getJSONArray("device_ids").getString(0))
|
||||
assertEquals("custom", profile.getString("vpn_dns_selection"))
|
||||
assertEquals("10.0.0.53", profile.getString("vpn_dns_custom"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exportDoesNotMixOwnerProfileFromAnotherServer() {
|
||||
val source = database("client-a", "Телефон")
|
||||
source.getJSONObject("admin_profile").put("vk_hashes", "server-owner-hash")
|
||||
|
||||
val prepared = prepareServerDatabaseForBackup(
|
||||
sourceJson = source.toString(),
|
||||
localOwnerProfile = ServerAdminProfileInfo(vkHashes = "other-server-hash"),
|
||||
localPeer = "other.example.org",
|
||||
sourceHost = "old.example.org"
|
||||
)
|
||||
|
||||
assertFalse(prepared.ownerProfileFromApp)
|
||||
assertEquals(
|
||||
"server-owner-hash",
|
||||
JSONObject(prepared.json).getJSONObject("admin_profile").getString("vk_hashes")
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionTwoBackupRoundTripVerifiesIntegrity() {
|
||||
val source = database("client-a", "Телефон")
|
||||
@@ -377,6 +434,33 @@ class ServerMigrationTest {
|
||||
assertEquals(source.toString(), decoded.passwordsJson)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun versionTwoBackupKeepsOwnerProfileSourceMarker() {
|
||||
val backup = parseBackup(
|
||||
passwordsJson = database("client-a", "Телефон").toString(),
|
||||
wgKeysDat = null,
|
||||
createdAt = "05.08.2026 23:00",
|
||||
sourceHost = "old.example.org",
|
||||
ownerProfileFromApp = true
|
||||
)
|
||||
|
||||
val decoded = parseBackupFile(backupToJson(backup))
|
||||
|
||||
assertTrue(decoded.ownerProfileFromApp)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun backupRejectsAdditionalWireGuardKeyLines() {
|
||||
val keys = List(5) { "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" }.joinToString("\n")
|
||||
|
||||
parseBackup(
|
||||
passwordsJson = database("client-a", "Телефон").toString(),
|
||||
wgKeysDat = keys,
|
||||
createdAt = "05.08.2026 23:00",
|
||||
sourceHost = "old.example.org"
|
||||
)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun versionTwoBackupRejectsChangedDatabase() {
|
||||
val source = database("client-a", "Телефон")
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class TunnelPowerVisualStateTest {
|
||||
@Test
|
||||
fun tunWithoutNetworkIsNotPresentedAsConnected() {
|
||||
assertEquals(
|
||||
TunnelPowerVisualState.NoNetwork,
|
||||
state(
|
||||
running = true,
|
||||
activeWorkers = 0,
|
||||
underlyingNetworkAvailable = false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun zeroWorkersRemainConnectingUntilFirstWorkerAppears() {
|
||||
assertEquals(
|
||||
TunnelPowerVisualState.Connecting,
|
||||
state(
|
||||
running = true,
|
||||
activeWorkers = 0,
|
||||
underlyingNetworkAvailable = true,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
TunnelPowerVisualState.Connected,
|
||||
state(
|
||||
running = true,
|
||||
activeWorkers = 1,
|
||||
underlyingNetworkAvailable = true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deliberateStopAndTrustedWifiWaitingKeepTheirOwnStates() {
|
||||
assertEquals(
|
||||
TunnelPowerVisualState.Stopping,
|
||||
state(stopping = true),
|
||||
)
|
||||
assertEquals(
|
||||
TunnelPowerVisualState.WaitingForTrustedWifi,
|
||||
state(waitingForTrustedWifi = true),
|
||||
)
|
||||
}
|
||||
|
||||
private fun state(
|
||||
running: Boolean = false,
|
||||
waitingForTrustedWifi: Boolean = false,
|
||||
starting: Boolean = false,
|
||||
stopping: Boolean = false,
|
||||
activeWorkers: Int = 0,
|
||||
underlyingNetworkAvailable: Boolean = true,
|
||||
hasConnectionError: Boolean = false,
|
||||
cooldownActive: Boolean = false,
|
||||
): TunnelPowerVisualState = tunnelPowerVisualState(
|
||||
running = running,
|
||||
waitingForTrustedWifi = waitingForTrustedWifi,
|
||||
starting = starting,
|
||||
stopping = stopping,
|
||||
activeWorkers = activeWorkers,
|
||||
underlyingNetworkAvailable = underlyingNetworkAvailable,
|
||||
hasConnectionError = hasConnectionError,
|
||||
cooldownActive = cooldownActive,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user