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