From 3793d2f133da756bbe0783b14c9e4ed634c73a4c Mon Sep 17 00:00:00 2001 From: Terry Wang Date: Mon, 16 Nov 2026 23:05:19 +0800 Subject: [PATCH 1/3] feat: attach to the machines a host's Herdr saved Herdr's own client switches between Local and the SSH machines saved with herdr machine add, each a server of its own; running herdr --remote inside a pane only shows the other server as that pane's terminal. Bellterm now lists a host's saved machines in the session drawer and attaches to one through the host: a route may carry a relay target, and every remote command then runs as ssh with the bridge's policy on the host, so the host's keys, configuration and known hosts sign in. Unreachable targets report the host's ssh error. Each machine is saved as a node via its host. Refs #29 --- .github/workflows/ci.yml | 50 ++++++++++++ README.md | 16 ++++ app/src/main/java/app/bellterm/BelltermApp.kt | 12 +++ .../main/java/app/bellterm/core/Machines.kt | 18 +++++ app/src/main/java/app/bellterm/core/Native.kt | 7 ++ app/src/main/java/app/bellterm/core/Routes.kt | 11 ++- app/src/main/java/app/bellterm/data/Node.kt | 10 ++- .../main/java/app/bellterm/data/NodeStore.kt | 33 +++++++- .../main/java/app/bellterm/ui/MainActivity.kt | 1 + .../java/app/bellterm/ui/nodes/NodesScreen.kt | 9 ++- .../app/bellterm/ui/session/SessionDrawer.kt | 30 +++++++- .../app/bellterm/ui/session/SessionScreen.kt | 53 ++++++++++++- app/src/main/res/values-zh/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../java/app/bellterm/core/MachinesTest.kt | 17 +++++ .../test/java/app/bellterm/core/RoutesTest.kt | 17 +++++ crates/herdr-client/src/external_bridge.rs | 9 +++ .../herdr-client/src/external_bridge/tests.rs | 40 ++++++++++ crates/herdr-client/src/lib.rs | 3 +- crates/herdr-client/src/ssh.rs | 17 +++++ native/src/config.rs | 20 +++++ native/src/error.rs | 4 + native/src/jni_api.rs | 19 ++++- native/src/lib.rs | 1 + native/src/machines.rs | 76 +++++++++++++++++++ native/src/machines/tests.rs | 66 ++++++++++++++++ native/src/ssh/mod.rs | 59 +++++++++++++- native/tests/live_ssh.rs | 70 ++++++++++++++++- 28 files changed, 651 insertions(+), 21 deletions(-) create mode 100644 app/src/main/java/app/bellterm/core/Machines.kt create mode 100644 app/src/test/java/app/bellterm/core/MachinesTest.kt create mode 100644 native/src/machines.rs create mode 100644 native/src/machines/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d451d1..91253f7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,6 +89,56 @@ jobs: if-no-files-found: error retention-days: 14 + # Issue #29: Herdr's own client switches to the machines its host saved with + # `herdr machine add`; Bellterm lists them and attaches through the host's + # ssh. Host and machine are two Herdr sessions behind one local sshd. + saved-machine: + name: Saved machine through its host + needs: android + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: live-ssh + path: live + + - name: sshd, Herdr, and a saved machine + run: | + [ -x /usr/sbin/sshd ] || sudo apt-get install -y openssh-server > /dev/null + sudo mkdir -p /run/sshd + mkdir -p ~/.ssh ~/sshd && chmod 700 ~/.ssh + ssh-keygen -q -t ed25519 -N '' -f ~/sshd/host + ssh-keygen -q -t ed25519 -N '' -f ~/.ssh/id_ed25519 + ssh-keygen -q -t ed25519 -N '' -f ~/bellterm-key + cat ~/.ssh/id_ed25519.pub ~/bellterm-key.pub >> ~/.ssh/authorized_keys + chmod 600 ~/.ssh/authorized_keys + printf '%s\n' 'Port 2222' 'ListenAddress 127.0.0.1' "HostKey $HOME/sshd/host" \ + "PidFile $HOME/sshd/pid" 'UsePAM no' 'PasswordAuthentication no' 'StrictModes no' > ~/sshd/config + /usr/sbin/sshd -f ~/sshd/config -E ~/sshd/log + ssh-keyscan -p 2222 -t ed25519 127.0.0.1 >> ~/.ssh/known_hosts 2> /dev/null + curl -fsSL https://herdr.dev/install.sh | sh + export PATH="$HOME/.local/bin:$PATH" + herdr machine add "ssh://$(id -un)@127.0.0.1:2222" --remote-session machine --label b-machine < /dev/null + herdr --session machine workspace create --label on-b --no-focus + herdr machine list --json + + - name: List the machine and attach through its host + run: | + export BELLTERM_LIVE_HOST=127.0.0.1 BELLTERM_LIVE_PORT=2222 BELLTERM_LIVE_USER="$(id -un)" + export BELLTERM_LIVE_KEY="$HOME/bellterm-key" + export BELLTERM_LIVE_MACHINE=b-machine BELLTERM_LIVE_MACHINE_WORKSPACE=on-b + chmod +x live/live_ssh + RUST_BACKTRACE=1 live/live_ssh --ignored --nocapture --exact attaches_to_a_saved_machine_through_its_host + + - name: sshd and Herdr state + if: failure() + run: | + cat ~/sshd/log || true + PATH="$HOME/.local/bin:$PATH" herdr machine status --json || true + # Issue #25: a Windows OpenSSH host runs cmd.exe or PowerShell, never # /bin/sh. A fresh admin user without Herdr goes through the app's flow: # install prompt, install over SSH, attach, update, attach. diff --git a/README.md b/README.md index ab985b4..fa56839 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,15 @@ loader only supports from Android 10. - **Jump hosts.** A node can name another node as its jump host, which can have its own, as `ssh -J a,b host` does. Every hop's host key is checked and trusted separately; the trust prompt names the hop. +- **Herdr's saved machines.** When Herdr on a host has saved SSH machines + with `herdr machine add`, the session drawer lists them under **Machines** + with the host itself, as Herdr's own sidebar does. Tapping one opens its + session, reached through the host: the host's own `ssh` signs in to the + machine with its keys, configuration, and known hosts, so the machine needs + nothing new from the phone. Each machine is saved as a node shown *via* its + host, removed along with the host. Running `herdr --remote` inside a pane + instead shows the other server only as that pane's terminal, since + Bellterm's workspaces are those of the server it attached to. - **Keys and certificates.** **Keys & certificates** (the lock icon) holds the device key generated on the phone, generated keys, and imported OpenSSH private keys (RSA, ECDSA, Ed25519; a passphrase is used once to decrypt). @@ -312,6 +321,13 @@ again. CI runs it against Windows OpenSSH on a `windows-2025` runner, once with `cmd.exe` and once with PowerShell as the default shell. The test binary is built on Linux and runs in WSL there, which shares the runner's localhost. +`attaches_to_a_saved_machine_through_its_host` needs the host's Herdr to have +saved a machine labelled `BELLTERM_LIVE_MACHINE`, whose session has a +workspace labelled `BELLTERM_LIVE_MACHINE_WORKSPACE`: it lists the host's +machines, attaches to that one through the host, and checks that an +unreachable target reports the host's `ssh` error. CI runs it with the host +and the machine as two Herdr sessions behind one local sshd. + Set `BELLTERM_LIVE_JUMP_PORT` to reach the target through a jump host on the same address, and `BELLTERM_LIVE_CERT` to a certificate for the key to sign in with it (point the target's `TrustedUserCAKeys` at the CA and its diff --git a/app/src/main/java/app/bellterm/BelltermApp.kt b/app/src/main/java/app/bellterm/BelltermApp.kt index c5a7a25..b55f1c4 100644 --- a/app/src/main/java/app/bellterm/BelltermApp.kt +++ b/app/src/main/java/app/bellterm/BelltermApp.kt @@ -6,6 +6,8 @@ import android.app.NotificationManager import android.content.Context import app.bellterm.core.Connection import app.bellterm.core.HerdrSetup +import app.bellterm.core.Machine +import app.bellterm.core.Machines import app.bellterm.core.Native import app.bellterm.core.Routes import app.bellterm.data.AppLanguages @@ -138,6 +140,16 @@ class BelltermApp : Application() { } } + /** + * The machines Herdr on [host] saved, reached over a connection of their + * own. Uses saved passwords only. Call off the main thread. + */ + fun machines(host: Node): Result> { + if (passwordsToAsk(host).isNotEmpty()) return Result.failure(IllegalStateException(getString(R.string.machines_need_password))) + val document = routeDocument(host, emptyMap(), dark = false, remember = false).getOrElse { return Result.failure(it) } + return runCatching { Machines.parse(Native.listMachines(document)) } + } + /** Nodes on [node]'s route that sign in with a password and have none saved. */ fun passwordsToAsk(node: Node): List = nodes.route(node).getOrNull()?.let { route -> Routes.unsavedPasswordHops(route) { keychain.hasPassword(it.id) } }.orEmpty() diff --git a/app/src/main/java/app/bellterm/core/Machines.kt b/app/src/main/java/app/bellterm/core/Machines.kt new file mode 100644 index 0000000..c6591a9 --- /dev/null +++ b/app/src/main/java/app/bellterm/core/Machines.kt @@ -0,0 +1,18 @@ +package app.bellterm.core + +import org.json.JSONArray + +/** An SSH machine Herdr on a host saved with `herdr machine add`. */ +data class Machine(val label: String, val target: String, val session: String) + +object Machines { + /** What [Native.listMachines] returns; the core already dropped disabled machines. */ + fun parse(json: String): List { + val array = JSONArray(json) + return List(array.length()) { + val o = array.getJSONObject(it) + val target = o.getString("target") + Machine(label = o.optString("label").ifBlank { target }, target = target, session = o.optString("session").ifBlank { "default" }) + } + } +} diff --git a/app/src/main/java/app/bellterm/core/Native.kt b/app/src/main/java/app/bellterm/core/Native.kt index 86d2e8d..819ff5c 100644 --- a/app/src/main/java/app/bellterm/core/Native.kt +++ b/app/src/main/java/app/bellterm/core/Native.kt @@ -32,6 +32,13 @@ object Native { */ external fun setupHerdr(configJson: String): String + /** + * The SSH machines Herdr on the route document's last host has saved, as + * a JSON array of `{id, label, target, session, enabled}`. Blocks for up + * to half a minute; throws when the host cannot be reached or list them. + */ + external fun listMachines(configJson: String): String + /** `{"private": …, "info": {algorithm, fingerprint, comment, public}}`; throws when unreadable. */ external fun importKey(text: String, passphrase: String?): String diff --git a/app/src/main/java/app/bellterm/core/Routes.kt b/app/src/main/java/app/bellterm/core/Routes.kt index bcc79d7..a70ef1b 100644 --- a/app/src/main/java/app/bellterm/core/Routes.kt +++ b/app/src/main/java/app/bellterm/core/Routes.kt @@ -10,13 +10,17 @@ import org.json.JSONObject /** * Builds the route document `native/src/config.rs` reads: every jump host in - * order, then the node, each with its pinned host key and credential. Private + * order, then the node, each with its pinned host key and credential. A saved + * machine is no SSH hop of ours: its jump host's `ssh` relays to it. Private * keys and saved passwords are decrypted from the keychain here and go * straight to the core; a password typed for this connection wins. */ object Routes { + /** The nodes in [route] Bellterm itself signs in to. */ + fun sshHops(route: List): List = if (route.lastOrNull()?.machine != null) route.dropLast(1) else route + /** Nodes in [route] that sign in with a password. */ - fun passwordHops(route: List): List = route.filter { it.auth == AuthMethod.Password } + fun passwordHops(route: List): List = sshHops(route).filter { it.auth == AuthMethod.Password } /** Password nodes in [route] with no saved password, which must be asked for. */ fun unsavedPasswordHops(route: List, saved: (Node) -> Boolean): List = @@ -32,7 +36,7 @@ object Routes { ): String { val target = route.last() val hops = JSONArray() - for (node in route) { + for (node in sshHops(route)) { val auth = when (node.auth) { AuthMethod.Password -> JSONObject().put("type", "password").put("password", passwords[node.id] ?: keychain.password(node.id).orEmpty()) AuthMethod.Key -> JSONObject() @@ -52,6 +56,7 @@ object Routes { return JSONObject() .put("session", target.session) .put("hops", hops) + .put("relay", target.machine) .put("keepalive_secs", target.keepAlive) .put("cols", grid[0]) .put("rows", grid[1]) diff --git a/app/src/main/java/app/bellterm/data/Node.kt b/app/src/main/java/app/bellterm/data/Node.kt index 1286509..cf6ff66 100644 --- a/app/src/main/java/app/bellterm/data/Node.kt +++ b/app/src/main/java/app/bellterm/data/Node.kt @@ -9,6 +9,10 @@ enum class AuthMethod { Key, Password } * A saved SSH server: a machine whose Herdr daemon Bellterm attaches to, or a * jump host on the way to one. A node reached through another names it in * [jumpId]; chains are resolved by [NodeStore.route]. + * + * A node with a [machine] is one of the SSH machines Herdr on its jump host + * saved with `herdr machine add`: the jump host's own `ssh` reaches + * [machine], so its address, user, and credentials here are unused. */ data class Node( val id: String = UUID.randomUUID().toString(), @@ -26,9 +30,11 @@ data class Node( /** SSH keepalive in seconds; 0 turns it off. */ val keepAlive: Int = 15, val lastUsed: Long = 0, + /** The SSH target the jump host's Herdr saved this machine under. */ + val machine: String? = null, ) { val title: String get() = name.ifBlank { address } - val destination: String get() = if (port == 22) "$user@$address" else "$user@$address:$port" + val destination: String get() = machine ?: if (port == 22) "$user@$address" else "$user@$address:$port" /** How the known-hosts list names this server, as the SSH layer does. */ val hostKeyName: String get() = "$address:$port" @@ -47,6 +53,7 @@ data class Node( .put("color", color) .put("keepalive", keepAlive) .put("last_used", lastUsed) + .put("machine", machine) companion object { fun fromJson(o: JSONObject) = Node( @@ -63,6 +70,7 @@ data class Node( color = o.optInt("color"), keepAlive = o.optInt("keepalive", 15), lastUsed = o.optLong("last_used"), + machine = o.optString("machine").takeUnless { o.isNull("machine") || it.isEmpty() }, ) /** Herdr session names are plain path components. */ diff --git a/app/src/main/java/app/bellterm/data/NodeStore.kt b/app/src/main/java/app/bellterm/data/NodeStore.kt index c791a0d..be7a217 100644 --- a/app/src/main/java/app/bellterm/data/NodeStore.kt +++ b/app/src/main/java/app/bellterm/data/NodeStore.kt @@ -51,9 +51,34 @@ class NodeStore(context: Context) { save(_nodes.value.map { byId.getValue(it.id) } + added.filter { new -> _nodes.value.none { it.id == new.id } }) } - /** Removes the node; nodes that jumped through it now connect directly. */ + /** + * Removes the node with the machines it saved, which only it can reach; + * other nodes that jumped through it now connect directly. + */ fun delete(node: Node) { - save(_nodes.value.filterNot { it.id == node.id }.map { if (it.jumpId == node.id) it.copy(jumpId = null) else it }) + save( + _nodes.value + .filterNot { it.id == node.id || (it.machine != null && it.jumpId == node.id) } + .map { if (it.jumpId == node.id) it.copy(jumpId = null) else it }, + ) + } + + /** The node for [host]'s saved machine [target] and [session], added when new. */ + fun machine(host: Node, label: String, target: String, session: String): Node { + _nodes.value.firstOrNull { it.jumpId == host.id && it.machine == target && it.session == session }?.let { return it } + val node = Node( + name = label, + address = target, + user = host.user, + session = session, + jumpId = host.id, + group = host.group, + color = host.color, + keepAlive = host.keepAlive, + machine = target, + ) + upsert(node) + return node } fun touch(node: Node) { @@ -75,9 +100,9 @@ class NodeStore(context: Context) { return Result.success(chain.toList()) } - /** Nodes that may serve as [node]'s jump host without making a loop. */ + /** Nodes that may serve as [node]'s jump host without making a loop; never a saved machine. */ fun jumpCandidates(node: Node?): List = _nodes.value.filter { candidate -> - candidate.id != node?.id && generateSequence(candidate) { get(it.jumpId) }.take(Node.MAX_HOPS).none { it.id == node?.id } + candidate.id != node?.id && candidate.machine == null && generateSequence(candidate) { get(it.jumpId) }.take(Node.MAX_HOPS).none { it.id == node?.id } } // Known hosts: "host:port" -> "SHA256:…", as the SSH layer names them. diff --git a/app/src/main/java/app/bellterm/ui/MainActivity.kt b/app/src/main/java/app/bellterm/ui/MainActivity.kt index 8d34e47..bac6be4 100644 --- a/app/src/main/java/app/bellterm/ui/MainActivity.kt +++ b/app/src/main/java/app/bellterm/ui/MainActivity.kt @@ -171,6 +171,7 @@ class MainActivity : ComponentActivity() { opened.value = null screen = "nodes" }, + onOpen = { open(it) }, ) } } diff --git a/app/src/main/java/app/bellterm/ui/nodes/NodesScreen.kt b/app/src/main/java/app/bellterm/ui/nodes/NodesScreen.kt index 81f2653..4693b3f 100644 --- a/app/src/main/java/app/bellterm/ui/nodes/NodesScreen.kt +++ b/app/src/main/java/app/bellterm/ui/nodes/NodesScreen.kt @@ -209,7 +209,7 @@ fun NodesScreen(app: BelltermApp, navigation: NodesNavigation) { NodeCard( node = node, jump = app.nodes.get(node.jumpId), - hasCertificate = node.auth == AuthMethod.Key && identities.firstOrNull { it.id == (node.identityId ?: Keychain.DEVICE) }?.certificate != null, + hasCertificate = node.machine == null && node.auth == AuthMethod.Key && identities.firstOrNull { it.id == (node.identityId ?: Keychain.DEVICE) }?.certificate != null, connection = connections[node.id], onOpen = { navigation.open(node) }, onEdit = { navigation.edit(node) }, @@ -389,8 +389,11 @@ private fun NodeCard( } GlassMenu(expanded = menu, onDismissRequest = { menu = false }) { MenuItem(R.string.connect, Icons.Default.PlayArrow) { menu = false; onOpen() } - MenuItem(R.string.edit, Icons.Default.Edit) { menu = false; onEdit() } - MenuItem(R.string.duplicate, Icons.Default.Add) { menu = false; onDuplicate() } + // A saved machine is defined by its host's Herdr, not here. + if (node.machine == null) { + MenuItem(R.string.edit, Icons.Default.Edit) { menu = false; onEdit() } + MenuItem(R.string.duplicate, Icons.Default.Add) { menu = false; onDuplicate() } + } if (connection != null) { MenuItem(R.string.disconnect, Icons.Default.Close) { menu = false; onDisconnect() } } diff --git a/app/src/main/java/app/bellterm/ui/session/SessionDrawer.kt b/app/src/main/java/app/bellterm/ui/session/SessionDrawer.kt index 5c1fded..9456f2d 100644 --- a/app/src/main/java/app/bellterm/ui/session/SessionDrawer.kt +++ b/app/src/main/java/app/bellterm/ui/session/SessionDrawer.kt @@ -61,7 +61,8 @@ import app.bellterm.ui.theme.color * Herdr's sidebar as a navigation drawer: every workspace with its branch and * the daemon's status dot, and every agent. A long press on a workspace * offers renaming or closing it. Tabs are switched from the session's own tab - * row, not here. + * row, not here. Like Herdr's own client, it also lists the host and the SSH + * machines its Herdr saved, each a session of its own. */ @Composable fun SessionDrawer( @@ -74,6 +75,9 @@ fun SessionDrawer( onNewWorkspace: () -> Unit, onRenameWorkspace: (Workspace) -> Unit, onCloseWorkspace: (Workspace) -> Unit, + /** The host first, then its machines; empty when it saved none. */ + machines: List, + onMachine: (MachineRow) -> Unit, ) { ModalDrawerSheet( drawerShape = RoundedCornerShape(topEnd = 32.dp, bottomEnd = 32.dp), @@ -162,11 +166,35 @@ fun SessionDrawer( ) } } + if (machines.isNotEmpty()) { + item { SectionLabel(stringResource(R.string.machines)) } + items(machines, key = { "m" + it.key }) { machine -> + DrawerRow( + selected = machine.current, + accent = accent, + onClick = { onMachine(machine) }, + leading = { NodeAvatar(machine.label, machine.color, size = 24.dp) }, + title = machine.label, + detail = machine.target + if (machine.session != "default") " · ${machine.session}" else "", + modifier = Modifier.testTag("machine:${machine.label}"), + ) + } + } item { Spacer(Modifier.size(24.dp)) } } } } +/** A host or one of its saved machines in the drawer; [current] is this session's. */ +data class MachineRow( + val key: String, + val label: String, + val target: String, + val session: String, + val color: Int, + val current: Boolean, +) + @Composable private fun DrawerRow( selected: Boolean, diff --git a/app/src/main/java/app/bellterm/ui/session/SessionScreen.kt b/app/src/main/java/app/bellterm/ui/session/SessionScreen.kt index 71a562c..4bd7a52 100644 --- a/app/src/main/java/app/bellterm/ui/session/SessionScreen.kt +++ b/app/src/main/java/app/bellterm/ui/session/SessionScreen.kt @@ -100,6 +100,7 @@ import app.bellterm.BelltermApp import app.bellterm.R import app.bellterm.core.AgentStatus import app.bellterm.core.Connection +import app.bellterm.core.Machine import app.bellterm.core.Native import app.bellterm.core.RenderFrame import app.bellterm.core.Tab @@ -125,7 +126,9 @@ import app.bellterm.ui.theme.NodeColors import app.bellterm.ui.theme.TerminalSchemes import app.bellterm.ui.theme.color import io.github.suqi8.coui.kmp.blur.rememberLayerBackdrop +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext /** What a confirmation or text dialog is for. */ internal sealed interface Prompt { @@ -144,7 +147,15 @@ internal sealed interface Prompt { */ @OptIn(ExperimentalMaterial3Api::class) @Composable -fun SessionScreen(app: BelltermApp, connection: Connection, focusPane: String?, dark: Boolean, onLeave: () -> Unit) { +fun SessionScreen( + app: BelltermApp, + connection: Connection, + focusPane: String?, + dark: Boolean, + onLeave: () -> Unit, + /** Opens another node's session, such as a machine from the drawer. */ + onOpen: (Node) -> Unit, +) { val context = LocalContext.current val settings by app.settings.settings.collectAsState() val fontChanges by app.fonts.changes.collectAsState() @@ -186,6 +197,38 @@ fun SessionScreen(app: BelltermApp, connection: Connection, focusPane: String?, } } + // The host whose Herdr saved this node's machine, or the node itself. + val savedNodes by app.nodes.nodes.collectAsState() + val host = if (node.machine != null) savedNodes.firstOrNull { it.id == node.jumpId } else node + var listed by remember(host?.id) { mutableStateOf?>(null) } + LaunchedEffect(drawer.isOpen, host?.id) { + if (drawer.isOpen && host != null && listed == null) { + withContext(Dispatchers.IO) { app.machines(host) }.onSuccess { listed = it } + } + } + // Listed machines, then ones saved before that this listing lacks, so a + // host that cannot list them now still offers the way back. + val machineRows = host?.let { h -> + val saved = savedNodes.filter { it.machine != null && it.jumpId == h.id } + .map { Machine(it.title, it.machine.orEmpty(), it.session) } + val machines = (listed.orEmpty() + saved).distinctBy { it.target to it.session } + if (machines.isEmpty()) { + emptyList() + } else { + listOf(MachineRow(h.id, h.title, h.destination, h.session, h.color, current = node.id == h.id)) + + machines.map { m -> + MachineRow( + key = "${m.target} ${m.session}", + label = m.label, + target = m.target, + session = m.session, + color = h.color, + current = node.machine == m.target && node.session == m.session, + ) + } + } + }.orEmpty() + LaunchedEffect(scheme, state) { connection.setTheme(scheme.toJson().toString()) } LaunchedEffect(typefaces, terminal) { typefaces?.let { terminal?.setTypefaces(it) } } LaunchedEffect(settings.fontSize, terminal) { terminal?.fontSizeSp = settings.fontSize } @@ -240,6 +283,14 @@ fun SessionScreen(app: BelltermApp, connection: Connection, focusPane: String?, onNewWorkspace = { connection.newWorkspace(workspace?.id); scope.launch { drawer.close() } }, onRenameWorkspace = { prompt = Prompt.RenameWorkspace(it.id, it.label) }, onCloseWorkspace = { prompt = Prompt.CloseWorkspace(it.id, it.label) }, + machines = machineRows, + onMachine = { row -> + scope.launch { drawer.close() } + val h = host ?: return@SessionDrawer + if (!row.current) { + onOpen(if (row.key == h.id) h else app.nodes.machine(h, row.label, row.target, row.session)) + } + }, ) }, ) { diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 63150a3..4ed71cf 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -109,6 +109,8 @@ 重新输入密码 工作区 代理 + 机器 + 保存这台主机的密码后,才能列出它的 Herdr 保存的机器。 新建工作区 新建标签页 名称 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1c67aca..0f2b185 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -110,6 +110,8 @@ Enter password Workspaces Agents + Machines + Save this host’s password to list the machines its Herdr saved. New workspace New tab Name diff --git a/app/src/test/java/app/bellterm/core/MachinesTest.kt b/app/src/test/java/app/bellterm/core/MachinesTest.kt new file mode 100644 index 0000000..82fe867 --- /dev/null +++ b/app/src/test/java/app/bellterm/core/MachinesTest.kt @@ -0,0 +1,17 @@ +package app.bellterm.core + +import org.junit.Assert.assertEquals +import org.junit.Test + +class MachinesTest { + @Test + fun parsesWhatTheCoreReturns() { + val json = """[{"id":"a1","label":"build","target":"me@build","session":"agents","enabled":true}, + {"id":"b2","label":"","target":"ssh://box:2200","session":"","enabled":true}]""" + assertEquals( + listOf(Machine("build", "me@build", "agents"), Machine("ssh://box:2200", "ssh://box:2200", "default")), + Machines.parse(json), + ) + assertEquals(emptyList(), Machines.parse("[]")) + } +} diff --git a/app/src/test/java/app/bellterm/core/RoutesTest.kt b/app/src/test/java/app/bellterm/core/RoutesTest.kt index 0957c8b..d034560 100644 --- a/app/src/test/java/app/bellterm/core/RoutesTest.kt +++ b/app/src/test/java/app/bellterm/core/RoutesTest.kt @@ -26,4 +26,21 @@ class RoutesTest { fun keyHopsAreNeverAskedFor() { assertEquals(emptyList(), Routes.unsavedPasswordHops(listOf(keyed)) { false }) } + + @Test + fun aSavedMachineIsNoHopOfOurs() { + val machine = Node(id = "machine", name = "b", address = "b", user = "u", auth = AuthMethod.Password, jumpId = "target", machine = "b") + val relayed = route + machine + assertEquals(route, Routes.sshHops(relayed)) + assertEquals(route, Routes.sshHops(route)) + assertEquals(listOf(jump, target), Routes.unsavedPasswordHops(relayed) { false }) + } + + @Test + fun aSavedMachineSurvivesStorage() { + val machine = Node(id = "machine", name = "b", address = "b", user = "u", jumpId = "target", machine = "ssh://me@b:2222", session = "agents") + assertEquals(machine, Node.fromJson(machine.toJson())) + assertEquals("ssh://me@b:2222", machine.destination) + assertEquals(null, Node.fromJson(target.toJson()).machine) + } } diff --git a/crates/herdr-client/src/external_bridge.rs b/crates/herdr-client/src/external_bridge.rs index 98de250..87acaea 100644 --- a/crates/herdr-client/src/external_bridge.rs +++ b/crates/herdr-client/src/external_bridge.rs @@ -71,6 +71,15 @@ pub fn answer_windows_bridge(stream: &mut (impl Read + Write), stop: &AtomicBool ssh::answer_powershell(stream, stop) } +/// `command` run on `target` by the `ssh` of the host the result runs on, for +/// an application that reaches Herdr through another host's saved machine: +/// that host's OpenSSH configuration, keys, and known hosts decide whether +/// `target` is reached. Wrap every remote command, the bridges included. +#[cfg(unix)] +pub fn relay_command(target: &str, command: &str) -> Result { + ssh::relay_command(target, command) +} + /// `script` as a remote command that PowerShell runs whether the Windows /// host's shell is `cmd.exe` or PowerShell. #[cfg(unix)] diff --git a/crates/herdr-client/src/external_bridge/tests.rs b/crates/herdr-client/src/external_bridge/tests.rs index 8176782..b42651c 100644 --- a/crates/herdr-client/src/external_bridge/tests.rs +++ b/crates/herdr-client/src/external_bridge/tests.rs @@ -149,3 +149,43 @@ fn the_windows_bridge_is_ready_after_its_crlf_banner() { ours.read_exact(&mut rest).unwrap(); assert_eq!(&rest, b"wire"); } + +/// The words `/bin/sh` splits `command` into. +fn words(command: &str) -> Vec { + let output = std::process::Command::new("/bin/sh") + .args([ + "-c", + &format!("for word in {command}; do printf '%s\\0' \"$word\"; done"), + ]) + .output() + .unwrap(); + String::from_utf8(output.stdout) + .unwrap() + .split_terminator('\0') + .map(str::to_owned) + .collect() +} + +#[test] +fn relay_runs_the_command_through_the_hosts_own_ssh() { + let bridge = remote_bridge_command("work").unwrap(); + let words = words(&relay_command("ssh://me@build:2222", &bridge).unwrap()); + assert_eq!(words[..2], ["ssh", "-T"]); + assert!(words.windows(2).any(|w| w == ["-o", "BatchMode=yes"])); + assert!( + words + .windows(2) + .any(|w| w == ["-o", "StrictHostKeyChecking=yes"]) + ); + // The relayed command reaches the target's shell as one word, quotes and all. + assert_eq!( + words[words.len() - 3..], + ["--", "ssh://me@build:2222", bridge.as_str()] + ); + for target in ["-oProxyCommand=x", "", "a:b@host"] { + assert!( + matches!(relay_command(target, "true"), Err(Error::InvalidSshTarget)), + "{target}" + ); + } +} diff --git a/crates/herdr-client/src/lib.rs b/crates/herdr-client/src/lib.rs index 1898db0..58ce3e9 100644 --- a/crates/herdr-client/src/lib.rs +++ b/crates/herdr-client/src/lib.rs @@ -60,7 +60,8 @@ pub use event::ClientEvent; pub use external_bridge::{answer_remote_bridge, remote_bridge_command}; #[cfg(unix)] pub use external_bridge::{ - answer_windows_bridge, powershell_command, windows_bridge_command, windows_probe_command, + answer_windows_bridge, powershell_command, relay_command, windows_bridge_command, + windows_probe_command, }; pub use forward::{ForwardEvent, PortForward, preferred_local_port}; pub use handle::{Client, ClientHandle}; diff --git a/crates/herdr-client/src/ssh.rs b/crates/herdr-client/src/ssh.rs index 9b52c0d..1cb48b5 100644 --- a/crates/herdr-client/src/ssh.rs +++ b/crates/herdr-client/src/ssh.rs @@ -460,6 +460,23 @@ pub(super) fn command(target: &str, remote_command: &str) -> Command { command } +/// `remote_command` as run on `target` by the `ssh` of the host this command +/// line runs on: a `/bin/sh` command line with the bridge's connection +/// policy, so that host's own OpenSSH configuration, keys, and known hosts +/// decide whether `target` is reached. +#[cfg(unix)] +pub(crate) fn relay_command(target: &str, remote_command: &str) -> Result { + validate_target(target)?; + let words = ["ssh"].into_iter().chain(POLICY).chain([ + "-o", + "ClearAllForwardings=yes", + "--", + target, + remote_command, + ]); + Ok(words.map(quote).collect::>().join(" ")) +} + /// `ssh` with the bridge's connection policy and nothing to connect yet. #[cfg(unix)] fn noninteractive() -> Command { diff --git a/native/src/config.rs b/native/src/config.rs index 5013613..17ff2d4 100644 --- a/native/src/config.rs +++ b/native/src/config.rs @@ -16,6 +16,9 @@ use zeroize::Zeroizing; struct Document { session: String, hops: Vec, + /// A saved machine of the last hop's Herdr, reached by that host's `ssh`. + #[serde(default)] + relay: Option, #[serde(default)] keepalive_secs: Option, cols: u16, @@ -79,6 +82,7 @@ pub fn parse(json: &str) -> Result { route: Route { hops, session: document.session, + relay: document.relay.filter(|target| !target.is_empty()), keepalive: document .keepalive_secs .filter(|secs| *secs > 0) @@ -128,11 +132,27 @@ mod tests { assert!(matches!(&hops[1].credential, Credential::Password(p) if p.as_str() == "pw")); assert_eq!(config.route.session, "work"); assert_eq!(config.route.keepalive, Some(Duration::from_secs(20))); + assert_eq!(config.route.relay, None); assert_eq!(config.options.surface_size.cols, 80); assert!(config.theme.dark); assert_eq!(config.theme.ansi[1].r, 0xff); } + #[test] + fn a_saved_machine_is_relayed_through_the_last_hop() { + let document = |relay: &str| { + format!( + r#"{{"session":"agents","relay":{relay},"cols":1,"rows":1,"theme":{THEME}, + "hops":[{{"host":"a","port":22,"user":"u","auth":{{"type":"password","password":"p"}}}}]}}"# + ) + }; + let config = parse(&document(r#""ssh://me@b:2222""#)).unwrap(); + assert_eq!(config.route.relay.as_deref(), Some("ssh://me@b:2222")); + assert_eq!(config.route.hops.len(), 1); + assert_eq!(parse(&document(r#""""#)).unwrap().route.relay, None); + assert_eq!(parse(&document("null")).unwrap().route.relay, None); + } + #[test] fn rejects_malformed_documents() { assert!(parse("{}").is_err()); diff --git a/native/src/error.rs b/native/src/error.rs index 514ed79..7919fd2 100644 --- a/native/src/error.rs +++ b/native/src/error.rs @@ -38,8 +38,12 @@ pub enum Error { NoSession, #[error("not connected to a daemon yet")] NotReady, + #[error("Herdr on this host cannot list saved machines")] + NoMachineList, #[error("system random source failed: {0}")] Random(getrandom::Error), + #[error("{target} could not be reached from its jump host: {detail}")] + Relay { target: String, detail: String }, #[error(transparent)] Ssh(#[from] russh::Error), #[error("SSH closed before the bridge started")] diff --git a/native/src/jni_api.rs b/native/src/jni_api.rs index bf0ca23..8e50d4b 100644 --- a/native/src/jni_api.rs +++ b/native/src/jni_api.rs @@ -14,7 +14,7 @@ use crate::{ Error, Result, config, herdr_setup, input::Touch, - keys, + keys, machines, session::{self, Session}, ssh_config, theme::Theme, @@ -189,6 +189,23 @@ pub extern "system" fn Java_app_bellterm_core_Native_connect<'local>( .resolve::() } +/// The enabled SSH machines Herdr on the route document's last host has +/// saved, as a JSON array. Blocks for up to half a minute: never call it on +/// the main thread. +#[unsafe(no_mangle)] +pub extern "system" fn Java_app_bellterm_core_Native_listMachines<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + config_json: JString<'local>, +) -> JString<'local> { + env.with_env(|env| -> Result<_> { + let json = Zeroizing::new(string(env, &config_json)?); + let listed = machines::list(config::parse(&json)?.route)?; + Ok(env.new_string(serde_json::to_string(&listed)?)?) + }) + .resolve::() +} + /// Install or update Herdr on the last host of the route document; returns /// `{"exit_status": …, "output": …}`. Blocks for minutes: never call it on /// the main thread. diff --git a/native/src/lib.rs b/native/src/lib.rs index 0dbafa2..08936ac 100644 --- a/native/src/lib.rs +++ b/native/src/lib.rs @@ -10,6 +10,7 @@ pub mod herdr_setup; pub mod input; mod jni_api; pub mod keys; +pub mod machines; pub mod render; mod screen; pub mod session; diff --git a/native/src/machines.rs b/native/src/machines.rs new file mode 100644 index 0000000..3799740 --- /dev/null +++ b/native/src/machines.rs @@ -0,0 +1,76 @@ +//! The SSH machines Herdr on a host has saved with `herdr machine add`. Herdr's +//! own client switches between them; the app reaches one through that host, +//! as a route with a [`Route::relay`](crate::ssh::Route::relay), so the +//! host's SSH configuration and keys sign in to it. + +use crate::{ + Error, Result, + ssh::{Collect, Remote, Route}, +}; +use herdr_client::{HERDR_CANDIDATES, shell_quote}; +use serde::{Deserialize, Serialize}; +use std::{sync::atomic::AtomicBool, time::Duration}; + +/// One saved machine, as `herdr machine list --json` prints it. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +pub struct Machine { + pub id: String, + pub label: String, + /// What the host passes to `ssh`: a config alias, `user@host`, or an + /// `ssh://` URL. + pub target: String, + pub session: String, + pub enabled: bool, +} + +const TIMEOUT: Duration = Duration::from_secs(30); +const OUTPUT_LIMIT: usize = 256 * 1024; + +/// Ask the first Herdr the bridge would find for its saved machines. +pub fn script() -> String { + format!( + r#"{HERDR_CANDIDATES} + if [ -n "$path" ] && [ -x "$path" ]; then + exec "$path" machine list --json Result> { + let never = AtomicBool::new(false); + let remote = Remote::connect(route, &never)?; + let collect = Collect { + timeout: TIMEOUT, + limit: OUTPUT_LIMIT, + stderr: false, + }; + let output = remote.run( + format!("/bin/sh -c {}", shell_quote(&script())), + collect, + &never, + )?; + parse(output.exit_status, &output.tail) +} + +/// A Herdr too old for `machine list`, none at all, or a host without +/// `/bin/sh` all exit without a list. +pub(crate) fn parse(exit_status: Option, stdout: &[u8]) -> Result> { + if exit_status != Some(0) { + return Err(Error::NoMachineList); + } + let machines: Vec = serde_json::from_slice(stdout)?; + Ok(machines + .into_iter() + .filter(|machine| { + machine.enabled && herdr_client::relay_command(&machine.target, "").is_ok() + }) + .collect()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests; diff --git a/native/src/machines/tests.rs b/native/src/machines/tests.rs new file mode 100644 index 0000000..105edb1 --- /dev/null +++ b/native/src/machines/tests.rs @@ -0,0 +1,66 @@ +use super::*; +use std::{fs, os::unix::fs::PermissionsExt, process::Command}; + +#[test] +fn parses_the_enabled_machines_herdr_lists() { + let listed = br#"[ + {"id": "a1", "label": "build", "target": "build", "session": "default", "enabled": true, "selected": true}, + {"id": "b2", "label": "old", "target": "me@old:2222", "session": "work", "enabled": false, "selected": false}, + {"id": "c3", "label": "odd", "target": "-oProxyCommand=x", "session": "default", "enabled": true, "selected": false}, + {"id": "d4", "label": "url", "target": "ssh://me@box:2200", "session": "agents", "enabled": true, "selected": false} +]"#; + let machines = parse(Some(0), listed).unwrap(); + let targets = machines + .iter() + .map(|m| m.target.as_str()) + .collect::>(); + assert_eq!(targets, ["build", "ssh://me@box:2200"]); + assert_eq!(machines[1].session, "agents"); + assert_eq!(parse(Some(0), b"[]").unwrap(), []); +} + +#[test] +fn a_host_that_cannot_list_machines_says_so() { + // No Herdr, or one from before `machine list --json`. + for status in [Some(127), Some(2), None] { + assert!( + matches!(parse(status, b""), Err(Error::NoMachineList)), + "{status:?}" + ); + } + assert!(matches!( + parse(Some(0), b"No saved SSH machines."), + Err(Error::Json(_)) + )); +} + +#[test] +fn the_script_runs_the_first_herdr_it_finds() { + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join(".local/bin"); + fs::create_dir_all(&bin).unwrap(); + let herdr = bin.join("herdr"); + fs::write(&herdr, "#!/bin/sh\necho \"listed: $*\"\n").unwrap(); + fs::set_permissions(&herdr, fs::Permissions::from_mode(0o755)).unwrap(); + let output = Command::new("/bin/sh") + .args(["-c", &script()]) + .env_clear() + .env("HOME", dir.path()) + .env("PATH", "/usr/bin:/bin") + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&output.stdout), + "listed: machine list --json\n" + ); + + fs::remove_file(&herdr).unwrap(); + let output = Command::new("/bin/sh") + .args(["-c", &script()]) + .env_clear() + .env("HOME", dir.path()) + .env("PATH", "/usr/bin:/bin") + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(127)); +} diff --git a/native/src/ssh/mod.rs b/native/src/ssh/mod.rs index 8e5de41..abaf0d7 100644 --- a/native/src/ssh/mod.rs +++ b/native/src/ssh/mod.rs @@ -8,14 +8,16 @@ //! one thread and owns only the SSH sessions. [`Remote::run`] runs a command //! over the same sessions and collects what it prints. A Windows OpenSSH host //! cannot run the POSIX bridge, so [`open`] then probes it through PowerShell -//! and bridges the `herdr.exe` it finds over another channel. +//! and bridges the `herdr.exe` it finds over another channel. A route with a +//! [`Route::relay`] runs every command one step further, through the last +//! hop's own `ssh` to a machine its Herdr saved. mod auth; use crate::{Error, Result}; pub use auth::Credential; use herdr_client::{ - Stream, answer_remote_bridge, answer_windows_bridge, remote_bridge_command, + Stream, answer_remote_bridge, answer_windows_bridge, relay_command, remote_bridge_command, windows_bridge_command, windows_probe_command, }; use russh::{ @@ -63,6 +65,10 @@ pub struct Route { pub session: String, /// SSH keepalive; `None` disables it. pub keepalive: Option, + /// An SSH target the last hop reaches with its own `ssh`, as a machine + /// saved by `herdr machine add` there. Its keys and known hosts decide + /// that step; Herdr runs on the target. + pub relay: Option, } /// Open the bridge to the route's Herdr and answer its discovery. Blocks, so @@ -71,6 +77,7 @@ pub fn open(route: Route, stop: &AtomicBool) -> Result { let session = route.session.clone(); let posix = remote_bridge_command(&session)?; let remote = Remote::connect(route, stop)?; + remote.reach_relay(stop)?; match remote.bridge(posix, stop, answer_remote_bridge) { Err(Error::Client(herdr_client::Error::SshClosed)) => {} result => return result, @@ -123,6 +130,7 @@ pub struct Collect { /// disconnect once every bridge it pumps has closed. pub struct Remote { requests: tokio::sync::mpsc::UnboundedSender, + relay: Option, } enum Request { @@ -145,6 +153,10 @@ impl Remote { if route.hops.is_empty() { return Err(Error::EmptyRoute); } + let relay = route.relay.clone(); + if let Some(target) = &relay { + relay_command(target, "")?; + } let (requests, received) = tokio::sync::mpsc::unbounded_channel(); let (ready, outcome) = mpsc::sync_channel(1); thread::Builder::new() @@ -163,7 +175,46 @@ impl Remote { runtime.block_on(serve(route, received, ready)); })?; wait(&outcome, stop, SETUP_TIMEOUT)?; - Ok(Self { requests }) + Ok(Self { requests, relay }) + } + + /// Whether the last hop reaches the relay target, so a failure there is + /// reported as what its `ssh` said rather than as a host without Herdr. + fn reach_relay(&self, stop: &AtomicBool) -> Result<()> { + let Some(target) = &self.relay else { + return Ok(()); + }; + let collect = Collect { + timeout: PROBE_TIMEOUT, + limit: 4096, + stderr: true, + }; + // `exit 0` means the same to POSIX shells, cmd.exe, and PowerShell. + let reached = self.run("exit 0".to_owned(), collect, stop)?; + if reached.exit_status == Some(0) { + return Ok(()); + } + let said = crate::herdr_setup::plain_text(&reached.tail); + Err(Error::Relay { + target: target.clone(), + detail: said + .lines() + .rev() + .find(|line| !line.trim().is_empty()) + .map_or_else( + || format!("exit status {:?}", reached.exit_status), + |line| line.trim().to_owned(), + ), + }) + } + + /// `command` as the last hop runs it: through its `ssh` to the relay + /// target when there is one. + fn wrap(&self, command: String) -> Result { + match &self.relay { + Some(target) => Ok(relay_command(target, &command)?), + None => Ok(command), + } } /// Run `command` as a bridge pumped through a socket, then let `answer` @@ -174,6 +225,7 @@ impl Remote { stop: &AtomicBool, answer: impl FnOnce(&mut UnixStream, &AtomicBool) -> herdr_client::Result<()>, ) -> Result { + let command = self.wrap(command)?; let (mut ours, theirs) = UnixStream::pair()?; let (opened, outcome) = mpsc::sync_channel(1); self.send(Request::Bridge { @@ -191,6 +243,7 @@ impl Remote { /// Run `command` and collect its output. Blocks for at most the collect /// timeout once its channel is open. pub fn run(&self, command: String, collect: Collect, stop: &AtomicBool) -> Result { + let command = self.wrap(command)?; let (done, outcome) = mpsc::sync_channel(1); self.send(Request::Run { command, diff --git a/native/tests/live_ssh.rs b/native/tests/live_ssh.rs index e57c8e0..e879e9e 100644 --- a/native/tests/live_ssh.rs +++ b/native/tests/live_ssh.rs @@ -6,10 +6,14 @@ //! README.md. Never point it at a daemon you care about: it types into the //! focused pane. `installs_herdr_then_attaches` instead needs a host without //! Herdr, POSIX or Windows OpenSSH, and installs it there. +//! `attaches_to_a_saved_machine_through_its_host` needs the host's Herdr to +//! have saved the machine `BELLTERM_LIVE_MACHINE` with `herdr machine add`, +//! and that machine's session to have a workspace labelled +//! `BELLTERM_LIVE_MACHINE_WORKSPACE`. #![allow(clippy::unwrap_used, clippy::expect_used)] use bellterm::{ - herdr_setup, + herdr_setup, machines, session::{self, Config, Session, UiEvent}, ssh::{Credential, Hop, Route}, theme::Theme, @@ -61,6 +65,7 @@ fn config(pinned: Option, jump_pinned: Option) -> Config { Config { route: Route { hops, + relay: None, session: env::var("BELLTERM_LIVE_SESSION").unwrap_or_else(|_| "default".into()), keepalive: Some(Duration::from_secs(15)), }, @@ -163,8 +168,9 @@ fn attaches_over_ssh_and_round_trips_input() { } /// Type a command into the focused pane and wait for its output. The newline -/// is sent as an Enter key press, which every pane's shell takes. -fn echo_round_trip(session: &Session, round: &str) { +/// is sent as an Enter key press, which every pane's shell takes. Returns the +/// shell view the attach began with. +fn echo_round_trip(session: &Session, round: &str) -> serde_json::Value { wait(session, "snapshot", |e| matches!(e, UiEvent::Snapshot)); let view: serde_json::Value = serde_json::from_str(&session.take_view().unwrap()).unwrap(); assert!(!view["workspaces"].as_array().unwrap().is_empty()); @@ -190,6 +196,7 @@ fn echo_round_trip(session: &Session, round: &str) { assert!(Instant::now() < deadline, "marker never appeared:\n{text}"); let _ = session.next_event(Duration::from_millis(200)); } + view } /// The flow a user without Herdr goes through: the connection offers the @@ -227,3 +234,60 @@ fn installs_herdr_then_attaches() { echo_round_trip(&session, round); } } + +/// Herdr's own client switches to a machine its host saved; Bellterm lists +/// those machines and attaches to one through the host's `ssh`. A target the +/// host cannot reach reports what its `ssh` said. +#[test] +#[ignore = "needs a host whose Herdr saved a machine; see README.md"] +fn attaches_to_a_saved_machine_through_its_host() { + let first = Session::connect(config(None, None)).unwrap(); + let pin = match wait(&first, "host key prompt", |e| { + matches!(e, UiEvent::UntrustedHostKey { .. }) + }) { + UiEvent::UntrustedHostKey { fingerprint, .. } => fingerprint, + _ => unreachable!(), + }; + + let label = var("BELLTERM_LIVE_MACHINE"); + let listed = machines::list(config(Some(pin.clone()), None).route).unwrap(); + eprintln!("machines: {listed:?}"); + let machine = listed + .iter() + .find(|m| m.label == label) + .unwrap_or_else(|| panic!("{label} is not among {listed:?}")); + + let relayed = |target: &str| { + let mut config = config(Some(pin.clone()), None); + config.route.relay = Some(target.to_owned()); + config.route.session = machine.session.clone(); + Session::connect(config).unwrap() + }; + let session = relayed(&machine.target); + wait_for(&session, "connected", Duration::from_secs(90), |e| { + matches!(e, UiEvent::Connected { .. }) + }); + let view = echo_round_trip(&session, "machine"); + let labels = view["workspaces"] + .as_array() + .unwrap() + .iter() + .filter_map(|w| w["label"].as_str()) + .collect::>(); + let expected = var("BELLTERM_LIVE_MACHINE_WORKSPACE"); + assert!( + labels.contains(&expected.as_str()), + "{labels:?} lacks {expected}" + ); + + let unreachable = relayed("ssh://nobody@127.0.0.1:1"); + let event = wait_for(&unreachable, "refusal", Duration::from_secs(60), |e| { + matches!(e, UiEvent::Disconnected { .. }) + }); + eprintln!("unreachable: {}", event.to_json()); + assert!( + event.to_json().contains("could not be reached"), + "{}", + event.to_json() + ); +} From 00a36cd05a6ab2997f62ece79280e506be7c9215 Mon Sep 17 00:00:00 2001 From: Terry Wang Date: Mon, 16 Nov 2026 23:07:44 +0800 Subject: [PATCH 2/3] test: switch to a saved machine in the app on an emulator GlassUiTest.t8 opens the drawer of a host whose Herdr saved a machine, switches to it, checks the machine's own workspace, and switches back. CI runs it on an emulator against the saved-machine job's sshd, after t0 publishes the device key for that host to trust, and keeps the screenshots. --- .github/workflows/ci.yml | 60 +++++++++- .../java/app/bellterm/e2e/GlassUiTest.kt | 106 +++++++++++++----- 2 files changed, 137 insertions(+), 29 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 91253f7..98ce592 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,7 +73,7 @@ jobs: - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - name: Unit tests and APKs - run: ./gradlew --console=plain testDebugUnitTest assembleDebug assembleRelease + run: ./gradlew --console=plain testDebugUnitTest assembleDebug assembleDebugAndroidTest assembleRelease # The release workflow builds this for Google Play; it must not check # dl.bellterm.app for updates. @@ -85,7 +85,9 @@ jobs: - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: bellterm-apks - path: app/build/outputs/apk/*/*.apk + path: | + app/build/outputs/apk/*/*.apk + app/build/outputs/apk/androidTest/debug/*.apk if-no-files-found: error retention-days: 14 @@ -96,7 +98,7 @@ jobs: name: Saved machine through its host needs: android runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 45 permissions: contents: read steps: @@ -105,6 +107,11 @@ jobs: name: live-ssh path: live + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: bellterm-apks + path: apks + - name: sshd, Herdr, and a saved machine run: | [ -x /usr/sbin/sshd ] || sudo apt-get install -y openssh-server > /dev/null @@ -124,6 +131,10 @@ jobs: herdr machine add "ssh://$(id -un)@127.0.0.1:2222" --remote-session machine --label b-machine < /dev/null herdr --session machine workspace create --label on-b --no-focus herdr machine list --json + # The host's own session, which the app attaches to first. + nohup herdr server > ~/herdr-host.log 2>&1 & + for _ in $(seq 30); do herdr status server --json | grep -q '"running":true' && break; sleep 1; done + echo "FINGERPRINT=$(ssh-keygen -lf ~/sshd/host.pub | awk '{print $2}')" >> "$GITHUB_ENV" - name: List the machine and attach through its host run: | @@ -133,10 +144,53 @@ jobs: chmod +x live/live_ssh RUST_BACKTRACE=1 live/live_ssh --ignored --nocapture --exact attaches_to_a_saved_machine_through_its_host + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + # The app itself on an emulator, which reaches the runner's sshd as + # 10.0.2.2: the drawer lists the machine, and switching to it attaches. + - name: Emulator script + run: | + cat > "$RUNNER_TEMP/emulator.sh" <<'SCRIPT' + set -u + trap 'adb pull /sdcard/Android/data/app.bellterm/files/e2e "$RUNNER_TEMP/screens" > /dev/null' EXIT + adb install -r -g apks/debug/app-debug.apk + adb install -r -g apks/androidTest/debug/app-debug-androidTest.apk + instrument() { + adb shell am instrument -w -r "$@" app.bellterm.test/androidx.test.runner.AndroidJUnitRunner \ + | tee /dev/stderr | grep -q '^OK (' + } + test=app.bellterm.e2e.GlassUiTest + instrument -e publish_key 1 -e class "$test#t0_publishesDeviceKey" || exit 1 + adb shell cat /sdcard/Android/data/app.bellterm/files/e2e/device.pub >> ~/.ssh/authorized_keys + instrument -e host 10.0.2.2 -e port 2222 -e user "$(id -un)" -e fingerprint "$FINGERPRINT" \ + -e machine b-machine -e machine_workspace on-b -e class "$test#t8_switchesToSavedMachine" + SCRIPT + + - uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0 + with: + api-level: 35 + arch: x86_64 + target: google_apis + disable-animations: true + script: bash "$RUNNER_TEMP/emulator.sh" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: saved-machine-screens + path: ${{ runner.temp }}/screens + if-no-files-found: warn + retention-days: 14 + - name: sshd and Herdr state if: failure() run: | cat ~/sshd/log || true + cat ~/herdr-host.log || true PATH="$HOME/.local/bin:$PATH" herdr machine status --json || true # Issue #25: a Windows OpenSSH host runs cmd.exe or PowerShell, never diff --git a/app/src/androidTest/java/app/bellterm/e2e/GlassUiTest.kt b/app/src/androidTest/java/app/bellterm/e2e/GlassUiTest.kt index bcdf289..2219e8b 100644 --- a/app/src/androidTest/java/app/bellterm/e2e/GlassUiTest.kt +++ b/app/src/androidTest/java/app/bellterm/e2e/GlassUiTest.kt @@ -36,6 +36,11 @@ import org.junit.runners.MethodSorters * adb shell am instrument -w -e host 192.168.0.100 -e port 2200 -e user me \ * app.bellterm.test/androidx.test.runner.AndroidJUnitRunner * + * Add `-e machine