From 9067ef8dc62d0a44b6dbc5eca25758f9ceaee9d3 Mon Sep 17 00:00:00 2001 From: andreas-byfut <356109509+andreas-byfut@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:46:36 +0100 Subject: [PATCH] fix(keys): keep key enrolment on its own line and across rotation Pushing a key appended it without checking that authorized_keys ended in a newline, so a file without one had the new key glued onto its last entry. The command now adds a newline only when the file ends mid-line, and is built by a testable function. It uses only syntax that both POSIX sh and csh/tcsh accept, since sshd runs it through the account's login shell. The enrolment section's result message, failure flag and switched flag are now rememberSaveable so a rotation no longer drops them. The generated key stays in plain remember because it holds the private key; when a rotation leaves a restored success without it, the section says the key was not kept and must be pushed again. --- .../feature/host/KeyEnrolmentSection.kt | 17 ++-- .../lordofpolls/shellwave/ssh/KeyEnrolment.kt | 25 ++++-- .../shellwave/ssh/KeyEnrolmentCommandTest.kt | 79 +++++++++++++++++++ 3 files changed, 111 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolmentCommandTest.kt diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/feature/host/KeyEnrolmentSection.kt b/app/src/main/java/io/github/lordofpolls/shellwave/feature/host/KeyEnrolmentSection.kt index 6411254..50628e3 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/feature/host/KeyEnrolmentSection.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/feature/host/KeyEnrolmentSection.kt @@ -11,6 +11,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.unit.dp import androidx.fragment.app.FragmentActivity @@ -43,10 +44,11 @@ fun KeyEnrolmentSection( ) { val scope = rememberCoroutineScope() var busy by remember { mutableStateOf(false) } + // Plain `remember`: this holds the private key, which must not land in saved instance state. var pushedKey by remember { mutableStateOf(null) } - var result by remember { mutableStateOf(null) } - var failed by remember { mutableStateOf(false) } - var switched by remember { mutableStateOf(false) } + var result by rememberSaveable { mutableStateOf(null) } + var failed by rememberSaveable { mutableStateOf(false) } + var switched by rememberSaveable { mutableStateOf(false) } Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( @@ -120,11 +122,16 @@ fun KeyEnrolmentSection( ) { Text("Use this key for this host") } } } - result?.let { + // The private key is not saved across rotation, so a restored success has nothing left to switch to. + val keyLost = result != null && !failed && !switched && pushedKey == null + val shown = + if (keyLost) "The key was installed on the host, but this screen no longer has it. Push a new key to use it." + else result + shown?.let { Text( it, style = MaterialTheme.typography.bodySmall, - color = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + color = if (failed || keyLost) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, ) } } diff --git a/app/src/main/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolment.kt b/app/src/main/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolment.kt index d61a994..6ccb6fb 100644 --- a/app/src/main/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolment.kt +++ b/app/src/main/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolment.kt @@ -9,6 +9,25 @@ internal const val ENROLMENT_FAIL_MARKER = "SHELLWAVE_ENROLL_FAIL" data class KeyEnrolmentResult(val success: Boolean, val message: String) +/** + * `authorized_keys` may not end in a newline, and appending to such a file would glue the new key + * onto the last entry and corrupt both. `tail -c1 | grep -q .` only succeeds when the last byte is + * not a newline (an empty file has no byte at all), so a newline is only added when the file ends + * mid-line. + * + * sshd runs the command through the account's login shell, which can be csh or tcsh, so it sticks + * to syntax both csh and POSIX sh accept: `&&`, `||`, `|`, `;` and `( )` subshells, but no command + * substitution, braces or `[ ]` tests. + */ +internal fun enrolmentCommand(key: String): String { + val quotedKey = posixQuote(key) + val file = "~/.ssh/authorized_keys" + return "mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch $file && chmod 600 $file && " + + "(grep -qxF -- $quotedKey $file || " + + "(tail -c1 $file | grep -q . && echo >> $file; printf '%s\\n' $quotedKey >> $file)) && " + + "grep -qxF -- $quotedKey $file && echo $ENROLMENT_OK_MARKER || echo $ENROLMENT_FAIL_MARKER" +} + /** * `ssh-copy-id` over an already-authenticated session: one POSIX shell command through * [ScriptRunner.runCapture] rather than a second exec path. Nothing sshj-specific lives here. @@ -42,11 +61,7 @@ constructor(private val scriptRunner: ScriptRunner) { ): KeyEnrolmentResult { val key = publicKeyLine.trim() require(key.isNotEmpty() && !key.contains('\n')) { "publicKeyLine must be a single non-blank line" } - val quotedKey = posixQuote(key) - val command = - "mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && " + - "(grep -qxF -- $quotedKey ~/.ssh/authorized_keys || printf '%s\\n' $quotedKey >> ~/.ssh/authorized_keys) && " + - "grep -qxF -- $quotedKey ~/.ssh/authorized_keys && echo $ENROLMENT_OK_MARKER || echo $ENROLMENT_FAIL_MARKER" + val command = enrolmentCommand(key) val result = scriptRunner.runCapture(runLabel, hostname, port, username, authMethod, command, hops) diff --git a/app/src/test/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolmentCommandTest.kt b/app/src/test/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolmentCommandTest.kt new file mode 100644 index 0000000..535c530 --- /dev/null +++ b/app/src/test/java/io/github/lordofpolls/shellwave/ssh/KeyEnrolmentCommandTest.kt @@ -0,0 +1,79 @@ +package io.github.lordofpolls.shellwave.ssh + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +/** + * Runs the real command through `sh` against a throwaway `$HOME`, since the append logic only + * exists as shell. Skipped where no `sh` is available. + */ +class KeyEnrolmentCommandTest { + + @get:Rule + val home = TemporaryFolder() + + private val key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAItest shellwave" + + private fun authorizedKeys() = File(home.root, ".ssh/authorized_keys") + + private fun run(): String { + assumeTrue(File("/bin/sh").canExecute()) + val process = ProcessBuilder("/bin/sh", "-c", enrolmentCommand(key)) + .redirectErrorStream(true) + .apply { environment()["HOME"] = home.root.absolutePath } + .start() + val output = process.inputStream.bufferedReader().readText() + process.waitFor() + return output + } + + private fun seed(content: String) { + authorizedKeys().parentFile.mkdirs() + authorizedKeys().writeText(content) + } + + @Test + fun missingFile_getsTheKeyAndATrailingNewline() { + assertTrue(ENROLMENT_OK_MARKER in run()) + assertEquals("$key\n", authorizedKeys().readText()) + } + + @Test + fun emptyFile_getsNoBlankLine() { + seed("") + run() + assertEquals("$key\n", authorizedKeys().readText()) + } + + @Test + fun fileWithTrailingNewline_getsNoBlankLine() { + seed("ssh-rsa AAAAold other\n") + run() + assertEquals("ssh-rsa AAAAold other\n$key\n", authorizedKeys().readText()) + } + + @Test + fun fileWithoutTrailingNewline_keepsTheLastEntryIntact() { + seed("ssh-rsa AAAAold other") + assertTrue(ENROLMENT_OK_MARKER in run()) + assertEquals("ssh-rsa AAAAold other\n$key\n", authorizedKeys().readText()) + } + + @Test + fun alreadyPresentKey_isNotAppendedAgain() { + seed("$key\n") + run() + assertEquals("$key\n", authorizedKeys().readText()) + } + + @Test + fun command_usesOnlySyntaxThatCshAlsoAccepts() { + val command = enrolmentCommand(key) + listOf("$(", "`", "{", "}", "[").forEach { assertTrue("contains $it", it !in command) } + } +}