Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 109 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -85,10 +85,117 @@ 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

# 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: 45
permissions:
contents: read
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
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
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
# 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: |
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: 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
# am instrument exits 0 on failures, and a skipped test (code -4) still
# reads OK, so both are checked in its output.
instrument() {
adb shell am instrument -w -r "$@" app.bellterm.test/androidx.test.runner.AndroidJUnitRunner > "$RUNNER_TEMP/instrument.log"
cat "$RUNNER_TEMP/instrument.log"
grep -q '^OK (' "$RUNNER_TEMP/instrument.log" && ! grep -q 'INSTRUMENTATION_STATUS_CODE: -4' "$RUNNER_TEMP/instrument.log"
}
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
# /bin/sh. A fresh admin user without Herdr goes through the app's flow:
# install prompt, install over SSH, attach, update, attach.
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down
106 changes: 80 additions & 26 deletions app/src/androidTest/java/app/bellterm/e2e/GlassUiTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <label>` when Herdr on that host saved a machine with
* `herdr machine add`, and `-e machine_workspace <label>` for a workspace
* only that machine's session has. `-e publish_key 1` writes the device's
* public key to e2e/device.pub for a host to trust.
*
* Screenshots land in the app's external files, under e2e/.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
Expand Down Expand Up @@ -66,6 +71,12 @@ class GlassUiTest {
}
}

@Test
fun t0_publishesDeviceKey() {
assumeTrue("not asked to publish the key", InstrumentationRegistry.getArguments().getString("publish_key") == "1")
File(shots, "device.pub").writeText(app.keychain.device(string(R.string.device_key_name)).publicKey + "\n")
}

@Test
fun t1_homeShowsGlassChrome() {
need(By.res("action:more"))
Expand Down Expand Up @@ -167,32 +178,7 @@ class GlassUiTest {
val args = InstrumentationRegistry.getArguments()
val host = args.getString("host")
assumeTrue("no host given; skipping the live connection", host != null)
val port = args.getString("port") ?: "22"
val user = args.getString("user") ?: "root"

need(By.res("add_node")).click()
type("field:name", HOST_NODE)
type("field:address", host!!)
type("field:user", user)
type("field:port", port)
assertTrue(waitEnabled(By.res("save")))
need(By.res("save")).click()
need(By.res("node:$HOST_NODE")).click()

val settled = device.wait(
Until.hasObject(By.res(Pattern.compile("session:state:Connected|session:state_card"))),
CONNECT_TIMEOUT,
)
assertTrue("connection settles", settled)
if (device.hasObject(By.res("session:state_card"))) {
shot("11_state_card")
// Only an unknown host key may be trusted here, and only the one the caller vouched for.
val expected = args.getString("fingerprint")
assumeTrue("host key prompt without an expected fingerprint", expected != null)
assertTrue(device.hasObject(By.textContains(expected!!)))
need(By.res("session:primary_action")).click()
need(By.res("session:state:Connected"), timeout = CONNECT_TIMEOUT)
}
connectHost(host!!)
need(By.res("session:title"))
need(By.res("session:tabs"))
need(By.res("extra_keys"))
Expand Down Expand Up @@ -259,6 +245,74 @@ class GlassUiTest {
assertTrue("deleting the node disconnects it", waitFor { app.connections.value.isEmpty() })
}

@Test
fun t8_switchesToSavedMachine() {
val args = InstrumentationRegistry.getArguments()
val host = args.getString("host")
val machine = args.getString("machine")
assumeTrue("no host with a saved machine given; skipping", host != null && machine != null)
connectHost(host!!)

// The drawer lists the host, then the machines its Herdr saved.
need(By.res("session:drawer")).click()
need(By.res("session:drawer_sheet"))
need(By.res("machine:$machine"), "the saved machine in the drawer", CONNECT_TIMEOUT)
need(By.res("machine:$HOST_NODE"))
shot("19_drawer_machines")

// Its session is the machine's server, reached through the host.
need(By.res("machine:$machine")).click()
assertTrue(device.wait(Until.gone(By.res("session:drawer_sheet")), TIMEOUT))
need(By.res("session:state:Connected"), timeout = CONNECT_TIMEOUT)
need(By.res("session:drawer")).click()
need(By.res("session:drawer_sheet"))
need(By.text(machine!!))
args.getString("machine_workspace")?.let { need(By.res("workspace:$it"), "the machine's own workspace", CONNECT_TIMEOUT) }
shot("20_machine_drawer")

// And back to the host from the machine's drawer.
need(By.res("machine:$HOST_NODE")).click()
assertTrue(device.wait(Until.gone(By.res("session:drawer_sheet")), TIMEOUT))
need(By.res("session:state:Connected"), timeout = CONNECT_TIMEOUT)
device.pressBack()
need(By.res("node:$machine"))
need(By.text(string(R.string.via_jump, HOST_NODE)))
shot("21_home_machine_node")
deleteNode(HOST_NODE)
assertTrue("the host's machines go with it", device.wait(Until.gone(By.res("node:$machine")), TIMEOUT))
}

/** Adds [host] from the instrumentation arguments as a node, opens it, and trusts its key when vouched for. */
private fun connectHost(host: String) {
val args = InstrumentationRegistry.getArguments()
val port = args.getString("port") ?: "22"
val user = args.getString("user") ?: "root"

need(By.res("add_node")).click()
type("field:name", HOST_NODE)
type("field:address", host)
type("field:user", user)
type("field:port", port)
assertTrue(waitEnabled(By.res("save")))
need(By.res("save")).click()
need(By.res("node:$HOST_NODE")).click()

val settled = device.wait(
Until.hasObject(By.res(Pattern.compile("session:state:Connected|session:state_card"))),
CONNECT_TIMEOUT,
)
assertTrue("connection settles", settled)
if (device.hasObject(By.res("session:state_card"))) {
shot("11_state_card")
// Only an unknown host key may be trusted here, and only the one the caller vouched for.
val expected = args.getString("fingerprint")
assumeTrue("host key prompt without an expected fingerprint", expected != null)
assertTrue(device.hasObject(By.textContains(expected!!)))
need(By.res("session:primary_action")).click()
need(By.res("session:state:Connected"), timeout = CONNECT_TIMEOUT)
}
}

private fun deleteNode(name: String) {
need(By.res("node_more:$name")).click()
need(By.text(string(R.string.delete))).click()
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/app/bellterm/BelltermApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<List<Machine>> {
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<Node> =
nodes.route(node).getOrNull()?.let { route -> Routes.unsavedPasswordHops(route) { keychain.hasPassword(it.id) } }.orEmpty()
Expand Down
18 changes: 18 additions & 0 deletions app/src/main/java/app/bellterm/core/Machines.kt
Original file line number Diff line number Diff line change
@@ -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<Machine> {
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" })
}
}
}
7 changes: 7 additions & 0 deletions app/src/main/java/app/bellterm/core/Native.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 8 additions & 3 deletions app/src/main/java/app/bellterm/core/Routes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Node>): List<Node> = if (route.lastOrNull()?.machine != null) route.dropLast(1) else route

/** Nodes in [route] that sign in with a password. */
fun passwordHops(route: List<Node>): List<Node> = route.filter { it.auth == AuthMethod.Password }
fun passwordHops(route: List<Node>): List<Node> = sshHops(route).filter { it.auth == AuthMethod.Password }

/** Password nodes in [route] with no saved password, which must be asked for. */
fun unsavedPasswordHops(route: List<Node>, saved: (Node) -> Boolean): List<Node> =
Expand All @@ -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()
Expand All @@ -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])
Expand Down
Loading
Loading