Archived
Fix recovering twice, and stop the keyboard editing the passphrase
Recovery minted the replacement code twice — one sent to the account service, a different one wrapped into the identity record and shown on screen. The first recovery looked perfect and left the account openable only with a code nobody had ever seen. It takes a second recovery to notice, which is to say it would have been noticed by somebody who had already lost a passphrase twice. One code now reaches both writes. The passphrase and recovery-code fields never told the keyboard what they were, so autocorrect was live on both. A passphrase is chosen to be long and memorable rather than dictionary-shaped, which is exactly the sort of text autocorrect likes to improve, and an improved passphrase cannot be recovered — only replaced with the code. The recovery code is twenty-eight characters of base32 typed once, from paper, under stress. Both now declare themselves, and the handle no longer gets a capital letter it never asked for. The recovery code is also laid out four groups to a line: left to wrap, the last group split across lines as "…-YR" and "RK", on the one screen somebody copies by hand with no way to check it afterwards. Rows this device can read now come before the ones it cannot. An area is shared by everyone cleared for it, so the listing carries other people's files as rows without names — showing them is deliberate, but arriving at a screenful of "Encrypted for another key" with your own folder below the fold is a poor way to meet the thing. The instrumented suites are new: registration, sign-in, recovering twice, folders, upload, share links with the secret asserted to be in the fragment, switching areas within a clearance, and a visual tour that photographs each screen. Shared helpers live in one file, because the same row-finder was copied into three and then fixed in one of them — and the first version scrolled inside a `waitUntil`, which ran on the main thread often enough for Android to declare the app unresponsive and kill the run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
f66d681c58
commit
25f343d901
@@ -65,4 +65,18 @@ dependencies {
|
||||
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||
androidTestImplementation("androidx.test:runner:1.6.2")
|
||||
androidTestImplementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
|
||||
|
||||
// Driving the actual screens. The engine's suites prove the cryptography;
|
||||
// these prove a button is connected to the thing it claims to do, which is
|
||||
// where the remaining risk lives.
|
||||
androidTestImplementation(platform("androidx.compose:compose-bom:2024.12.01"))
|
||||
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
|
||||
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||||
// Stubbing the system file picker, so upload can be tested without a human
|
||||
// tapping through a chooser this app does not own.
|
||||
androidTestImplementation("androidx.test.espresso:espresso-intents:3.6.1")
|
||||
// Only for the visual tour: Compose's own test API cannot photograph the
|
||||
// screen, and a screenshot is the one thing that shows what a person
|
||||
// actually sees rather than what the semantics tree claims.
|
||||
androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Instrumentation
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.hasTestTag
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithTag
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollToNode
|
||||
import androidx.compose.ui.test.performTextClearance
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.test.espresso.intent.Intents
|
||||
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The app, driven through its own screens.
|
||||
*
|
||||
* ⚠️ **This is the part that was untested.** The engine has vectors, the wire
|
||||
* layer has a command-line client that runs full round trips — and neither says
|
||||
* anything about whether a button is wired to the thing it claims to do. Every
|
||||
* bug found in this feature so far was found by running it, not by reading it.
|
||||
*
|
||||
* Needs a stack on the host, and this first:
|
||||
*
|
||||
* adb reverse tcp:8081 tcp:8081 && adb reverse tcp:8100 tcp:8100
|
||||
*
|
||||
* ⚠️ Loopback rather than the emulator's `10.0.2.2` alias, and not by taste.
|
||||
* The server tells clients where its account service lives, and that answer is
|
||||
* one string for every client — so an emulator that reaches the server on
|
||||
* `10.0.2.2` is still handed `127.0.0.1:8100` for accounts and fails with
|
||||
* "Failed to connect to /127.0.0.1:8100" against a stack that is plainly
|
||||
* running. Forwarding the ports makes loopback mean the same thing here as it
|
||||
* does in a browser and on the iOS simulator, so one server configuration
|
||||
* serves all three.
|
||||
*
|
||||
* Deliberately not production: these register accounts, and a test suite should
|
||||
* not be creating real ones.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class AppFlowTest {
|
||||
@get:Rule
|
||||
val rule = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private val server = "http://127.0.0.1:8081"
|
||||
private val passphrase = "correct horse battery staple"
|
||||
|
||||
/** A fresh handle per test. Registration is once per name, and a test that
|
||||
* only passes against a clean database is a test that gets ignored. */
|
||||
private fun handle(prefix: String) =
|
||||
"$prefix${System.currentTimeMillis().toString(36)}"
|
||||
|
||||
@Before
|
||||
fun pointAtTheLocalStack() {
|
||||
// The app remembers the server and the handle, deliberately. That makes
|
||||
// them shared state between tests, so each run starts from a known one.
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
context.getSharedPreferences("flamenet-files", 0).edit()
|
||||
.putString("server", server).putString("handle", "").commit()
|
||||
}
|
||||
|
||||
// MARK: helpers
|
||||
|
||||
private fun register(name: String) {
|
||||
rule.waitUntil(10_000) {
|
||||
rule.onAllNodesWithTag("handle").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithTag("mode-register").performClick()
|
||||
// Cleared, not just typed into. The handle is remembered between
|
||||
// launches on purpose, and the rule starts the activity *before*
|
||||
// @Before runs — so resetting the preference is too late and the field
|
||||
// arrives carrying the previous test's name with this one appended.
|
||||
rule.onNodeWithTag("handle").performTextClearance()
|
||||
rule.onNodeWithTag("handle").performTextInput(name)
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrase)
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
|
||||
// The stretch is deliberately slow, and slower again on an emulator.
|
||||
rule.waitUntil(120_000) {
|
||||
rule.onAllNodesWithText("Write this down now").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithTag("ack-recovery").performClick()
|
||||
rule.awaitFileList()
|
||||
}
|
||||
|
||||
|
||||
|
||||
// MARK: the flows
|
||||
|
||||
/**
|
||||
* Registration through to a usable file list, and the banner that says
|
||||
* where a new file will be filed. The banner is not decoration: which area
|
||||
* you are in decides who can ever read what you put there.
|
||||
*/
|
||||
@Test
|
||||
fun registeringReachesTheFileList() {
|
||||
register(handle("uia"))
|
||||
rule.onNode(hasText("Working at", substring = true)).assertIsDisplayed()
|
||||
rule.onNodeWithText("All files").assertIsDisplayed()
|
||||
}
|
||||
|
||||
/**
|
||||
* A folder round trip. The name only comes back if it encrypted, uploaded,
|
||||
* listed and decrypted — the whole hierarchy, exercised by one tap.
|
||||
*/
|
||||
@Test
|
||||
fun aFolderSurvivesARoundTrip() {
|
||||
register(handle("uib"))
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("New folder").performClick()
|
||||
rule.onNodeWithTag("folder-name").performTextInput("Reports")
|
||||
rule.onNodeWithText("Create").performClick()
|
||||
|
||||
rule.awaitRow("row:Reports")
|
||||
rule.onNodeWithTag("row:Reports").assertIsDisplayed()
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload, with the system chooser stubbed.
|
||||
*
|
||||
* The chooser belongs to Android and testing it would be testing Android.
|
||||
* What is worth testing is everything after it: reading the returned URI
|
||||
* through the content resolver, the size check, encrypting, uploading, and
|
||||
* the list coming back with a name this device can read. That path had
|
||||
* never been run before this test existed.
|
||||
*/
|
||||
@Test
|
||||
fun aFileCanBeUploadedAndComesBackReadable() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
val file = File(context.cacheDir, "upload-me.txt")
|
||||
file.writeText("the quick brown fox, encrypted before it leaves")
|
||||
|
||||
val uri = androidx.core.content.FileProvider.getUriForFile(
|
||||
context, "${context.packageName}.files", file)
|
||||
// Initialised here rather than for every test. A test that fails before
|
||||
// its @After leaves Intents initialised, and the next init() throws —
|
||||
// which turns one failure into a cascade that hides what actually broke.
|
||||
Intents.init()
|
||||
try {
|
||||
val result = Intent().setData(uri)
|
||||
Intents.intending(hasAction(Intent.ACTION_OPEN_DOCUMENT))
|
||||
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, result))
|
||||
|
||||
register(handle("uic"))
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("Upload a file").performClick()
|
||||
|
||||
rule.awaitRow("row:upload-me.txt")
|
||||
rule.onNodeWithTag("row:upload-me.txt").assertIsDisplayed()
|
||||
} finally {
|
||||
Intents.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign out, sign back in, and the file is still readable.
|
||||
*
|
||||
* This is the one that proves the identity record actually round-trips: the
|
||||
* second session unlocks a keypair from the server and unwraps a label key
|
||||
* with it, rather than reusing anything held in memory.
|
||||
*/
|
||||
@Test
|
||||
fun filesSurviveSigningOutAndBackIn() {
|
||||
val name = handle("uid")
|
||||
register(name)
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("New folder").performClick()
|
||||
rule.onNodeWithTag("folder-name").performTextInput("Persistent")
|
||||
rule.onNodeWithText("Create").performClick()
|
||||
rule.awaitRow("row:Persistent")
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("Sign out").performClick()
|
||||
|
||||
rule.waitUntil(15_000) {
|
||||
rule.onAllNodesWithTag("submit").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
// The handle is remembered; only the passphrase is asked for again.
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrase)
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
|
||||
rule.awaitFileList()
|
||||
rule.awaitRow("row:Persistent")
|
||||
rule.onNodeWithTag("row:Persistent").assertIsDisplayed()
|
||||
}
|
||||
|
||||
/** A wrong passphrase is refused, and says so rather than hanging. */
|
||||
@Test
|
||||
fun aWrongPassphraseIsRefused() {
|
||||
val name = handle("uie")
|
||||
register(name)
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("Sign out").performClick()
|
||||
rule.waitUntil(15_000) {
|
||||
rule.onAllNodesWithTag("submit").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
|
||||
rule.onNodeWithTag("passphrase").performTextInput("not the passphrase")
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
|
||||
rule.waitUntil(120_000) {
|
||||
rule.onAllNodesWithText("Something went wrong").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithText("Something went wrong").assertIsDisplayed()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Instrumentation
|
||||
import android.content.Intent
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.hasTestTag
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithTag
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollToNode
|
||||
import androidx.compose.ui.test.performTextClearance
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.test.espresso.intent.Intents
|
||||
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The parts of browsing that had no test at all.
|
||||
*
|
||||
* Navigating into a folder and back is not decoration: the folder you are in
|
||||
* decides which key names its children, so "back" is a key change and not a
|
||||
* view change. And a share link is the one feature that hands something to
|
||||
* somebody who is not signed in, which makes it worth watching most carefully.
|
||||
*
|
||||
* Needs a stack on the host, and this first:
|
||||
*
|
||||
* adb reverse tcp:8081 tcp:8081 && adb reverse tcp:8100 tcp:8100
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class BrowseFlowTest {
|
||||
@get:Rule
|
||||
val rule = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private val server = "http://127.0.0.1:8081"
|
||||
private val passphrase = "correct horse battery staple"
|
||||
|
||||
private fun handle(prefix: String) = "$prefix${System.currentTimeMillis().toString(36)}"
|
||||
|
||||
@Before
|
||||
fun pointAtTheLocalStack() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
context.getSharedPreferences("flamenet-files", 0).edit()
|
||||
.putString("server", server).putString("handle", "").commit()
|
||||
}
|
||||
|
||||
|
||||
/** Waits for a row, scrolling the list if it is below the fold. */
|
||||
|
||||
private fun register(name: String) {
|
||||
rule.waitUntil(10_000) {
|
||||
rule.onAllNodesWithTag("handle").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithTag("mode-register").performClick()
|
||||
rule.onNodeWithTag("handle").performTextClearance()
|
||||
rule.onNodeWithTag("handle").performTextInput(name)
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrase)
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
rule.waitUntil(150_000) {
|
||||
rule.onAllNodesWithText("Write this down now").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithTag("ack-recovery").performClick()
|
||||
rule.awaitFileList()
|
||||
}
|
||||
|
||||
private fun makeFolder(name: String) {
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("New folder").performClick()
|
||||
rule.onNodeWithTag("folder-name").performTextInput(name)
|
||||
rule.onNodeWithText("Create").performClick()
|
||||
rule.awaitRow("row:$name")
|
||||
}
|
||||
|
||||
/**
|
||||
* Into a folder, file something there, and back out.
|
||||
*
|
||||
* A child appearing inside proves it was named under the *folder's* key
|
||||
* rather than the area key — the two are different, and a client that
|
||||
* confuses them produces a listing that decrypts at the top level and
|
||||
* turns to noise one level down.
|
||||
*/
|
||||
@Test
|
||||
fun aFolderCanBeOpenedAndLeft() {
|
||||
register(handle("andbr"))
|
||||
|
||||
makeFolder("Contracts")
|
||||
rule.onNodeWithTag("row:Contracts").performClick()
|
||||
makeFolder("Signed")
|
||||
|
||||
rule.onNodeWithContentDescription("Back").performClick()
|
||||
|
||||
rule.awaitRow("row:Contracts")
|
||||
assertFalse(
|
||||
"a child is showing at the top level, so the listing is not folder-scoped",
|
||||
rule.onAllNodesWithTag("row:Signed").fetchSemanticsNodes().isNotEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Making a link.
|
||||
*
|
||||
* A real file, because a link is offered for files and not for folders —
|
||||
* sharing a folder would mean sharing a key, which is what giving somebody
|
||||
* the area is for.
|
||||
*/
|
||||
@Test
|
||||
fun aShareLinkIsProducedAndKeepsItsSecretInTheFragment() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
val file = File(context.cacheDir, "minutes.txt")
|
||||
file.writeText("what was agreed")
|
||||
val uri = androidx.core.content.FileProvider.getUriForFile(
|
||||
context, "${context.packageName}.files", file)
|
||||
|
||||
Intents.init()
|
||||
try {
|
||||
Intents.intending(hasAction(Intent.ACTION_OPEN_DOCUMENT))
|
||||
.respondWith(Instrumentation.ActivityResult(
|
||||
Activity.RESULT_OK, Intent().setData(uri)))
|
||||
|
||||
register(handle("andbs"))
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("Upload a file").performClick()
|
||||
rule.awaitRow("row:minutes.txt")
|
||||
|
||||
rule.onNodeWithText("Link").performClick()
|
||||
rule.onNodeWithText("Create link").performClick()
|
||||
|
||||
// Generous: this mints a key and wraps it, and an emulator is slow.
|
||||
rule.waitUntil(60_000) {
|
||||
rule.onAllNodesWithTag("share-link").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
val link = rule.onNodeWithTag("share-link").fetchSemanticsNode()
|
||||
.config[SemanticsProperties.Text].first().text
|
||||
assertTrue("the link does not look like a share link: $link", "/s/" in link)
|
||||
// The half that never reaches the server. A "link" without one
|
||||
// would be a link the server could open, which is the entire
|
||||
// property this feature claims.
|
||||
assertTrue("the link has no fragment, so its secret is being sent " +
|
||||
"to the server: $link", "#" in link)
|
||||
rule.onNodeWithText("Copy link").assertIsDisplayed()
|
||||
} finally {
|
||||
Intents.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Choosing where a file will be filed.
|
||||
*
|
||||
* The area decides who can ever read what goes there, so a picker that says
|
||||
* one thing and files another is a confidentiality bug rather than a
|
||||
* cosmetic one. Needs an account with a clearance, which is assigned by
|
||||
* command and cannot be arranged from inside an emulator:
|
||||
*
|
||||
* node scripts/seed-ui-account.mjs
|
||||
*
|
||||
* Skipped rather than failed when that has not been run, because a red test
|
||||
* for a missing fixture trains people to ignore red tests.
|
||||
*/
|
||||
@Test
|
||||
fun theAreaCanBeChangedWithinAClearance() {
|
||||
// Typed in, rather than written to preferences and the activity
|
||||
// recreated. The view model outlives `recreate()` — that is what view
|
||||
// models are for — so it keeps the handle it read at launch, which is
|
||||
// whatever the *previous* test registered. That account exists and has
|
||||
// the same passphrase, so signing in succeeds and lands in the open
|
||||
// area, and the failure reads "did not open at the top of the
|
||||
// clearance" as though the clearance had not been granted.
|
||||
rule.waitUntil(15_000) {
|
||||
rule.onAllNodesWithTag("handle").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithTag("handle").performTextClearance()
|
||||
rule.onNodeWithTag("handle").performTextInput("uitest.cleared")
|
||||
rule.onNodeWithTag("passphrase").performTextClearance()
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrase)
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
|
||||
val cleared = runCatching { rule.awaitFileList() }.isSuccess
|
||||
assumeTrue("no cleared account seeded — run scripts/seed-ui-account.mjs", cleared)
|
||||
|
||||
// The app opens at the top of the clearance on purpose: starting low
|
||||
// would file a sensitive document in the open area because nobody
|
||||
// changed a picker, and that cannot be undone once it has been read.
|
||||
assertTrue(
|
||||
"did not open at the top of the clearance",
|
||||
rule.onAllNodes(hasText("Working at Confidential", substring = true))
|
||||
.fetchSemanticsNodes().isNotEmpty(),
|
||||
)
|
||||
|
||||
rule.onNodeWithContentDescription("Area").performClick()
|
||||
rule.onNodeWithTag("area-Public").performClick()
|
||||
|
||||
rule.waitUntil(20_000) {
|
||||
rule.onAllNodes(hasText("Working at Public", substring = true))
|
||||
.fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.hasTestTag
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithTag
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performScrollToNode
|
||||
import androidx.compose.ui.test.performTextClearance
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Losing a passphrase and getting back in.
|
||||
*
|
||||
* This is the path with the worst failure mode in the app: it runs exactly when
|
||||
* somebody has already lost their only other way in, so a mistake here is not
|
||||
* recoverable by definition. It is also the path least likely to be tried by
|
||||
* hand, because doing so costs a real account every time.
|
||||
*
|
||||
* Needs a stack on the host, and this first:
|
||||
*
|
||||
* adb reverse tcp:8081 tcp:8081 && adb reverse tcp:8100 tcp:8100
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class RecoveryFlowTest {
|
||||
@get:Rule
|
||||
val rule = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private val server = "http://127.0.0.1:8081"
|
||||
private val passphrases = listOf(
|
||||
"correct horse battery staple",
|
||||
"a different passphrase entirely",
|
||||
"third passphrase, also long",
|
||||
)
|
||||
|
||||
private fun handle(prefix: String) = "$prefix${System.currentTimeMillis().toString(36)}"
|
||||
|
||||
@Before
|
||||
fun pointAtTheLocalStack() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
context.getSharedPreferences("flamenet-files", 0).edit()
|
||||
.putString("server", server).putString("handle", "").commit()
|
||||
}
|
||||
|
||||
// MARK: helpers
|
||||
|
||||
private fun awaitSignInScreen() {
|
||||
rule.waitUntil(20_000) {
|
||||
rule.onAllNodesWithTag("handle").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reads the code off the screen and dismisses it.
|
||||
*
|
||||
* Read rather than assumed. The whole question is whether the code a person
|
||||
* is *shown* is the one that will be accepted later, and a test that used
|
||||
* the code the client handed it internally would agree with the client
|
||||
* about a code nobody was ever shown.
|
||||
*/
|
||||
private fun acknowledgeCode(): String {
|
||||
rule.waitUntil(150_000) {
|
||||
rule.onAllNodesWithTag("issued-code").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
// The code is laid out over two lines so a group never wraps in the
|
||||
// middle, so the text carries a newline where a separator belongs.
|
||||
val code = rule.onNodeWithTag("issued-code").fetchSemanticsNode()
|
||||
.config[SemanticsProperties.Text].first().text
|
||||
.replace("\n", "-")
|
||||
rule.onNodeWithTag("ack-recovery").performClick()
|
||||
rule.awaitFileList()
|
||||
return code
|
||||
}
|
||||
|
||||
private fun register(name: String): String {
|
||||
awaitSignInScreen()
|
||||
rule.onNodeWithTag("mode-register").performClick()
|
||||
// Cleared, not just typed into: the handle survives a launch on
|
||||
// purpose, and the rule starts the activity before @Before runs.
|
||||
rule.onNodeWithTag("handle").performTextClearance()
|
||||
rule.onNodeWithTag("handle").performTextInput(name)
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrases[0])
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
return acknowledgeCode()
|
||||
}
|
||||
|
||||
private fun signOut() {
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("Sign out").performClick()
|
||||
awaitSignInScreen()
|
||||
}
|
||||
|
||||
private fun recover(code: String, newPassphrase: String): String {
|
||||
rule.onNodeWithTag("mode-recover").performClick()
|
||||
rule.onNodeWithTag("passphrase").performTextClearance()
|
||||
rule.onNodeWithTag("passphrase").performTextInput(newPassphrase)
|
||||
rule.onNodeWithTag("recovery-code").performTextClearance()
|
||||
rule.onNodeWithTag("recovery-code").performTextInput(code)
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
return acknowledgeCode()
|
||||
}
|
||||
|
||||
// MARK: the flows
|
||||
|
||||
/**
|
||||
* The whole point of recovering rather than starting over: the keys are the
|
||||
* same afterwards, so what was filed before is still readable.
|
||||
*/
|
||||
@Test
|
||||
fun recoveringKeepsTheFiles() {
|
||||
val first = register(handle("andrec"))
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("New folder").performClick()
|
||||
rule.onNodeWithTag("folder-name").performTextInput("Ledger")
|
||||
rule.onNodeWithText("Create").performClick()
|
||||
rule.awaitRow("row:Ledger")
|
||||
|
||||
signOut()
|
||||
recover(first, passphrases[1])
|
||||
|
||||
// Decrypted with a key unwrapped by the recovery code rather than by the
|
||||
// passphrase that encrypted it. Had recovery quietly minted a new
|
||||
// identity, this row would be present and unreadable.
|
||||
rule.awaitRow("row:Ledger")
|
||||
}
|
||||
|
||||
/**
|
||||
* The regression this file was written for.
|
||||
*
|
||||
* Both mobile clients used to generate the replacement code twice — once
|
||||
* for the account service and once for the identity record — and displayed
|
||||
* the second one. The first recovery looked perfect, and the account was
|
||||
* afterwards recoverable only with a code that had never been shown to
|
||||
* anybody. It takes a *second* recovery to notice, which is to say it would
|
||||
* have been noticed by somebody who had already lost a passphrase twice.
|
||||
*/
|
||||
@Test
|
||||
fun theCodeShownAfterRecoveringWorksNextTime() {
|
||||
val first = register(handle("andcode"))
|
||||
signOut()
|
||||
|
||||
val second = recover(first, passphrases[1])
|
||||
assertNotEquals("recovering did not issue a fresh code", first, second)
|
||||
|
||||
signOut()
|
||||
recover(second, passphrases[2])
|
||||
rule.awaitFileList()
|
||||
}
|
||||
|
||||
/** A mistyped code has to say so, and leave the account alone. */
|
||||
@Test
|
||||
fun aWrongRecoveryCodeIsRefused() {
|
||||
register(handle("andwrong"))
|
||||
signOut()
|
||||
|
||||
rule.onNodeWithTag("mode-recover").performClick()
|
||||
rule.onNodeWithTag("passphrase").performTextClearance()
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrases[1])
|
||||
// Right shape, right alphabet, wrong code — refused by the server
|
||||
// rather than by the client's own checksum.
|
||||
rule.onNodeWithTag("recovery-code").performTextInput("045J7GAKYE7BCCK7DT3NPQEW2980")
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
|
||||
rule.waitUntil(120_000) {
|
||||
rule.onAllNodesWithText("Something went wrong").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
rule.onNodeWithText("OK").performClick()
|
||||
|
||||
// And the original passphrase still works, so the failed attempt
|
||||
// changed nothing.
|
||||
rule.onNodeWithTag("mode-sign_in").performClick()
|
||||
rule.onNodeWithTag("passphrase").performTextClearance()
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrases[0])
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
rule.awaitFileList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import androidx.compose.ui.test.hasTestTag
|
||||
import androidx.compose.ui.test.hasText
|
||||
import androidx.compose.ui.test.junit4.ComposeTestRule
|
||||
import androidx.compose.ui.test.onAllNodesWithTag
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.performScrollToNode
|
||||
|
||||
/**
|
||||
* Shared driving for the instrumented suites, so a fix lands in one place
|
||||
* rather than in whichever file somebody happened to be editing.
|
||||
*/
|
||||
|
||||
/** The area banner, which is the proof that the browse screen actually loaded. */
|
||||
fun ComposeTestRule.awaitFileList(timeoutMillis: Long = 60_000) {
|
||||
waitUntil(timeoutMillis) {
|
||||
onAllNodes(hasText("Working at", substring = true))
|
||||
.fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a row, scrolling once if it is below the fold.
|
||||
*
|
||||
* The open area is shared: every account cleared for it sees every row filed
|
||||
* there, including the ones it cannot decrypt. So the list is not empty when a
|
||||
* new account arrives, a freshly created row is not necessarily on screen, and
|
||||
* a lazy list does not compose rows it has not shown — which makes "further
|
||||
* down" and "not there at all" look identical.
|
||||
*
|
||||
* ⚠️ The scroll happens *once*, outside the waiting. Doing it inside a
|
||||
* `waitUntil` predicate re-runs it on every poll, and every one of those runs
|
||||
* on the main thread: the app then stops answering input long enough for the
|
||||
* system to declare it unresponsive, and the whole instrumentation run dies
|
||||
* with `keyDispatchingTimedOut` — a test that looked exactly like an app that
|
||||
* hangs.
|
||||
*/
|
||||
fun ComposeTestRule.awaitRow(tag: String) {
|
||||
val showing = { onAllNodesWithTag(tag).fetchSemanticsNodes().isNotEmpty() }
|
||||
|
||||
val quick = runCatching { waitUntil(10_000) { showing() } }.isSuccess
|
||||
if (quick) return
|
||||
|
||||
runCatching { onNodeWithTag("entries").performScrollToNode(hasTestTag(tag)) }
|
||||
waitUntil(20_000) { showing() }
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithTag
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performTextClearance
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.test.uiautomator.UiDevice
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Walks the app and photographs it.
|
||||
*
|
||||
* Not an assertion suite — a way to look at what people actually see. Green
|
||||
* tests say the wiring works; they say nothing about whether a screen is
|
||||
* legible, whether the important thing on it is what stands out, or whether
|
||||
* the words make sense to somebody who has not read the source.
|
||||
*
|
||||
* Writes PNGs to the device's external files directory, which `adb pull`
|
||||
* reaches.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class VisualTourTest {
|
||||
@get:Rule
|
||||
val rule = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private val server = "http://127.0.0.1:8081"
|
||||
private val passphrase = "correct horse battery staple"
|
||||
|
||||
@Before
|
||||
fun pointAtTheLocalStack() {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
context.getSharedPreferences("flamenet-files", 0).edit()
|
||||
.putString("server", server).putString("handle", "").commit()
|
||||
}
|
||||
|
||||
private fun shoot(name: String) {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
// Loud on failure. Returning quietly when there is nowhere to write
|
||||
// produced a tour that ran, passed, and photographed nothing.
|
||||
val directory = context.getExternalFilesDir(null)
|
||||
?: throw AssertionError("no external files directory to write $name to")
|
||||
directory.mkdirs()
|
||||
val file = File(directory, "tour-$name.png")
|
||||
val taken = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
|
||||
.takeScreenshot(file)
|
||||
if (!taken || !file.exists()) {
|
||||
throw AssertionError("could not photograph $name at ${file.absolutePath}")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun walkTheScreens() {
|
||||
rule.waitUntil(20_000) {
|
||||
rule.onAllNodesWithTag("handle").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
shoot("01-signin")
|
||||
|
||||
rule.onNodeWithTag("mode-register").performClick()
|
||||
shoot("02-create-account")
|
||||
|
||||
val name = "tour${System.currentTimeMillis().toString(36)}"
|
||||
rule.onNodeWithTag("handle").performTextClearance()
|
||||
rule.onNodeWithTag("handle").performTextInput(name)
|
||||
rule.onNodeWithTag("passphrase").performTextInput(passphrase)
|
||||
// Settled before photographing. Without this the picture catches the
|
||||
// field mid-typing — empty, with the submit button still disabled —
|
||||
// which looks like a bug and shows nothing about the keyboard.
|
||||
rule.waitForIdle()
|
||||
rule.waitUntil(5_000) {
|
||||
rule.onAllNodesWithTag("submit").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
shoot("03-filled-in")
|
||||
|
||||
rule.onNodeWithTag("submit").performClick()
|
||||
rule.waitUntil(150_000) {
|
||||
rule.onAllNodesWithText("Write this down now").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
shoot("04-recovery-code")
|
||||
|
||||
rule.onNodeWithTag("ack-recovery").performClick()
|
||||
rule.awaitFileList()
|
||||
shoot("05-empty-area")
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
shoot("06-the-menu")
|
||||
rule.onNodeWithText("New folder").performClick()
|
||||
shoot("07-new-folder-dialog")
|
||||
rule.onNodeWithTag("folder-name").performTextInput("Contracts")
|
||||
rule.onNodeWithText("Create").performClick()
|
||||
rule.awaitRow("row:Contracts")
|
||||
shoot("08-with-a-folder")
|
||||
|
||||
rule.onNodeWithTag("overflow").performClick()
|
||||
rule.onNodeWithText("Share this area").performClick()
|
||||
rule.waitUntil(15_000) {
|
||||
rule.onAllNodesWithText("Give them the key").fetchSemanticsNodes().isNotEmpty()
|
||||
}
|
||||
shoot("09-share-this-area")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
@@ -45,12 +46,7 @@ fun Browse(model: FilesViewModel, state: UiState) {
|
||||
ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
uri ?: return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
val name = uri.lastPathSegment?.substringAfterLast('/') ?: "file"
|
||||
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
if (bytes == null) return@launch
|
||||
model.upload(bytes, name)
|
||||
}
|
||||
scope.launch { model.uploadFrom(uri, context.contentResolver) }
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { model.refresh() }
|
||||
@@ -80,13 +76,23 @@ fun Browse(model: FilesViewModel, state: UiState) {
|
||||
)
|
||||
},
|
||||
onClick = { showingAreas = false; model.use(label) },
|
||||
// Tagged because an area's name is also the
|
||||
// subtitle of every row filed there, so
|
||||
// matching on the text finds a dozen nodes
|
||||
// and can only pick the wrong one.
|
||||
modifier = Modifier.testTag(
|
||||
"area-${model.nameFor(label)}",
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
IconButton(onClick = { showingMenu = true }) {
|
||||
IconButton(
|
||||
onClick = { showingMenu = true },
|
||||
modifier = Modifier.testTag("overflow"),
|
||||
) {
|
||||
Icon(Icons.Default.MoreVert, contentDescription = "More")
|
||||
}
|
||||
DropdownMenu(showingMenu, onDismissRequest = { showingMenu = false }) {
|
||||
@@ -141,7 +147,10 @@ fun Browse(model: FilesViewModel, state: UiState) {
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn {
|
||||
// Tagged so a test can scroll it. The open area is shared, so this
|
||||
// list is not empty when you arrive and a row you just created is
|
||||
// not necessarily on screen.
|
||||
LazyColumn(modifier = Modifier.testTag("entries")) {
|
||||
items(state.entries, key = { it.id }) { entry ->
|
||||
Row(entry, model, onShare = { sharing = entry })
|
||||
HorizontalDivider()
|
||||
@@ -160,6 +169,7 @@ fun Browse(model: FilesViewModel, state: UiState) {
|
||||
onValueChange = { folderName = it },
|
||||
singleLine = true,
|
||||
label = { Text("Name") },
|
||||
modifier = Modifier.testTag("folder-name"),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
@@ -280,7 +290,7 @@ private fun Row(entry: FilesSession.Entry, model: FilesViewModel, onShare: () ->
|
||||
TextButton(onClick = onShare) { Text("Link") }
|
||||
}
|
||||
},
|
||||
modifier = Modifier.clickable {
|
||||
modifier = Modifier.testTag("row:${entry.name ?: "locked"}").clickable {
|
||||
if (entry.isFolder) {
|
||||
model.open(entry)
|
||||
} else if (entry.name != null) {
|
||||
@@ -333,8 +343,12 @@ private fun ShareDialog(entry: FilesSession.Entry, model: FilesViewModel, onDism
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
val current = link
|
||||
if (current != null) {
|
||||
// Tagged so a test can read the link back and check that
|
||||
// its secret is in the fragment, where the server never
|
||||
// sees it — the one property this feature claims.
|
||||
Text(current, fontFamily = FontFamily.Monospace,
|
||||
style = MaterialTheme.typography.bodySmall)
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.testTag("share-link"))
|
||||
Text(
|
||||
"The part after # never leaves the recipient's browser, so the server storing this link cannot open it.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import io.flamenet.files.client.AccountsClient
|
||||
@@ -130,6 +133,10 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
|
||||
var freshCode: String? = null
|
||||
var enrolledKey: java.security.PrivateKey? = null
|
||||
// The replacement code issued during recovery. Held here because it
|
||||
// has to reach *both* writes below, and they are on opposite sides
|
||||
// of signing in.
|
||||
var replacementEntropy: ByteArray? = null
|
||||
|
||||
when (mode) {
|
||||
SignInMode.REGISTER -> {
|
||||
@@ -155,9 +162,16 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
enrolledKey = pair.private
|
||||
}
|
||||
SignInMode.RECOVER -> {
|
||||
// One code, threaded through both writes. The account
|
||||
// service stores an auth secret derived from it and the
|
||||
// identity record is wrapped under it, and those have to be
|
||||
// the same code: the one displayed afterwards comes from the
|
||||
// identity side, so if they diverge the account can only ever
|
||||
// be recovered again with a code nobody was ever shown.
|
||||
val next = Recovery.generate().entropy
|
||||
replacementEntropy = next
|
||||
accounts.rotate(
|
||||
handle, Recovery.decode(recoveryCode),
|
||||
passphrase, Recovery.generate().entropy,
|
||||
handle, Recovery.decode(recoveryCode), passphrase, next,
|
||||
)
|
||||
}
|
||||
SignInMode.SIGN_IN -> Unit
|
||||
@@ -173,7 +187,7 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
)
|
||||
SignInMode.RECOVER -> FilesSession.recover(
|
||||
api, accounts, token, recoveryCode, passphrase,
|
||||
clearance, Recovery.generate().entropy,
|
||||
clearance, replacementEntropy!!,
|
||||
)
|
||||
SignInMode.SIGN_IN -> FilesSession.open(
|
||||
api, accounts, token, passphrase, clearance,
|
||||
@@ -181,6 +195,9 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
}
|
||||
|
||||
session = opened
|
||||
// The server's own limit, so a file too big for it is refused
|
||||
// before this device reads it into memory rather than after.
|
||||
opened.maxUploadBytes = config.maxUploadBytes
|
||||
opened.loadLabelKeys()
|
||||
val vocabulary = api.vocabulary()
|
||||
// The *maximum*, matching the web client, and deliberately not the
|
||||
@@ -225,7 +242,16 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
fun refresh() = launchIO {
|
||||
val current = session ?: return@launchIO
|
||||
try {
|
||||
// Readable rows first. An area is shared by everyone cleared for
|
||||
// it, so the listing contains other people's files as rows without
|
||||
// names. Showing them is deliberate and hiding them would be a lie
|
||||
// about what the server knows — but arriving at a screenful of
|
||||
// "Encrypted for another key" with your own folder below the fold
|
||||
// is a poor way to meet the thing. Partitioned rather than sorted,
|
||||
// so the server's ordering is otherwise untouched.
|
||||
val entries = current.list(folderID)
|
||||
.partition { it.name != null }
|
||||
.let { (readable, locked) -> readable + locked }
|
||||
_state.update { it.copy(entries = entries) }
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = friendly(error)) }
|
||||
@@ -267,16 +293,64 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
fun upload(bytes: ByteArray, name: String) = launchIO {
|
||||
val current = session ?: return@launchIO
|
||||
/**
|
||||
* Take a document the chooser handed back and put it in the current area.
|
||||
*
|
||||
* The name and the size come from the content resolver rather than from the
|
||||
* URI: a `content://` path segment is an opaque id on most providers, and
|
||||
* naming every uploaded file after one would be worse than useless.
|
||||
*
|
||||
* Size is checked before the bytes are read. Reading a file to find out how
|
||||
* big it is defeats the point of asking, and on a phone the difference is a
|
||||
* message versus a crash.
|
||||
*/
|
||||
fun uploadFrom(uri: Uri, resolver: ContentResolver) = launchIO {
|
||||
var name = "file"
|
||||
var size = -1L
|
||||
resolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val nameColumn = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||
val sizeColumn = cursor.getColumnIndex(OpenableColumns.SIZE)
|
||||
if (cursor.moveToFirst()) {
|
||||
if (nameColumn >= 0) name = cursor.getString(nameColumn) ?: name
|
||||
if (sizeColumn >= 0 && !cursor.isNull(sizeColumn)) size = cursor.getLong(sizeColumn)
|
||||
}
|
||||
}
|
||||
|
||||
val limit = session?.maxUploadBytes
|
||||
if (limit != null && size > limit) {
|
||||
_state.update {
|
||||
it.copy(error = "$name is ${size / 1_000_000} MB. " +
|
||||
"This server accepts up to ${limit / 1_000_000} MB.")
|
||||
}
|
||||
return@launchIO
|
||||
}
|
||||
|
||||
val bytes = try {
|
||||
resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
} catch (error: Exception) {
|
||||
null
|
||||
}
|
||||
if (bytes == null) {
|
||||
_state.update { it.copy(error = "Could not read that file.") }
|
||||
return@launchIO
|
||||
}
|
||||
uploadBytes(bytes, name)
|
||||
}
|
||||
|
||||
fun upload(bytes: ByteArray, name: String) = launchIO { uploadBytes(bytes, name) }
|
||||
|
||||
private suspend fun uploadBytes(bytes: ByteArray, name: String) {
|
||||
val current = session ?: return
|
||||
_state.update { it.copy(phase = Phase.Working("Encrypting $name…")) }
|
||||
try {
|
||||
current.upload(bytes, name, folderID)
|
||||
_state.update { it.copy(phase = Phase.Browsing) }
|
||||
refresh()
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(phase = Phase.Browsing, error = friendly(error)) }
|
||||
return
|
||||
}
|
||||
val entries = try { current.list(folderID) } catch (error: Exception) { return }
|
||||
_state.update { it.copy(entries = entries) }
|
||||
}
|
||||
|
||||
suspend fun download(entry: FilesSession.Entry): ByteArray? = withContext(Dispatchers.IO) {
|
||||
@@ -318,8 +392,38 @@ class FilesViewModel(context: Context) : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun friendly(error: Throwable): String =
|
||||
(error as? ClientException)?.message ?: error.message ?: "Something went wrong."
|
||||
/**
|
||||
* Turn an accurate message into an actionable one.
|
||||
*
|
||||
* The server's refusals are deliberately terse and deliberately identical
|
||||
* to each other — "handle or passphrase is incorrect" says nothing about
|
||||
* which, because saying more would confirm who holds an account. That is
|
||||
* right on the wire and wrong on screen, where it arrives lowercase and
|
||||
* unpunctuated in the middle of a dialog. Matched on the wording the web
|
||||
* client matches on, so the three clients say the same things.
|
||||
*/
|
||||
private fun friendly(error: Throwable): String {
|
||||
val raw = (error as? ClientException)?.message ?: error.message
|
||||
?: return "Something went wrong."
|
||||
val text = raw.lowercase()
|
||||
return when {
|
||||
"checksum" in text -> "That recovery code has a typo in it."
|
||||
"28 characters" in text || "must be 28" in text ->
|
||||
"A recovery code is 28 characters. Check for a missing chunk."
|
||||
"invalid character" in text ->
|
||||
"That recovery code has a character that isn't part of one. Check for a typo."
|
||||
"not available" in text -> "That handle is already taken."
|
||||
"handle or passphrase" in text -> "Handle or passphrase is incorrect."
|
||||
"handle or recovery code" in text -> "Handle or recovery code is incorrect."
|
||||
"no recovery code on file" in text -> "This account has no recovery code on file."
|
||||
// Already a sentence, and one worth showing exactly as sent.
|
||||
"too many" in text -> raw
|
||||
"failed to connect" in text || "unable to resolve" in text
|
||||
|| "connection refused" in text || "timeout" in text ->
|
||||
"Couldn't reach the server. Check the address and your connection."
|
||||
else -> raw
|
||||
}
|
||||
}
|
||||
|
||||
private fun launchIO(block: suspend () -> Unit) {
|
||||
viewModelScope.launch(Dispatchers.IO) { block() }
|
||||
|
||||
@@ -9,6 +9,11 @@ import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
@@ -17,6 +22,7 @@ import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
@@ -118,7 +124,17 @@ fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
onValueChange = model::setHandle,
|
||||
label = { Text("Handle") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
// A handle is not prose. Left to its defaults the keyboard
|
||||
// capitalises the first letter and offers corrections, and a
|
||||
// corrected handle is somebody else's account or nobody's.
|
||||
keyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.None,
|
||||
autoCorrectEnabled = false,
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
),
|
||||
// Tagged rather than found by label: the copy is allowed to change
|
||||
// without silently un-testing the field it names.
|
||||
modifier = Modifier.fillMaxWidth().testTag("handle"),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = passphrase,
|
||||
@@ -126,7 +142,16 @@ fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
label = { Text(if (mode == SignInMode.RECOVER) "New passphrase" else "Passphrase") },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
// Declared a password so the keyboard stops autocorrecting and
|
||||
// stops suggesting. A passphrase is chosen to be long and
|
||||
// memorable rather than dictionary-shaped, which is exactly the
|
||||
// sort of text autocorrect likes to improve — and an improved
|
||||
// passphrase cannot be recovered, only replaced with the code.
|
||||
keyboardOptions = KeyboardOptions(
|
||||
autoCorrectEnabled = false,
|
||||
keyboardType = KeyboardType.Password,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth().testTag("passphrase"),
|
||||
)
|
||||
if (mode == SignInMode.RECOVER) {
|
||||
OutlinedTextField(
|
||||
@@ -134,7 +159,15 @@ fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
onValueChange = { recoveryCode = it },
|
||||
label = { Text("Recovery code") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
// Twenty-eight characters of Crockford base32, typed once,
|
||||
// under stress, from paper. Autocorrect has no business here
|
||||
// and the alphabet is upper case.
|
||||
keyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.Characters,
|
||||
autoCorrectEnabled = false,
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth().testTag("recovery-code"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -154,7 +187,7 @@ fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
onClick = { model.signIn(passphrase, mode, recoveryCode) },
|
||||
enabled = state.handle.isNotBlank() && passphrase.isNotEmpty() &&
|
||||
(mode != SignInMode.RECOVER || recoveryCode.isNotBlank()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier.fillMaxWidth().testTag("submit"),
|
||||
) { Text(mode.label) }
|
||||
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
@@ -163,6 +196,7 @@ fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
selected = mode == option,
|
||||
onClick = { mode = option },
|
||||
shape = SegmentedButtonDefaults.itemShape(index, SignInMode.entries.size),
|
||||
modifier = Modifier.testTag("mode-${option.name.lowercase()}"),
|
||||
) { Text(option.label) }
|
||||
}
|
||||
}
|
||||
@@ -196,11 +230,21 @@ fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
}
|
||||
|
||||
/** Shown once, and it says so. */
|
||||
/// Lays a recovery code out four groups to a line, so it never wraps in the
|
||||
/// middle of one.
|
||||
private fun inGroupedLines(code: String, perLine: Int = 4): String =
|
||||
code.split("-").chunked(perLine).joinToString("\n") { it.joinToString("-") }
|
||||
|
||||
@Composable
|
||||
fun RecoveryCode(code: String, onAcknowledge: () -> Unit) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
// Scrollable, because this screen has no way out except the button at the
|
||||
// bottom of it. A long code, a large font-size setting or a small phone
|
||||
// pushes that button past the edge, and an unreachable button here does not
|
||||
// mean a clumsy layout — it means the account is finished, the code is on
|
||||
// screen, and the app cannot be used again.
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(28.dp),
|
||||
modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(28.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
@@ -220,17 +264,31 @@ fun RecoveryCode(code: String, onAcknowledge: () -> Unit) {
|
||||
// Monospaced and generously spaced, because this gets copied onto
|
||||
// paper by hand and a wrapped group is a transcription error.
|
||||
Text(
|
||||
code,
|
||||
// Broken into lines here rather than left to wrap.
|
||||
//
|
||||
// Left alone the last group splits across the line — "…-YR"
|
||||
// and "RK" on the next — and this is the screen somebody
|
||||
// copies onto paper by hand, once, with no way to check it
|
||||
// afterwards. A group cut in half is a transcription error
|
||||
// waiting to happen.
|
||||
inGroupedLines(code),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(18.dp).fillMaxWidth(),
|
||||
// Tagged so a test can read back the code it was actually
|
||||
// shown. Checking that the *displayed* code still works is the
|
||||
// only way to catch a client that files one code with the
|
||||
// account service and prints a different one.
|
||||
modifier = Modifier.padding(18.dp).fillMaxWidth().testTag("issued-code"),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(22.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(onClick = { clipboard.setText(AnnotatedString(code)) }) { Text("Copy") }
|
||||
Button(onClick = onAcknowledge) { Text("I've written it down") }
|
||||
Button(
|
||||
onClick = onAcknowledge,
|
||||
modifier = Modifier.testTag("ack-recovery"),
|
||||
) { Text("I've written it down") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,7 +307,21 @@ class FilesSession internal constructor(
|
||||
* the label key — never to the parent folder's key. That is what keeps the
|
||||
* key hierarchy aligned with the lattice rather than with the tree.
|
||||
*/
|
||||
/**
|
||||
* The largest file this session will attempt, learned from the server.
|
||||
*
|
||||
* Enforced here rather than left to the server's rejection because the costs
|
||||
* are not symmetric: by the time the server says no, the client has read the
|
||||
* whole file into memory and encrypted it into a second copy. On a phone
|
||||
* that is not a wasted round trip, it is a crash.
|
||||
*/
|
||||
var maxUploadBytes: Long? = null
|
||||
|
||||
fun upload(bytes: ByteArray, name: String, parentID: String? = null): Wire.Node? {
|
||||
val limit = maxUploadBytes
|
||||
if (limit != null && bytes.size > limit) {
|
||||
throw ClientException.TooLarge(limit, bytes.size.toLong())
|
||||
}
|
||||
requireLabelKey()
|
||||
val folderKey = folderKey(parentID)
|
||||
val nodeKey = ByteArray(32).also(random::nextBytes)
|
||||
|
||||
@@ -32,6 +32,12 @@ object Wire {
|
||||
val siteURL: String,
|
||||
val sourceURL: String,
|
||||
val protocolVersion: Int,
|
||||
/**
|
||||
* The largest ciphertext this deployment accepts. Null on servers older
|
||||
* than this field — an app that refused to work against a slightly older
|
||||
* server would be worse than one that finds the limit the hard way.
|
||||
*/
|
||||
val maxUploadBytes: Long? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -221,6 +227,12 @@ sealed class ClientException(message: String) : Exception(message) {
|
||||
)
|
||||
|
||||
class NotCleared : ClientException("You aren't cleared for this.")
|
||||
|
||||
/** Refused before reading, not after uploading. */
|
||||
class TooLarge(limit: Long, actual: Long) : ClientException(
|
||||
"That file is ${actual / 1_000_000} MB. " +
|
||||
"This server accepts up to ${limit / 1_000_000} MB.",
|
||||
)
|
||||
class WrongPassphrase : ClientException("That handle and passphrase don't match.")
|
||||
class BadServer(why: String) : ClientException(why)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user