Files
WDTT-Plus/app/src/test/java/com/wdtt/plus/ui/OutboundWireGuardTest.kt
T
2026-09-11 15:45:55 +03:00

793 lines
35 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 = """
[Interface]
PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
Address = 172.16.0.2/32
DNS = 1.1.1.1
MTU = 1280
Table = auto
[Peer]
PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = engage.cloudflareclient.com:2408
PersistentKeepalive = 25
""".trimIndent()
@Test
fun importedWireGuardConfig_isSanitizedForPolicyRouting() {
val sanitized = sanitizeWireGuardConfigForWdttExit(safeConfig)
assertTrue("Table = off" in sanitized)
assertTrue("MTU = 1280" in sanitized)
assertFalse(Regex("(?im)^\\s*DNS\\s*=").containsMatchIn(sanitized))
assertFalse("Table = auto" in sanitized)
}
@Test
fun importedWireGuardConfig_rejectsCommandsAndUnknownParameters() {
val commandConfig = safeConfig.replace("MTU = 1280", "PostUp = touch /tmp/unsafe")
val unknownConfig = safeConfig.replace("MTU = 1280", "UnsafeOption = true")
assertTrue(validateWireGuardConfigText(commandConfig).isFailure)
assertTrue(validateWireGuardConfigText(unknownConfig).isFailure)
}
@Test
fun importedWireGuardConfig_requiresDefaultIpv4Route() {
val config = safeConfig.replace("0.0.0.0/0, ::/0", "10.0.0.0/8")
assertTrue(validateWireGuardConfigText(config).isFailure)
}
@Test
fun freeWarpScript_hasSafeUpdateChecksAndValidShellSyntax() {
val script = buildFreeWarpInstallScript(1392)
assertTrue(WGCF_VERSION == "2.2.32")
assertTrue(THREEPROXY_VERSION == "0.9.7")
assertTrue("WARP_MTU=1392" in script)
assertTrue("checksums.txt" in script)
assertTrue("sha256sum" in script)
assertTrue("--accept-tos" in script)
assertTrue("wdtt_wgcf_registration_error" in script)
assertTrue("warp_registration_rate_limited" in script)
assertTrue("warp_registration_certificate_failed" in script)
assertTrue("warp_registration_tls_failed" in script)
assertTrue("warp_registration_dns_failed" in script)
assertTrue("warp_registration_network_failed" in script)
assertTrue("warp_registration_rejected" in script)
assertTrue("warp_registration_service_failed" in script)
assertTrue("wdtt-warp-watchdog.timer" in script)
assertTrue("wdtt_warp_autotune" in script)
assertTrue("WARP_ENDPOINT_CANDIDATES" in script)
assertTrue("engage.cloudflareclient.com:2408" in script)
assertTrue("rollback after WARP check error" in script)
assertTrue("trap wdtt_wg_up_cleanup 0" in script)
assertTrue("rollback after WireGuard service start error" in script)
assertTrue("WDTT_ERROR=wireguard_exit_service_inactive" in script)
assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script)
assertShellSyntax(script)
}
@Test
fun freeWarpRegistrationErrorClassifier_distinguishesSafeFailureReasons() {
val script = buildFreeWarpInstallScript()
val classifier = Regex(
"(?ms)^wdtt_wgcf_registration_error\\(\\) \\{.*?^\\}",
).find(script)?.value.orEmpty()
assertTrue("классификатор должен присутствовать в скрипте установки", classifier.isNotBlank())
fun classify(error: String): String {
val log = Files.createTempFile("wdtt-wgcf-error-", ".log").toFile()
return try {
log.writeText(error)
val process = ProcessBuilder(
"bash",
"-c",
"$classifier\nwdtt_wgcf_registration_error \"${'$'}1\"",
"classifier",
log.absolutePath,
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }.trim()
assertEquals(0, process.waitFor())
output
} finally {
log.delete()
}
}
assertEquals("warp_registration_rate_limited", classify("429 Too Many Requests"))
assertEquals("warp_registration_tls_failed", classify("net/http: TLS handshake timeout"))
assertEquals("warp_registration_dns_failed", classify("dial tcp: lookup api.cloudflareclient.com: no such host"))
assertEquals("warp_registration_network_failed", classify("dial tcp: i/o timeout"))
assertEquals("warp_registration_rejected", classify("403 Forbidden error 1020"))
assertEquals("warp_registration_service_failed", classify("500 Internal Server Error"))
assertEquals("warp_registration_certificate_failed", classify("x509: certificate has expired"))
assertEquals("warp_registration_failed", classify("unexpected enrollment response"))
}
@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()
assertTrue("wdtt_clear_external_out" in script)
assertTrue("ip link delete \"${'$'}WDTT_WG_IFACE\"" in script)
assertTrue("WDTT_ERROR=direct_cleanup_failed" in script)
assertTrue("wdtt_write_mode \"direct\"" in script)
assertShellSyntax(script)
}
@Test
fun outboundCleanupScripts_areScopedAndHaveValidShellSyntax() {
val localStop = stopLocalProxyScript()
val localRemove = removeLocalProxyScript()
val external = deleteExternalProxyScript()
val imported = deleteImportedWireGuardExitScript()
val currentVps = deleteWireGuardVpsCurrentScript()
val foreignVps = deleteWireGuardVpsForeignScript()
assertTrue("systemctl disable --now wdtt-3proxy" in localStop)
assertTrue("local_proxy_service_still_active" in localStop)
assertTrue("LOCAL_PROXY_PASSWORD_B64" in localRemove)
assertTrue("local_proxy_remove_failed" in localRemove)
assertTrue("wdtt_clear_proxy_out" in external)
assertTrue("EXTERNAL_PROXY_PASSWORD_B64" in external)
assertTrue("external_proxy_remove_failed" in external)
assertTrue("OWNS_ACTIVE" in imported)
assertTrue("wdtt_clear_wireguard_out" in imported)
assertTrue("IMPORTED_WG_CONFIG_B64" in imported)
assertTrue("wireguard_vps_current_remove_failed" in currentVps)
assertTrue("WDTT_EXIT_FOREIGN" in foreignVps)
assertTrue("foreign_wireguard_not_owned" in foreignVps)
assertShellSyntax(localStop)
assertShellSyntax(localRemove)
assertShellSyntax(external)
assertShellSyntax(imported)
assertShellSyntax(currentVps)
assertShellSyntax(foreignVps)
}
@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
fun serverDiagnosticsScript_hasPortableChecksAndValidShellSyntax() {
val script = serverDiagnosticsScript()
assertTrue("WDTT_SERVER_DIAG" in script)
assertTrue("apt-get dnf yum zypper apk pacman" in script)
assertFalse("diagnostics must not install packages", "apt-get install" in script)
assertFalse("diagnostics must not install packages", "dnf install" in script)
assertFalse("diagnostics must not install packages", "yum install" in script)
assertFalse("diagnostics must not install packages", "zypper --non-interactive install" in script)
assertFalse("diagnostics must not install packages", "apk add" in script)
assertFalse("diagnostics must not install packages", "pacman -Sy" in script)
assertTrue("Диагностика ничего не устанавливала" in script)
assertTrue("systemctl" in script)
assertTrue("iptables" in script)
assertTrue("nft" in script)
assertTrue("VK/OK с VPS (справочно)" in script)
assertTrue("не влияет на основной VK-вход" in script)
assertTrue("login.vk.ru" in script)
assertTrue("api.vk.me" in script)
assertTrue("api.vk.ru" in script)
assertTrue("calls.okcdn.ru" in script)
assertTrue("Получение VK-токенов и решение капчи выполняются на телефоне" in script)
assertFalse("обязательным узлам VK в зоне .ru" in script)
assertTrue("api.telegram.org" in script)
assertTrue("Бесплатный WARP" in script)
assertTrue("api.cloudflareclient.com" in script)
assertTrue("регистрация api.cloudflareclient.com" in script)
assertTrue("engage.cloudflareclient.com" in script)
assertTrue("wdtt_diag_wg_exit_probe" in script)
assertTrue("Cloudflare подтвердил warp=" in script)
assertTrue("WG_POLICY_RULE_ACTIVE" in script)
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)
assertTrue("wdtt_diag_udp_probe" in script)
assertTrue("/dev/net/tun" in script)
assertTrue("admin.sock" in script)
assertFalse("PrivateKey =" in script)
assertShellSyntax(script, shell = "sh")
}
@Test
fun standaloneOwnershipProbe_requiresBothOwnedMarkersAndHasSafeShellSyntax() {
val script = standaloneInstallerOwnershipProbeScript()
assertTrue("/var/lib/wdtt-server-installer/ownership" in script)
assertTrue("/etc/systemd/system/wdtt.service" in script)
assertTrue("Managed by WDTT Plus standalone server installer" in script)
assertTrue("WDTT_STANDALONE_MANAGED=1" in script)
assertTrue("WDTT_STANDALONE_MANAGED=0" in script)
assertTrue("WDTT_ANDROID_DEPLOY_MANAGED=1" in script)
assertTrue("Managed by WDTT Plus Android deploy" in script)
assertTrue("WDTT deploy compatibility: 1" in script)
assertTrue("WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=1" in script)
assertTrue("WDTT_ANDROID_DATA_PRESERVED=1" in script)
assertTrue("WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=1" in script)
assertTrue("WDTT_INSTALL_TRACE=1" in script)
assertTrue("-config-dir[[:space:]]+/etc/wdtt" in script)
assertTrue("grep -Fq 'wdtt0'" in script)
assertTrue("[ ! -L" in script)
assertShellSyntax(script)
val process = ProcessBuilder("bash", "-c", script)
.redirectErrorStream(true)
.start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals(0, process.waitFor())
assertFalse("probe must print real lines, not literal \\n sequences", "\\n" in output)
assertEquals(1, Regex("(?m)^WDTT_STANDALONE_MANAGED=[01]$").findAll(output).count())
assertEquals(1, Regex("(?m)^WDTT_ANDROID_DEPLOY_MANAGED=[01]$").findAll(output).count())
assertEquals(1, Regex("(?m)^WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=[01]$").findAll(output).count())
assertEquals(1, Regex("(?m)^WDTT_ANDROID_DATA_PRESERVED=[01]$").findAll(output).count())
assertEquals(1, Regex("(?m)^WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=[01]$").findAll(output).count())
assertEquals(1, Regex("(?m)^WDTT_INSTALL_TRACE=[01]$").findAll(output).count())
deploymentOwnershipFromProbe(output)
}
@Test
fun existingInstallActions_failClosedForUnknownOrFailedOwnershipCheck() {
val unknown = existingInstallOwnershipFromFlags(
standaloneManaged = false,
androidDeployManaged = false,
legacyAndroidDeployCandidate = false
)
assertFalse(
existingInstallAllowsPreservingUpdate(
ownership = unknown,
checkSucceeded = true
)
)
assertFalse(existingInstallAllowsReset(ownership = unknown, checkSucceeded = true))
val standalone = existingInstallOwnershipFromFlags(
standaloneManaged = true,
androidDeployManaged = false,
legacyAndroidDeployCandidate = false
)
assertFalse(
existingInstallAllowsPreservingUpdate(
ownership = standalone,
checkSucceeded = true
)
)
assertFalse(existingInstallAllowsReset(ownership = standalone, checkSucceeded = true))
val legacy = existingInstallOwnershipFromFlags(
standaloneManaged = false,
androidDeployManaged = false,
legacyAndroidDeployCandidate = true
)
assertTrue(
existingInstallAllowsPreservingUpdate(
ownership = legacy,
checkSucceeded = true
)
)
assertFalse(existingInstallAllowsReset(ownership = legacy, checkSucceeded = true))
val incomplete = existingInstallOwnershipFromFlags(
standaloneManaged = false,
androidDeployManaged = false,
legacyAndroidDeployCandidate = false,
incompleteAndroidDeployCandidate = true
)
assertFalse(
existingInstallAllowsPreservingUpdate(
ownership = incomplete,
checkSucceeded = true
)
)
assertTrue(existingInstallAllowsReset(ownership = incomplete, checkSucceeded = true))
assertFalse(existingInstallAllowsReset(ownership = incomplete, checkSucceeded = false))
val android = existingInstallOwnershipFromFlags(
standaloneManaged = false,
androidDeployManaged = true,
legacyAndroidDeployCandidate = true
)
assertEquals(DeploymentOwnership.AndroidDeploy, android)
assertTrue(existingInstallAllowsReset(ownership = android, checkSucceeded = true))
assertFalse(existingInstallAllowsReset(ownership = android, checkSucceeded = false))
val preserved = existingInstallOwnershipFromFlags(
standaloneManaged = false,
androidDeployManaged = false,
legacyAndroidDeployCandidate = false,
preservedAndroidData = true
)
assertEquals(DeploymentOwnership.PreservedAndroidData, preserved)
assertTrue(existingInstallAllowsPreservingUpdate(preserved, checkSucceeded = true))
assertTrue(existingInstallAllowsReset(preserved, checkSucceeded = true))
}
@Test
fun ownershipProbe_recognizesRealLegacyV14AndroidUnitForPreservingUpdate() {
val root = Files.createTempDirectory("wdtt-v14-owner-probe").toFile()
try {
val binary = File(root, "usr/local/bin/wdtt-server")
val config = File(root, "etc/wdtt")
val unit = File(root, "etc/systemd/system/wdtt.service")
requireNotNull(binary.parentFile).mkdirs()
config.mkdirs()
requireNotNull(unit.parentFile).mkdirs()
binary.writeText("#!/bin/sh\nexit 0\n")
binary.setExecutable(true)
File(config, "passwords.json").writeText("{}\n")
File(config, "wg-keys.dat").writeText("test-only\n")
unit.writeText(
"""
[Service]
ExecStartPre=-/usr/bin/env bash -c "ip link show wdtt0 >/dev/null 2>&1 && ip link del wdtt0 || true"
ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:56000 -wg-port 56001 -config-dir /etc/wdtt -max-passwords 50
""".trimIndent()
)
val process = ProcessBuilder(
"bash",
"-c",
standaloneInstallerOwnershipProbeScript(root.absolutePath)
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals(0, process.waitFor())
val ownership = deploymentOwnershipFromProbe(output)
assertEquals(DeploymentOwnership.LegacyAndroidDeploy, ownership)
assertTrue(existingInstallAllowsPreservingUpdate(ownership, checkSucceeded = true))
assertFalse(existingInstallAllowsReset(ownership, checkSucceeded = true))
} finally {
root.deleteRecursively()
}
}
@Test
fun ownershipProbe_allowsOnlyExactInterruptedAndroidFootprintToBeReset() {
val root = Files.createTempDirectory("wdtt-incomplete-owner-probe").toFile()
try {
val config = File(root, "etc/wdtt")
config.mkdirs()
assertTrue(config.setReadable(false, false))
assertTrue(config.setWritable(false, false))
assertTrue(config.setExecutable(false, false))
assertTrue(config.setReadable(true, true))
assertTrue(config.setWritable(true, true))
assertTrue(config.setExecutable(true, true))
val database = File(config, "passwords.json")
database.writeText("{\"passwords\":{},\"devices\":{}}\n")
assertTrue(database.setReadable(false, false))
assertTrue(database.setWritable(false, false))
assertTrue(database.setExecutable(false, false))
assertTrue(database.setReadable(true, true))
assertTrue(database.setWritable(true, true))
fun probe(): DeploymentOwnership {
val process = ProcessBuilder(
"bash",
"-c",
standaloneInstallerOwnershipProbeScript(root.absolutePath)
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals(0, process.waitFor())
return deploymentOwnershipFromProbe(output)
}
val incomplete = probe()
assertEquals(DeploymentOwnership.IncompleteAndroidDeploy, incomplete)
assertFalse(existingInstallAllowsPreservingUpdate(incomplete, checkSucceeded = true))
assertTrue(existingInstallAllowsReset(incomplete, checkSucceeded = true))
File(config, "foreign.conf").writeText("do-not-touch\n")
assertEquals(DeploymentOwnership.UnknownExisting, probe())
} finally {
root.deleteRecursively()
}
}
@Test
fun ownershipProbe_markedPartialAndroidInstallCanOnlyBeReset() {
val root = Files.createTempDirectory("wdtt-marked-partial-owner-probe").toFile()
try {
val unit = File(root, "etc/systemd/system/wdtt.service")
requireNotNull(unit.parentFile).mkdirs()
unit.writeText(
"""
# Managed by WDTT Plus Android deploy
# WDTT deploy compatibility: 1
[Service]
ExecStartPre=-/usr/bin/env bash -c "ip link show wdtt0 >/dev/null 2>&1 && ip link del wdtt0 || true"
ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:56000 -wg-port 56001 -config-dir /etc/wdtt
""".trimIndent()
)
fun probe(): DeploymentOwnership {
val process = ProcessBuilder(
"bash",
"-c",
standaloneInstallerOwnershipProbeScript(root.absolutePath)
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals(0, process.waitFor())
return deploymentOwnershipFromProbe(output)
}
val incomplete = probe()
assertEquals(DeploymentOwnership.IncompleteAndroidDeploy, incomplete)
assertFalse(existingInstallAllowsPreservingUpdate(incomplete, checkSucceeded = true))
assertTrue(existingInstallAllowsReset(incomplete, checkSucceeded = true))
val binary = File(root, "usr/local/bin/wdtt-server")
requireNotNull(binary.parentFile).mkdirs()
Files.createSymbolicLink(binary.toPath(), File(root, "foreign-server").toPath())
assertEquals(DeploymentOwnership.UnknownExisting, probe())
Files.delete(binary.toPath())
binary.writeText("#!/bin/sh\nexit 0\n")
assertTrue(binary.setExecutable(true))
val config = File(root, "etc/wdtt")
config.mkdirs()
File(config, "wg-keys.dat").writeText("test-only\n")
assertEquals(DeploymentOwnership.IncompleteAndroidDeploy, probe())
File(config, "passwords.json").writeText("{\"passwords\":{},\"devices\":{}}\n")
assertEquals(DeploymentOwnership.AndroidDeploy, probe())
} finally {
root.deleteRecursively()
}
}
@Test
fun ownershipProbe_recognizesPreservedAndroidDataAndExactV17RemovalFootprint() {
val root = Files.createTempDirectory("wdtt-preserved-owner-probe").toFile()
try {
val config = File(root, "etc/wdtt")
config.mkdirs()
assertTrue(config.setReadable(false, false))
assertTrue(config.setWritable(false, false))
assertTrue(config.setExecutable(false, false))
assertTrue(config.setReadable(true, true))
assertTrue(config.setWritable(true, true))
assertTrue(config.setExecutable(true, true))
listOf("passwords.json", "wg-keys.dat").forEach { name ->
File(config, name).apply {
writeText("test-only\n")
assertTrue(setReadable(false, false))
assertTrue(setWritable(false, false))
assertTrue(setExecutable(false, false))
assertTrue(setReadable(true, true))
assertTrue(setWritable(true, true))
}
}
fun probe(): DeploymentOwnership {
val process = ProcessBuilder(
"bash",
"-c",
standaloneInstallerOwnershipProbeScript(root.absolutePath)
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals(0, process.waitFor())
return deploymentOwnershipFromProbe(output)
}
assertEquals(DeploymentOwnership.PreservedAndroidData, probe())
File(config, ".android-deploy-preserved")
.writeText("Preserved by WDTT Plus Android deploy\n")
File(config, "backup-policy.json").writeText("{}\n")
assertEquals(DeploymentOwnership.PreservedAndroidData, probe())
File(config, ".android-deploy-preserved")
.writeText("foreign marker\n")
assertEquals(DeploymentOwnership.UnknownExisting, probe())
} finally {
root.deleteRecursively()
}
}
@Test
fun deploymentOwnership_allowsOnlyStrictLegacyAndroidShapeForPreserveMigration() {
assertEquals(
DeploymentOwnership.LegacyAndroidDeploy,
deploymentOwnershipFromProbe(
"""
WDTT_STANDALONE_MANAGED=0
WDTT_ANDROID_DEPLOY_MANAGED=0
WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=1
WDTT_ANDROID_DATA_PRESERVED=0
WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0
WDTT_INSTALL_TRACE=1
""".trimIndent()
)
)
assertEquals(
DeploymentOwnership.UnknownExisting,
deploymentOwnershipFromProbe(
"""
WDTT_STANDALONE_MANAGED=0
WDTT_ANDROID_DEPLOY_MANAGED=0
WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0
WDTT_ANDROID_DATA_PRESERVED=0
WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0
WDTT_INSTALL_TRACE=1
""".trimIndent()
)
)
assertEquals(
DeploymentOwnership.NoInstall,
deploymentOwnershipFromProbe(
"""
WDTT_STANDALONE_MANAGED=0
WDTT_ANDROID_DEPLOY_MANAGED=0
WDTT_LEGACY_ANDROID_DEPLOY_CANDIDATE=0
WDTT_ANDROID_DATA_PRESERVED=0
WDTT_INCOMPLETE_ANDROID_DEPLOY_CANDIDATE=0
WDTT_INSTALL_TRACE=0
""".trimIndent()
)
)
}
@Test
fun ownershipProbe_doesNotTreatSudoDiscoveryAsSudoInvocation() {
val command = rootCommand("printf 'probe\\n'")
assertTrue("command -v sudo >/dev/null 2>&1" in command)
assertTrue("sudo -S -p '' bash -c" in command)
assertShellSyntax(command)
}
@Test
fun connectWithoutInstall_usesStandaloneDatabaseNotInstallerOwnership() {
val connection = selectExistingServerConnection(
dbJson = """
{
"main_password":"SafeOwnerPassword42",
"admin_id":"",
"bot_token":"",
"dns":"1.1.1.1,1.0.0.1",
"max_passwords":50,
"default_ports":"56000,56001,9000",
"public_ip":"203.0.113.10",
"passwords":{},
"devices":{}
}
""".trimIndent(),
fallbackHost = "198.51.100.10",
adminMainPassword = "SafeOwnerPassword42"
)
assertEquals("203.0.113.10", connection.host)
assertEquals("SafeOwnerPassword42", connection.password)
assertEquals(56000, connection.ports.first)
assertEquals(56001, connection.ports.second)
assertEquals(9000, connection.ports.third)
assertEquals("1.1.1.1", connection.dns1)
assertEquals("1.0.0.1", connection.dns2)
}
@Test
fun externalProxyTransparentCheck_doesNotCaptureRootXrayTraffic() {
val script = outboundShellPrelude()
assertTrue("umask 077" in script)
assertTrue("install -d -m 0700 /etc/wdtt /etc/wdtt/outbound" in script)
assertTrue("chmod 0600 /etc/wdtt/outbound.json" in script)
assertTrue("WDTT_PROXY_TEST_SOURCE=\"${'$'}test_source\"" in script)
assertTrue("iptables -t nat -I OUTPUT -s \"${'$'}test_source\" -p tcp -j WDTT_PROXY_TEST" in script)
assertTrue("curl --interface \"${'$'}test_source\"" in script)
assertFalse("iptables -t nat -I OUTPUT -p tcp -m owner --uid-owner 0 -j WDTT_PROXY_TEST" in script)
assertShellSyntax(script)
}
@Test
fun outboundSnapshot_preservesExplicitlySavedEmptyFields() {
val script = outboundSnapshotScript()
assertTrue("wdtt_profile_has_key" in script)
assertTrue("if wdtt_profile_has_key LOCAL_PROXY_LOGIN_B64" in script)
assertTrue("if wdtt_profile_has_key EXTERNAL_PROXY_HOST_B64" in script)
assertTrue("if wdtt_profile_has_key WG_VPS_DNS_B64" in script)
assertTrue("! wdtt_profile_has_key IMPORTED_WG_CONFIG_B64" in script)
assertTrue("WDTT_LOCAL_PROXY_SERVICE_ENABLED" in script)
assertTrue("WDTT_EXTERNAL_PROXY_SERVICE_ENABLED" in script)
assertTrue("WDTT_WG_SERVICE_ENABLED" in script)
assertShellSyntax(script)
}
@Test
fun detailedOutboundStatus_reportsRoutesAndAutostart() {
val script = outboundStatusScript()
assertTrue("Автозапуск внешнего TCP-прокси" in script)
assertTrue("Правило маршрутизации подсети WDTT" in script)
assertTrue("NAT WireGuard-выхода" in script)
assertShellSyntax(script)
}
@Test(expected = IllegalArgumentException::class)
fun freeWarpScript_rejectsUnsafeMtu() {
buildFreeWarpInstallScript(1600)
}
private fun assertShellSyntax(script: String, shell: String = "bash") {
val file = File.createTempFile("wdtt-warp-", ".sh")
try {
file.writeText(script)
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()
}
}
}