refactor(ssh): типизированный результат вместо строк ERROR

Вывод удалённой команды, начинавшийся с ERROR, был неотличим от отказа транспорта. connectSsh отдаёт Boolean, отпечаток берётся из activeSshConfig.
This commit is contained in:
samosvalishe committed 2026-09-20 10:06:54 +03:00
1 parent 2d4ce0af2d
commit 2cfa906606
6 files changed
+63 -46

No files matched your search

@@ -7,13 +7,6 @@ object ControlResponseParser {
val text = raw.trim()
if (text.isEmpty()) return err("internal", "empty output")
// Транспортная ошибка SSHManager / sudo: JSON в stdout нет.
val firstLine = text.lineSequence().firstOrNull()?.trim().orEmpty()
if (firstLine.startsWith("ERROR:")) {
val m = text.removePrefix("ERROR:").trim()
return err(transportCode(m), m)
}
// MOTD/banner/.bashrc или sudo-остаток могли попасть ПЕРЕД нашим
// единственным JSON-объектом - берём последнюю строку, начинающуюся с '{'.
val jsonLine = text.lineSequence().lastOrNull { it.trimStart().startsWith("{") }
@@ -26,6 +19,8 @@ object ControlResponseParser {
}
}
fun transportFailure(message: String): ControlResponse = err(transportCode(message), message)
private fun transportCode(msg: String): String = when {
msg.contains("sudo", ignoreCase = true) && msg.contains("password", ignoreCase = true) -> "sudo_auth_failed"
msg.contains("a terminal is required", ignoreCase = true) || msg.contains("requiretty", ignoreCase = true) -> "sudo_requiretty"
@@ -5,6 +5,7 @@ import com.freeturn.app.data.config.SshConfig
import com.freeturn.app.data.control.ControlResponse
import com.freeturn.app.data.control.ControlResponseParser
import com.freeturn.app.domain.ssh.SSHManager
import com.freeturn.app.domain.ssh.SshResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -45,7 +46,7 @@ class ServerControl(
} else {
script
}
val output = ssh.executeWithStdin(
val result = ssh.executeWithStdin(
ip = cfg.ip,
port = cfg.port,
user = cfg.username,
@@ -55,7 +56,10 @@ class ServerControl(
knownFingerprint = cfg.hostFingerprint.ifEmpty { null },
sshKey = if (cfg.authType == SshConfig.AUTH_SSH_KEY) cfg.sshKey else ""
)
ControlResponseParser.parse(output)
when (result) {
is SshResult.Output -> ControlResponseParser.parse(result.text)
is SshResult.Failure -> ControlResponseParser.transportFailure(result.message)
}
}
/**
@@ -63,13 +67,13 @@ class ServerControl(
* null - транспортная ошибка (соединение не удалось).
*/
suspend fun detectRootMode(cfg: SshConfig): String? = withContext(Dispatchers.IO) {
val out = ssh.executeSilentCommand(
val result = ssh.executeSilentCommand(
cfg.ip, cfg.port, cfg.username, cfg.password,
"id -u; command -v sudo >/dev/null 2>&1 && { sudo -n true 2>/dev/null && echo FT_SUDO_NOPASS || echo FT_SUDO_PASS; }",
knownFingerprint = cfg.hostFingerprint.ifEmpty { null },
sshKey = if (cfg.authType == SshConfig.AUTH_SSH_KEY) cfg.sshKey else ""
)
if (out.startsWith("ERROR:")) null else classifyRootMode(out)
(result as? SshResult.Output)?.let { classifyRootMode(it.text) }
}
/**
@@ -15,6 +15,12 @@ import java.util.Properties
private const val CONNECT_TIMEOUT_MS = 5000
sealed interface SshResult {
/** stdout+stderr команды (`exec 2>&1`). */
data class Output(val text: String) : SshResult
data class Failure(val message: String) : SshResult
}
class SSHManager {
@Volatile var lastSeenFingerprint: String? = null
@@ -25,7 +31,7 @@ class SSHManager {
knownFingerprint: String? = null,
sshKey: String = "",
execTimeoutMs: Int = 30_000
): String = exec(ip, port, user, pass, command, null, knownFingerprint, sshKey, execTimeoutMs)
): SshResult = exec(ip, port, user, pass, command, null, knownFingerprint, sshKey, execTimeoutMs)
suspend fun executeWithStdin(
ip: String, port: Int, user: String, pass: String,
@@ -33,22 +39,22 @@ class SSHManager {
knownFingerprint: String? = null,
sshKey: String = "",
execTimeoutMs: Int = 180_000
): String = exec(ip, port, user, pass, command, stdin, knownFingerprint, sshKey, execTimeoutMs)
): SshResult = exec(ip, port, user, pass, command, stdin, knownFingerprint, sshKey, execTimeoutMs)
private suspend fun exec(
ip: String, port: Int, user: String, pass: String,
command: String, stdin: String?,
knownFingerprint: String?, sshKey: String, execTimeoutMs: Int
): String = withContext(Dispatchers.IO) {
): SshResult = withContext(Dispatchers.IO) {
val tofu = TofuHostKeyRepository(knownFingerprint)
var session: Session? = null
try {
session = connectSession(ip, port, user, pass, sshKey, tofu)
lastSeenFingerprint = verifyConnectedFingerprint(knownFingerprint, tofu.capturedFingerprint)
session.timeout = execTimeoutMs
runCommand(session, command, stdin, execTimeoutMs)
SshResult.Output(runCommand(session, command, stdin, execTimeoutMs))
} catch (e: Exception) {
mitmOrError(e, tofu, knownFingerprint)
SshResult.Failure(failureMessage(e, tofu, knownFingerprint))
} finally {
session?.disconnect()
}
@@ -96,16 +102,16 @@ class SSHManager {
return output.trim()
}
private fun mitmOrError(e: Exception, tofu: TofuHostKeyRepository, knownFingerprint: String?): String {
private fun failureMessage(e: Exception, tofu: TofuHostKeyRepository, knownFingerprint: String?): String {
val isMitm = tofu.capturedFingerprint != null &&
knownFingerprint != null &&
tofu.capturedFingerprint != knownFingerprint
return if (isMitm) {
"ERROR: Отпечаток сервера изменился - возможна MITM-атака\n" +
"Отпечаток сервера изменился - возможна MITM-атака\n" +
"Ожидался: $knownFingerprint\n" +
"Получен: ${tofu.capturedFingerprint}"
} else {
"ERROR: ${e.message}"
e.message ?: e.javaClass.simpleName
}
}
@@ -26,11 +26,9 @@ import kotlinx.serialization.json.contentOrNull
import java.time.LocalTime
import java.time.format.DateTimeFormatter
class SshRepository(
context: Context,
private val sshManager: SSHManager = SSHManager(),
private val serverControl: ServerControl = ServerControl(context, sshManager)
) {
class SshRepository(context: Context, private val sshManager: SSHManager) {
private val serverControl = ServerControl(context, sshManager)
// Параллельные команды на одном SSHManager затирали бы fingerprint/_serverState.
private val mutex = Mutex()
@@ -93,33 +91,40 @@ class SshRepository(
return result
}
private suspend fun runEcho(cfg: SshConfig): String {
private suspend fun runEcho(cfg: SshConfig): SshResult {
logHeader("Подключение", "${cfg.username}@${cfg.ip}:${cfg.port}")
val result = sshManager.executeSilentCommand(
cfg.ip, cfg.port, cfg.username, cfg.password, "echo OK",
knownFingerprint = cfg.hostFingerprint.ifEmpty { null },
sshKey = if (cfg.authType == SshConfig.AUTH_SSH_KEY) cfg.sshKey else ""
)
appendSshLog(result.lines().filter { it.isNotBlank() })
when (result) {
is SshResult.Output -> appendSshLog(result.text.lines().filter { it.isNotBlank() })
is SshResult.Failure -> appendSshLog("ERROR: ${result.message}")
}
return result
}
suspend fun connectSsh(config: SshConfig): Pair<Boolean, String?> = mutex.withLock {
suspend fun connectSsh(config: SshConfig): Boolean = mutex.withLock {
_sshState.value = SshConnectionState.Connecting
val result = runEcho(config)
// Сравниваем построчно, а не весь вывод: серверный MOTD/banner или строки
// из .bashrc могут попасть в stdout перед "OK" и сломать строгое равенство.
if (result.lines().any { it.trim() == "OK" }) {
if (result is SshResult.Output && result.text.lines().any { it.trim() == "OK" }) {
val fp = sshManager.lastSeenFingerprint ?: config.hostFingerprint
// Сохранённый rootMode мог устареть между SSH-сессиями.
val mode = serverControl.detectRootMode(config) ?: config.rootMode
activeSshConfig = config.copy(hostFingerprint = fp, rootMode = mode)
_sshState.value = SshConnectionState.Connected(config.ip)
checkServerStateLocked(activeSshConfig, silent = false)
Pair(true, sshManager.lastSeenFingerprint)
true
} else {
_sshState.value = SshConnectionState.Error(result.removePrefix("ERROR: "))
Pair(false, null)
val message = when (result) {
is SshResult.Failure -> result.message
is SshResult.Output -> result.text
}
_sshState.value = SshConnectionState.Error(message)
false
}
}
@@ -1,6 +1,5 @@
package com.freeturn.app.viewmodel.server
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences
@@ -12,7 +11,8 @@ import com.freeturn.app.domain.proxy.ProxyOrchestrator
import com.freeturn.app.domain.ServerState
import com.freeturn.app.domain.SshConnectionState
import com.freeturn.app.domain.ssh.SshRepository
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.viewmodel.HapticEvent
import com.freeturn.app.viewmodel.Haptics
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
@@ -25,11 +25,9 @@ class ServerViewModel(
private val sshRepository: SshRepository,
private val prefs: AppPreferences,
private val orchestrator: ProxyOrchestrator,
context: Context
private val haptics: Haptics
) : ViewModel() {
private val appContext = context.applicationContext
val sshState: StateFlow<SshConnectionState> = sshRepository.sshState
val serverState: StateFlow<ServerState> = sshRepository.serverState
val sshLog: StateFlow<List<String>> = sshRepository.sshLog
@@ -65,19 +63,20 @@ class ServerViewModel(
fun connectSsh(config: SshConfig) {
viewModelScope.launch {
prefs.saveSshConfig(config)
val (success, fp) = sshRepository.connectSsh(config)
if (success) {
if (config.hostFingerprint.isEmpty() && fp != null) {
prefs.saveSshFingerprint(fp)
if (sshRepository.connectSsh(config)) {
val active = sshRepository.activeSshConfig
if (config.hostFingerprint.isEmpty()) {
active?.hostFingerprint?.takeIf { it.isNotEmpty() }
?.let { prefs.saveSshFingerprint(it) }
}
// Детект rootMode живёт только в сессии; без персиста cleanup/share
// (factory, читают сохранённый cfg) упирались бы в stale needs_root.
sshRepository.activeSshConfig?.rootMode
active?.rootMode
?.takeIf { it != config.rootMode }
?.let { prefs.saveSshRootMode(it) }
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
haptics.perform(HapticEvent.SUCCESS)
} else {
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
}
}
}
@@ -46,16 +46,24 @@ class ControlResponseParserTest {
}
@Test
fun `transport ERROR prefix maps to err`() {
val r = ControlResponseParser.parse("ERROR: connection refused")
fun `transport failure maps to err`() {
val r = ControlResponseParser.transportFailure("connection refused")
assertFalse(r.isOk)
assertEquals("transport", r.code)
assertEquals("connection refused", r.msg)
}
@Test
fun `ERROR prefix in output is kept as output`() {
val r = ControlResponseParser.parse("ERROR: something printed by the host")
assertFalse(r.isOk)
assertEquals("ERROR: something printed by the host", r.msg)
}
// sudo пишет отказ в stderr, он в общем выводе (exec 2>&1) вместо JSON.
@Test
fun `sudo password failure detected`() {
val r = ControlResponseParser.parse("ERROR: sudo: a password is required")
val r = ControlResponseParser.parse("sudo: a password is required")
assertEquals("sudo_auth_failed", r.code)
}