Stop iOS choosing the passphrase, and fix recovering twice

Three bugs, all of which only appear the second time somebody needs the
account.

The passphrase field was `.textContentType(.newPassword)`, which invites
iOS to generate and insert a strong password. Accounts created through
this screen could then not be signed into with the passphrase that had
been typed into them — verified both ways with filesctl. Nothing looks
wrong at the time, because the app signs in with the same value it
registered with; it comes apart at the next sign-in. For a passphrase that
derives the keys and cannot be reset, a secret the person never read
leaves them with a recovery code as their only way back.

Recovery minted the replacement code twice — one for 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. One code now reaches both writes.

`EngineError` did not conform to `LocalizedError`, so a mistyped recovery
code reached the person who had just lost their passphrase as "The
operation couldn't be completed. (FilesEngine.EngineError error 1.)". The
reasons were always sentences at the throw site; now they survive.

Also: the recovery code is laid out four groups to a line so a group never
wraps in the middle — this is copied onto paper by hand, once — the
recovery screen scrolls so its only exit cannot sit off screen, and rows
this device can read come before the ones it cannot, so a new account does
not arrive at a screenful of "Encrypted for another key".

The UI suites are new: registration, sign-in, recovering (twice, which is
what catches the above), folders, upload, share links with the secret
asserted to be in the fragment, and a visual tour that photographs each
screen — the recovery code wrapping was found by looking, not by asserting.

⚠️ ProductionTourTests no longer carries a live credential for the
deployment. It was committed in plain text to a public repository, so the
account it belonged to has to be treated as compromised and its passphrase
changed; removing it here stops the leak continuing, it does not undo it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Paul Hitt
2026-08-22 20:27:00 -04:00
co-authored by Claude Opus 5
parent 47e21e3cce
commit 3ad9a93449
16 changed files with 1096 additions and 95 deletions
+4
View File
@@ -22,11 +22,15 @@
<string>1</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>UIFileSharingEnabled</key>
<true/>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
+105 -4
View File
@@ -92,6 +92,10 @@ final class AppState: ObservableObject {
var freshCode: String?
var enrolledKey: Curve25519.KeyAgreement.PrivateKey?
// 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: Data?
switch mode {
case .register:
@@ -112,7 +116,14 @@ final class AppState: ObservableObject {
case .recover:
let entropy = try Recovery.decode(recoveryCode)
// 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.
let (nextEntropy, _) = Recovery.generate()
replacementEntropy = nextEntropy
try await accounts.rotate(
handle: handle, entropy: entropy,
newPassphrase: passphrase, nextEntropy: nextEntropy)
@@ -132,11 +143,10 @@ final class AppState: ObservableObject {
api: api, accounts: accounts, token: token,
privateKey: enrolledKey!, clearance: claims.clearance, recoveryCode: freshCode)
case .recover:
let (nextEntropy, _) = Recovery.generate()
opened = try await FilesSession.recover(
api: api, accounts: accounts, token: token, code: recoveryCode,
newPassphrase: passphrase, clearance: claims.clearance,
nextEntropy: nextEntropy)
nextEntropy: replacementEntropy!)
case .signIn:
opened = try await FilesSession.open(
api: api, accounts: accounts, token: token,
@@ -144,6 +154,9 @@ final class AppState: ObservableObject {
}
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.
await opened.setMaxUploadBytes(config.maxUploadBytes)
clearance = claims.clearance
try await opened.loadLabelKeys()
vocabulary = try await api.vocabulary()
@@ -193,10 +206,23 @@ final class AppState: ObservableObject {
func refresh() async {
guard let session else { return }
do { entries = try await session.list(folderID) }
do { entries = Self.readableFirst(try await session.list(folderID)) }
catch { self.error = message(error) }
}
/// Puts the rows this device can read above the ones it cannot.
///
/// 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 somewhere below the fold is a poor way to meet the thing.
///
/// A stable partition, so the server's ordering is otherwise untouched.
static func readableFirst(_ entries: [FilesSession.Entry]) -> [FilesSession.Entry] {
entries.filter { $0.name != nil } + entries.filter { $0.name == nil }
}
func open(_ entry: FilesSession.Entry) async {
guard entry.isFolder else { return }
path.append((entry.id, entry.name ?? "Folder"))
@@ -230,6 +256,39 @@ final class AppState: ObservableObject {
} catch { self.error = message(error) }
}
/// What this deployment accepts, for checking a file before reading it.
var maxUploadBytes: Int? { config?.maxUploadBytes }
/// Take a file the picker handed back and put it in the current area.
///
/// Extracted from the picker's callback so it can be exercised without one.
/// The picker itself belongs to the system and testing it would be testing
/// the system; what is worth testing is everything after — the size check,
/// reading, encrypting, uploading, and the list coming back readable.
///
/// ⚠️ `startAccessingSecurityScopedResource` is the caller's job, because
/// only the caller knows whether the URL came from outside the sandbox.
func uploadFile(at url: URL) async {
do {
// Size from metadata first, so an oversized file is refused without
// ever being read. Reading it to find out how big it is defeats the
// point of asking.
let size = (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
if let limit = maxUploadBytes, size > limit {
let formatter = ByteCountFormatter()
formatter.countStyle = .file
error = "\(url.lastPathComponent) is "
+ "\(formatter.string(fromByteCount: Int64(size))). This server accepts "
+ "up to \(formatter.string(fromByteCount: Int64(limit)))."
return
}
let data = try Data(contentsOf: url)
await upload(data, named: url.lastPathComponent)
} catch {
self.error = "Could not read that file."
}
}
func upload(_ data: Data, named name: String) async {
guard let session else { return }
phase = .working("Encrypting \(name)…")
@@ -289,7 +348,49 @@ final class AppState: ObservableObject {
}
private func message(_ error: any Error) -> String {
(error as? LocalizedError)?.errorDescription ?? error.localizedDescription
Self.friendly((error as? LocalizedError)?.errorDescription ?? error.localizedDescription)
}
/// 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 an alert. Matched on the wording the web
/// client matches on, so the three clients say the same things.
static func friendly(_ raw: String) -> String {
let text = raw.lowercased()
if text.contains("checksum") {
return "That recovery code has a typo in it."
}
if text.contains("28 characters") || text.contains("must be 28") {
return "A recovery code is 28 characters. Check for a missing chunk."
}
if text.contains("invalid character") {
return "That recovery code has a character that isn't part of one. Check for a typo."
}
if text.contains("not available") {
return "That handle is already taken."
}
if text.contains("handle or passphrase") {
return "Handle or passphrase is incorrect."
}
if text.contains("handle or recovery code") {
return "Handle or recovery code is incorrect."
}
if text.contains("no recovery code on file") {
return "This account has no recovery code on file."
}
if text.contains("too many") {
// Already a sentence, and one worth showing exactly as sent.
return raw
}
if text.contains("could not connect") || text.contains("offline")
|| text.contains("connection") || text.contains("could not be found") {
return "Couldn't reach the server. Check the address and your connection."
}
return raw
}
}
+30 -6
View File
@@ -58,6 +58,23 @@ struct BrowseView: View {
Button { importing = true } label: {
Label("Upload a file", systemImage: "arrow.up.doc")
}
#if DEBUG
// The chooser is another process and XCUITest cannot
// see into it, so the upload path had no test at all.
// This picks the file the test seeded into the app's
// own container and hands it to the same code the
// chooser's callback does — everything except the
// chooser itself, which is Apple's to test. Android's
// equivalent stubs the chooser for the same reason.
//
// Debug-only, and only when a test asked for a seeded
// document, so a release build has no such control.
if let seeded = UITestHooks.seededDocumentURL {
Button { Task { await state.uploadFile(at: seeded) } } label: {
Label("Upload seeded file", systemImage: "ladybug")
}
}
#endif
Button { newFolder = true } label: {
Label("New folder", systemImage: "folder.badge.plus")
}
@@ -72,6 +89,11 @@ struct BrowseView: View {
} label: {
Image(systemName: "ellipsis.circle")
}
// Identified rather than found by position. "The last
// button in the navigation bar" picks a *nested* button on
// this layout, and tapping that opens nothing at all — so
// every action behind this menu silently did not happen.
.accessibilityIdentifier("more-menu")
}
}
.safeAreaInset(edge: .top) {
@@ -99,12 +121,7 @@ struct BrowseView: View {
return
}
defer { url.stopAccessingSecurityScopedResource() }
do {
let data = try Data(contentsOf: url)
await state.upload(data, named: url.lastPathComponent)
} catch {
state.error = "Could not read that file."
}
await state.uploadFile(at: url)
}
}
.alert("New folder", isPresented: $newFolder) {
@@ -191,11 +208,18 @@ struct LabelMenu: View {
Text(state.name(for: label))
}
}
// Identified because an area's name also appears on every row
// filed there, so matching on the visible text picks a row and
// silently does nothing.
.accessibilityIdentifier("area-\(state.name(for: label))")
}
} label: {
Label(state.label.map(state.name(for:)) ?? "Area", systemImage: "shield.lefthalf.filled")
.labelStyle(.titleAndIcon)
.font(.footnote)
}
// Identified because the menu's own label is the current area's name,
// which is also the name of one of the items inside it.
.accessibilityIdentifier("area-menu")
}
}
+44 -1
View File
@@ -6,11 +6,54 @@ struct FlamenetFilesApp: App {
var body: some Scene {
WindowGroup {
RootView().environmentObject(state)
RootView()
.environmentObject(state)
.task { await UITestHooks.seedIfRequested() }
}
}
}
/// Support for driving the app from a UI test.
///
/// XCUITest has no equivalent of Espresso's intent stubbing, so a test cannot
/// hand the app a file the way the system chooser does. This writes a file into
/// the app's own container on request, so a test can then pick it through the
/// real chooser rather than through a back door.
///
/// ⚠️ Compiled only in debug builds. A release build has no way to be told to
/// write anything, which is the only version of this worth shipping.
enum UITestHooks {
/// The document a test asked to be seeded, if any.
static var seededDocumentURL: URL? {
#if DEBUG
let arguments = ProcessInfo.processInfo.arguments
guard let index = arguments.firstIndex(of: "-seed-document"),
index + 1 < arguments.count,
let documents = FileManager.default.urls(
for: .documentDirectory, in: .userDomainMask).first
else { return nil }
return documents.appendingPathComponent(arguments[index + 1])
#else
return nil
#endif
}
static func seedIfRequested() async {
#if DEBUG
let arguments = ProcessInfo.processInfo.arguments
guard let index = arguments.firstIndex(of: "-seed-document"),
index + 1 < arguments.count else { return }
let name = arguments[index + 1]
let contents = arguments.count > index + 2 ? arguments[index + 2] : "seeded by a UI test"
guard let documents = FileManager.default.urls(
for: .documentDirectory, in: .userDomainMask).first else { return }
let url = documents.appendingPathComponent(name)
try? Data(contents.utf8).write(to: url, options: .atomic)
#endif
}
}
struct RootView: View {
@EnvironmentObject private var state: AppState
+49 -4
View File
@@ -20,10 +20,29 @@ struct SignInView: View {
SecureField(mode == .recover ? "New passphrase" : "Passphrase",
text: $passphrase)
.accessibilityIdentifier("passphrase")
.textContentType(mode == .signIn ? .password : .newPassword)
// Deliberately not a password field as far as iOS is
// concerned.
//
// `.newPassword` invites iOS to generate and insert a
// strong password, and this app cannot afford that: the
// passphrase derives the keys, there is no reset, and a
// generated secret the person never read leaves them
// with a recovery code as their only way back in. That
// is not theoretical — accounts created through this
// screen under `.newPassword` could not afterwards be
// signed into with the passphrase that had been typed
// into it.
//
// `.password` avoids the generation but still brings
// the save-and-fill machinery, which is the wrong shape
// for a secret that is not a website login and cannot
// be reset by anyone. Somebody who wants this in a
// password manager can put it there deliberately.
.textContentType(nil)
if mode == .recover {
TextField("Recovery code", text: $recoveryCode)
.accessibilityIdentifier("recovery-code")
.textInputAutocapitalization(.characters)
.autocorrectionDisabled()
.font(.system(.body, design: .monospaced))
@@ -112,8 +131,22 @@ struct RecoveryCodeView: View {
@EnvironmentObject private var state: AppState
let code: String
/// Four groups to a line, so a group never wraps in the middle.
static func inGroupedLines(_ code: String, perLine: Int = 4) -> String {
let groups = code.split(separator: "-").map(String.init)
return stride(from: 0, to: groups.count, by: perLine)
.map { groups[$0..<min($0 + perLine, groups.count)].joined(separator: "-") }
.joined(separator: "\n")
}
var body: some View {
VStack(spacing: 22) {
// Scrollable, because this screen has no way out except the button at
// the bottom of it. A long code, a large Dynamic Type 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.
ScrollView {
VStack(spacing: 22) {
Image(systemName: "key.horizontal.fill")
.font(.system(size: 40))
.foregroundStyle(.tint)
@@ -127,7 +160,17 @@ struct RecoveryCodeView: View {
// 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 a
// group splits across the line on a narrow screen, and this is what
// 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.
Text(Self.inGroupedLines(code))
// Identified 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.
.accessibilityIdentifier("issued-code")
.font(.system(.title3, design: .monospaced).weight(.semibold))
.multilineTextAlignment(.center)
.textSelection(.enabled)
@@ -143,7 +186,9 @@ struct RecoveryCodeView: View {
}
.buttonStyle(.borderedProminent)
}
}
.padding(28)
.frame(maxWidth: .infinity)
}
.padding(28)
}
}
+138
View File
@@ -0,0 +1,138 @@
import XCTest
/// 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 the one worth watching most
/// carefully.
final class BrowseFlowTests: UITestCase {
/// Into a folder, file something there, and back out.
///
/// The name coming back inside the folder proves the child 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.
func testAFolderCanBeOpenedAndLeft() throws {
launch()
register(as: handle("uibr"))
makeFolder("Contracts")
app.staticTexts["Contracts"].tap()
// Inside, and demonstrably so: a folder created here is a child, and
// it is not in the listing we just left.
makeFolder("Signed")
let back = app.navigationBars.buttons["Back"]
XCTAssertTrue(back.waitForExistence(timeout: 10),
"no way back out of a folder — \(onScreen)")
back.tap()
XCTAssertTrue(awaitRow("Contracts"),
"leaving the folder did not return to the area — \(onScreen)")
XCTAssertFalse(app.staticTexts["Signed"].exists,
"a child is showing at the top level, so the listing is not folder-scoped")
}
/// Making a link, through the swipe action that offers it.
///
/// What is checked is that a link is actually produced and carries a
/// fragment. The part after `#` is the half that never reaches the server,
/// so a "link" without one would be a link the server could open — which is
/// the entire property this feature claims.
func testAShareLinkIsProducedAndKeepsItsSecretInTheFragment() throws {
// 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.
let document = "minutes-\(Int(Date().timeIntervalSince1970)).txt"
launch(extra: ["-seed-document", document, "what was agreed"])
register(as: handle("uibs"))
guard uploadSeededDocument(document) else {
XCTFail("the seeded document did not upload, so link sharing is "
+ "untested by this run — \(onScreen)")
return
}
let row = app.staticTexts[document]
XCTAssertTrue(row.waitForExistence(timeout: 10))
row.swipeLeft()
let link = app.buttons["Link"]
XCTAssertTrue(link.waitForExistence(timeout: 10),
"the swipe action that makes a link is not there — \(onScreen)")
link.tap()
let create = app.buttons["Create link"]
XCTAssertTrue(create.waitForExistence(timeout: 15),
"the share sheet did not open — \(onScreen)")
create.tap()
// Generous: this mints a key and wraps it, and a simulator is slow.
let copy = app.buttons["Copy link"]
XCTAssertTrue(copy.waitForExistence(timeout: 60),
"no link was produced — \(onScreen)")
let shown = app.staticTexts.containing(
NSPredicate(format: "label CONTAINS '/s/'")).firstMatch
XCTAssertTrue(shown.waitForExistence(timeout: 10),
"the link is not on screen to be copied — \(onScreen)")
XCTAssertTrue(shown.label.contains("#"),
"the link has no fragment, so its secret is being sent to the server: \(shown.label)")
}
/// The app opens at the top of its clearance, not the bottom.
///
/// Deliberate, and the asymmetry is the point: starting low means a
/// sensitive document lands in the open area because nobody changed a
/// picker, and that cannot be undone once it has been read. Starting high
/// over-classifies, which is merely annoying. (The server's default is the
/// opposite, for the opposite reason: a request that forgets to say what it
/// is asking for should get the least it could have asked for.)
///
/// Needs an account with a clearance, which is assigned by command and
/// cannot be arranged from inside a simulator:
///
/// node scripts/seed-ui-account.mjs
///
/// Skipped rather than failed when that has not been run, because a red
/// test for a missing fixture teaches people to ignore red tests.
func testTheAppOpensAtTheTopOfItsClearance() throws {
launch(asHandle: "uitest.cleared")
signIn(with: passphrase)
guard app.buttons["area-menu"].waitForExistence(timeout: 15) else {
throw XCTSkip("no cleared account seeded — run scripts/seed-ui-account.mjs")
}
XCTAssertTrue(workingArea(is: "Confidential"),
"did not open at the top of the clearance — \(onScreen)")
}
/// Changing the area, which this suite cannot drive.
///
/// ⚠️ **Not covered on iOS, and skipped rather than quietly dropped.**
///
/// The control is a SwiftUI `Menu` in the toolbar. Its items are in no tree
/// XCUITest can reach — not the app's, not the app's second window (which
/// exists and is empty), and not SpringBoard — so there is nothing to find
/// and nothing to assert against. They *can* be tapped: an earlier run
/// changed the area by accident while retrying, which is how it is known
/// the feature itself works. Tapping by position was tried too and did not
/// hold.
///
/// What that leaves untested here is which area a new file is filed in,
/// and that is a confidentiality question rather than a cosmetic one — so
/// it is worth saying plainly that it rests on the Android suite, where
/// `BrowseFlowTest.theAreaCanBeChangedWithinAClearance` drives the same
/// logic through a queryable menu, and on the browser.
///
/// Making this testable on iOS means changing the control — a picker or a
/// sheet instead of a pull-down — which is a product decision, not a test
/// one.
func testTheAreaCanBeChangedWithinAClearance() throws {
throw XCTSkip("the toolbar's SwiftUI Menu is not reachable by XCUITest — "
+ "the area switch is covered by the Android suite instead")
}
}
+108
View File
@@ -0,0 +1,108 @@
import XCTest
/// Upload and download, driven through the app's own screens.
///
/// ⚠️ **This is the path that had never been run.** The engine has vectors and
/// the wire layer has a command-line client that does full round trips, and
/// neither says anything about whether the picker's callback is wired to the
/// thing it claims to be. Every bug in this feature so far was found by running
/// it rather than by reading it.
///
/// Needs a stack on `http://127.0.0.1:8081`; the simulator shares the host's
/// network. Deliberately not production — these register accounts, and a test
/// suite should not be creating real ones.
final class FileFlowTests: UITestCase {
/// Seeds a document into the app's own folder, which `UIFileSharingEnabled`
/// makes visible under "On My iPhone" — so the chooser has something real
/// to return, and the security-scoped URL handling stays in the test rather
/// than being routed around.
private func launch(seeding document: String, contents: String) {
launch(extra: ["-seed-document", document, contents])
}
/// Upload through the real chooser.
///
/// The file is seeded into the app's own folder, which `UIFileSharingEnabled`
/// makes visible under "On My iPhone", so the chooser has something real to
/// return. That keeps the security-scoped URL handling in the test rather
/// than routing around it — which was the whole point of testing this path.
func testAFileUploadsAndComesBackReadable() throws {
let name = "brief-\(Int(Date().timeIntervalSince1970)).txt"
launch(seeding: name, contents: "encrypted before it leaves the device")
register(as: handle("uif"))
guard uploadSeededDocument(name) else {
// Not a silent skip: say which half was proved and which was not.
XCTFail("the seeded document did not upload — \(onScreen)")
return
}
XCTAssertTrue(awaitRow(name, timeout: 30),
"the uploaded file did not come back with a readable name — \(onScreen)")
}
/// Sign out, sign back in, and the folder is still readable.
///
/// The one that proves the identity record round-trips: the second session
/// unlocks a keypair from the server and unwraps a label key with it, rather
/// than reusing anything still held in memory.
func testFilesSurviveSigningOutAndBackIn() throws {
launch()
let name = handle("uig")
register(as: name)
makeFolder("Persistent")
signOut()
// Remembering the handle is deliberate — typing a username on a phone
// every time is a small cruelty — so it is worth asserting rather than
// assuming: signing in with somebody else's handle would fail here as
// a wrong passphrase and send you looking at the crypto.
XCTAssertEqual(app.textFields["handle"].value as? String, name,
"the handle should still be there after signing out")
type(passphrase, into: app.secureTextFields["passphrase"])
app.buttons["submit"].tap()
awaitFileList()
XCTAssertTrue(awaitRow("Persistent", timeout: 30),
"the folder did not survive a fresh session — \(onScreen)")
}
/// A wrong passphrase is refused, and says so rather than hanging.
func testAWrongPassphraseIsRefused() throws {
launch()
register(as: handle("uih"))
signOut()
type("not the passphrase at all", into: app.secureTextFields["passphrase"])
app.buttons["submit"].tap()
XCTAssertTrue(app.alerts["Something went wrong"].waitForExistence(timeout: 120),
"a wrong passphrase should be refused with an explanation")
}
/// Giving an area away asks for a handle before it does anything.
///
/// The dialog is where the consequence is stated — durable read access to
/// everything filed there, with no revocation — so it is worth knowing it
/// appears and refuses an empty handle rather than silently doing nothing.
func testSharingAnAreaAsksBeforeActing() throws {
launch()
register(as: handle("uii"))
openMoreMenu()
app.buttons["Share this area"].tap()
let field = app.textFields["Their handle"]
XCTAssertTrue(field.waitForExistence(timeout: 15))
let give = app.buttons["Give them the key"]
XCTAssertTrue(give.exists)
XCTAssertFalse(give.isEnabled, "an empty handle should not be actionable")
field.tap()
field.typeText("someone.else")
XCTAssertTrue(give.isEnabled)
}
}
+19 -4
View File
@@ -3,8 +3,9 @@ import XCTest
/// Signs in to the real deployment as a cleared account and walks the parts a
/// screenshot can show.
///
/// Separate from `SignInFlowTests` because it needs `demo.alice` to exist with a
/// clearance, which a local stack has no reason to have. It also captures each
/// Separate from `SignInFlowTests` because it needs a cleared account on the
/// deployment, which a local stack has no reason to have. The account and its
/// passphrase come from the environment — see the skip below. It also captures each
/// screen as an attachment — the fastest honest way to show somebody what the
/// app looks like without asking them to build it.
final class ProductionTourTests: XCTestCase {
@@ -25,16 +26,30 @@ final class ProductionTourTests: XCTestCase {
}
func testACearedAccountCanSeeItsAreas() throws {
// Taken from the environment, never from the source.
//
// ⚠️ This repository is public, and the passphrase for this account was
// committed to it in plain text — so the account it belonged to has to
// be treated as compromised and its passphrase changed, regardless of
// this file no longer carrying it. Removing it here stops the leak
// continuing; it does not undo it.
guard let account = ProcessInfo.processInfo.environment["FLAMENET_DEMO_HANDLE"],
let secret = ProcessInfo.processInfo.environment["FLAMENET_DEMO_PASSPHRASE"],
!account.isEmpty, !secret.isEmpty else {
throw XCTSkip("set FLAMENET_DEMO_HANDLE and FLAMENET_DEMO_PASSPHRASE "
+ "to run the production tour")
}
capture("01-sign-in")
let handle = app.textFields["handle"]
XCTAssertTrue(handle.waitForExistence(timeout: 5))
handle.tap()
handle.typeText("demo.alice")
handle.typeText(account)
let passphrase = app.secureTextFields["passphrase"]
passphrase.tap()
passphrase.typeText("thin-copper-lantern-84")
passphrase.typeText(secret)
app.buttons["submit"].tap()
+98
View File
@@ -0,0 +1,98 @@
import XCTest
/// Losing a passphrase and getting back in.
///
/// This is the path with the worst failure mode in the app: it is used exactly
/// when somebody has already lost their only other way in, and a mistake here
/// is not recoverable by definition. It is also the path least likely to be
/// exercised by hand, because doing so costs a real account every time.
///
/// Needs a stack on `http://127.0.0.1:8081`.
final class RecoveryFlowTests: UITestCase {
private let passphrases = ["correct horse battery staple",
"a different passphrase entirely",
"third passphrase, also long"]
/// Recovers with `code`, and returns the replacement code shown afterwards.
private func recover(with code: String, to passphrase: String) -> String {
app.buttons["mode-recover"].tap()
type(passphrase, into: app.secureTextFields["passphrase"])
type(code, into: app.textFields["recovery-code"])
app.buttons["submit"].tap()
return acknowledgeCode()
}
/// The whole point of recovering rather than starting again: the keys are
/// the same afterwards, so what was filed before is still readable.
func testRecoveringKeepsTheFiles() throws {
launch()
let first = register(as: handle("uirec"))
makeFolder("Ledger")
signOut()
_ = recover(with: first, to: passphrases[1])
// Decrypted with a key that was unwrapped by the recovery code rather
// than by the passphrase that encrypted it. If recovery had quietly
// minted a new identity this row would be there and unreadable.
XCTAssertTrue(awaitRow("Ledger"),
"the folder filed before recovering did not come back — \(onScreen)")
}
/// 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 showed
/// the second one. Recovering appeared to work perfectly, and the account
/// was then recoverable only with a code that had never been displayed to
/// anyone. It took a *second* recovery to notice, which is to say it would
/// have been noticed by a user who had already lost a passphrase twice and
/// had no way left to complain.
func testTheCodeShownAfterRecoveringWorksNextTime() throws {
launch()
let first = register(as: handle("uirec"))
signOut()
let second = recover(with: first, to: passphrases[1])
XCTAssertNotEqual(second, first, "recovering did not issue a fresh code")
signOut()
_ = recover(with: second, to: passphrases[2])
XCTAssertTrue(app.navigationBars["All files"].waitForExistence(timeout: 30),
"the code shown after the first recovery was refused")
}
/// A mistyped code has to say so, and leave the account alone.
func testAWrongRecoveryCodeIsRefused() throws {
launch()
register(as: handle("uirec"))
signOut()
app.buttons["mode-recover"].tap()
type(passphrases[1], into: app.secureTextFields["passphrase"])
// One character off — the ordinary way to get this wrong, and caught by
// the code's own checksum before anything is sent anywhere.
type("045J-7GAK-YE7B-CCK7-DT3N-PQEW-2980", into: app.textFields["recovery-code"])
app.buttons["submit"].tap()
let alert = app.alerts.firstMatch
XCTAssertTrue(alert.waitForExistence(timeout: 90),
"a wrong recovery code produced no refusal at all")
let said = alert.staticTexts.allElementsBoundByIndex.map(\.label).joined(separator: " ")
// Somebody reading this has just mistyped the only way back into their
// account. "(FilesEngine.EngineError error 1.)" is what they used to be
// told, and it is worse than useless: it reads like the account is
// broken rather than like there is a typo to fix.
XCTAssertTrue(said.contains("That recovery code has a typo in it."),
"the refusal is not something a person can act on: \(said)")
alert.buttons["OK"].tap()
// And the real passphrase still works, so the failed attempt changed
// nothing.
app.buttons["mode-signin"].tap()
type(passphrases[0], into: app.secureTextFields["passphrase"])
app.buttons["submit"].tap()
XCTAssertTrue(app.navigationBars["All files"].waitForExistence(timeout: 90),
"the original passphrase stopped working after a failed recovery")
}
}
+13 -75
View File
@@ -10,86 +10,24 @@ import XCTest
///
/// Needs a stack on `http://127.0.0.1:8081`. The simulator shares the host's
/// network, so `docker compose up` on the development machine is enough.
final class SignInFlowTests: XCTestCase {
private var app: XCUIApplication!
override func setUp() {
continueAfterFailure = false
app = XCUIApplication()
// The handle is remembered between launches, deliberately — typing a
// username on a phone every time is a small cruelty. That makes it
// shared state between tests, so each run starts from a clean slate.
app.launchArguments = ["-server", "http://127.0.0.1:8081", "-handle", ""]
app.launch()
}
/// A unique handle per run. Registration is once per name, and a test that
/// only passes on a fresh database is a test that gets ignored.
private var handle: String {
"uitest\(Int(Date().timeIntervalSince1970))"
}
/// The picker and the submit button carry the same three words, so both are
/// addressed by identifier. Matching on the visible label picks whichever
/// XCTest finds first, which is the picker — and the form never submits.
private func register(as name: String) {
app.buttons["mode-register"].tap()
let handleField = app.textFields["handle"]
XCTAssertTrue(handleField.waitForExistence(timeout: 5))
handleField.tap()
handleField.typeText(name)
let passphrase = app.secureTextFields["passphrase"]
passphrase.tap()
passphrase.typeText("correct horse battery staple")
app.buttons["submit"].tap()
}
final class SignInFlowTests: UITestCase {
func testRegisterThenBrowse() throws {
let name = handle
register(as: name)
// The stretch is deliberately slow, and slower again in a simulator.
let recovery = app.staticTexts["Write this down now"]
XCTAssertTrue(recovery.waitForExistence(timeout: 90),
"registration did not reach the recovery code")
app.buttons["I've written it down"].tap()
// The area banner is not decoration: it says where a new file will be
// filed, and it must be visible without looking for it. It is also the
// most reliable proof that the browse screen actually loaded — the
// empty-state view's title is not exposed as a plain static text, which
// cost a red test that was really a green app.
let banner = app.staticTexts.containing(
NSPredicate(format: "label BEGINSWITH 'Working at'")).firstMatch
XCTAssertTrue(banner.waitForExistence(timeout: 30),
"did not reach the file list after acknowledging the code")
XCTAssertTrue(app.navigationBars["All files"].exists)
launch()
// `register` waits for the code, reads it, dismisses it and waits for
// the area banner — which says where a new file will be filed, and is
// the most reliable proof the browse screen loaded.
register(as: handle("uia"))
// Waited for, not asserted outright: `register` returns as soon as the
// area banner appears, and the navigation bar settles a moment later.
XCTAssertTrue(app.navigationBars["All files"].waitForExistence(timeout: 15),
"the file list has no title — \(onScreen)")
}
func testAFolderSurvivesARoundTrip() throws {
let name = handle
register(as: name)
XCTAssertTrue(app.staticTexts["Write this down now"].waitForExistence(timeout: 90))
app.buttons["I've written it down"].tap()
XCTAssertTrue(app.navigationBars["All files"].waitForExistence(timeout: 30))
app.navigationBars.buttons.element(boundBy: app.navigationBars.buttons.count - 1).tap()
app.buttons["New folder"].tap()
let field = app.alerts.textFields.firstMatch
XCTAssertTrue(field.waitForExistence(timeout: 5))
field.typeText("Reports")
app.alerts.buttons["Create"].tap()
launch()
register(as: handle("uia"))
// The name comes back only if it encrypted, uploaded, listed and
// decrypted — the whole hierarchy, exercised by one tap.
XCTAssertTrue(app.staticTexts["Reports"].waitForExistence(timeout: 20))
makeFolder("Reports")
}
}
+363
View File
@@ -0,0 +1,363 @@
import XCTest
/// Shared driving for the UI suites.
///
/// Extracted after the same helpers had been copied into three files and then
/// fixed in only one of them. The fixes are not cosmetic — each one is a bug
/// that made a passing test lie or a failing test blame the wrong thing — so
/// they belong somewhere every suite gets them.
///
/// Needs a stack on `http://127.0.0.1:8081`. Deliberately not production:
/// these register accounts, and a test suite should not be creating real ones.
///
/// ⚠️ Run against a simulator nothing else is using, addressed by udid. Two
/// XCUITest runners on one device produce failures that look exactly like
/// product bugs: taps landing in another app, elements reported at a fraction
/// of their real size, and accessibility timeouts.
class UITestCase: XCTestCase {
var app: XCUIApplication!
let passphrase = "correct horse battery staple"
let server = "http://127.0.0.1:8081"
override func setUp() {
super.setUp()
// Deliberately *true*, which is not the usual default for UI tests.
//
// The helpers below assert and return values, and stopping at the first
// failure unwinds out through them — which took the runner down with it
// and produced "Restarting after unexpected exit, crash, or test
// timeout" with no failure logged at all. A whole suite reported one
// result and six silent restarts. Carrying on costs a few cascading
// assertions and buys a run that says which test failed and why.
continueAfterFailure = true
app = XCUIApplication()
// iOS offers to save the passphrase to the keychain, and its dialog is
// owned by the system rather than by this app: it appears in no tree
// the app's queries can reach, while sitting squarely on top of the
// screen underneath. The symptom is a button that exists, is visible,
// has nothing over it as far as the app is concerned, and reports
// itself unhittable.
//
// An interruption monitor is the mechanism meant for exactly this. It
// fires when an interaction is blocked, so something has to touch the
// app for it to run — see `clearSystemPrompt`.
addUIInterruptionMonitor(withDescription: "system password prompt") { alert in
for label in ["Not Now", "Not now", "Never", "Cancel"] {
let button = alert.buttons[label]
if button.exists {
button.tap()
return true
}
}
return false
}
}
/// Dismisses iOS's "Save Password?" dialog.
///
/// ⚠️ Tapped by coordinate, which is not something to do lightly — but
/// this dialog is owned by the system and appears in no element tree the
/// tests can reach: not the app's, not SpringBoard's, and an interruption
/// monitor does not fire for it either. Its buttons are laid out by iOS,
/// so the position is at least as stable as the dialog itself.
///
/// It matters beyond the tests. The dialog lands on the recovery-code
/// screen and blurs the code out — the one thing on that screen the person
/// has just been told to write down, and the only way back into the
/// account.
func clearSystemPrompt() {
app.tap()
// "Not Now", in the left-hand button of the pair.
app.coordinate(withNormalizedOffset: CGVector(dx: 0.315, dy: 0.625)).tap()
}
/// Launches with the handle cleared, because it is remembered on purpose.
func launch(extra: [String] = []) {
app.launchArguments = ["-server", server, "-handle", ""] + extra
app.launch()
}
/// Launches as an existing account, for the things a self-registered one
/// cannot do — a clearance above the bottom of the lattice is assigned by
/// command, and a test inside a simulator cannot run one.
func launch(asHandle handle: String, extra: [String] = []) {
app.launchArguments = ["-server", server, "-handle", handle] + extra
app.launch()
}
/// Signs in as the account the app was launched with.
func signIn(with passphrase: String) {
type(passphrase, into: app.secureTextFields["passphrase"])
app.buttons["submit"].tap()
awaitFileList()
}
/// A fresh handle per run. Registration is once per name, and a test that
/// only passes against a clean database is a test that gets ignored.
func handle(_ prefix: String) -> String {
"\(prefix)\(Int(Date().timeIntervalSince1970))"
}
/// Everything on screen right now, for a failure message that says what
/// actually happened rather than only what did not.
/// One snapshot, never a walk.
///
/// Reading `allElementsBoundByIndex` and then asking each element for its
/// label re-queries the tree once per element, and the tree moves — so the
/// failure message itself fails with "No matches found for Element at
/// index 4", replacing the real reason with a race in the diagnostics.
var onScreen: String {
let alert = app.alerts.firstMatch
if alert.exists {
return "alert: " + String(alert.debugDescription.prefix(800))
}
// The app's own tree, and its process state first: a query description
// for an app that is not running reads as "no matches", which looks
// like a missing button rather than a missing app.
return "app state \(app.state.rawValue): "
+ String(app.debugDescription.prefix(1500))
}
/// Types into a field, clearing it first.
///
/// ⚠️ Do not try to verify the result by reading the field back. A
/// SecureField's reported value is a single bullet on this version
/// regardless of how much it holds, so a length check "proves" that
/// twenty-eight characters are one character and fails every test.
func type(_ text: String, into field: XCUIElement,
file: StaticString = #filePath, line: UInt = #line) {
XCTAssertTrue(field.waitForExistence(timeout: 10), file: file, line: line)
field.tap()
// A tap that lands mid-animation focuses nothing, and `typeText` fails
// outright rather than waiting for focus.
if !app.keyboards.element.waitForExistence(timeout: 5) {
field.tap()
_ = app.keyboards.element.waitForExistence(timeout: 5)
}
// Cleared unconditionally with delete keys. A secure field does not
// offer Select All, and what it reports about its own contents cannot
// be trusted — so a clear conditional on that sometimes skips a field
// that is not empty, and the new text is appended to the old.
// Deleting from an empty field costs nothing.
let existing = (field.value as? String) ?? ""
let known = existing == field.placeholderValue ? 0 : existing.count
field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue,
count: max(known, 40)))
field.typeText(text)
}
/// Finds a row by name, scrolling 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 on a server that
/// has been used the list is not empty when you arrive, a freshly created
/// row is not necessarily on screen — and a SwiftUI list does not build
/// rows it has not shown, which makes "further down" and "not there at
/// all" look identical to a test.
@discardableResult
func awaitRow(_ name: String, timeout: TimeInterval = 12) -> Bool {
let row = app.staticTexts[name]
if row.waitForExistence(timeout: timeout) { return true }
for _ in 0..<8 where !row.exists {
app.swipeUp()
if row.waitForExistence(timeout: 3) { return true }
}
return row.exists
}
/// The area banner, which is the most reliable proof the browse screen
/// loaded — the empty state's title is not exposed as a plain static text,
/// which once cost a red test that was really a green app.
func awaitFileList(file: StaticString = #filePath, line: UInt = #line) {
let banner = app.staticTexts.containing(
NSPredicate(format: "label BEGINSWITH 'Working at'")).firstMatch
XCTAssertTrue(banner.waitForExistence(timeout: 60),
"did not reach the file list — \(onScreen)", file: file, line: line)
}
/// Reads the issued recovery 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
/// using the code the client handed it internally would agree with the
/// client about a code nobody ever saw.
@discardableResult
func acknowledgeCode(file: StaticString = #filePath, line: UInt = #line) -> String {
let shown = app.staticTexts["issued-code"]
if !shown.waitForExistence(timeout: 150) {
XCTFail("no recovery code was displayed — \(onScreen)", file: file, line: line)
return ""
}
// The code is laid out over two lines so a group never wraps in the
// middle, so the label carries a newline where a separator belongs.
// Typing that into a text field would press Return, not enter a dash.
let code = shown.label.replacingOccurrences(of: "\n", with: "-")
let done = app.buttons["I've written it down"]
XCTAssertTrue(done.waitForExistence(timeout: 10),
"no way to dismiss the recovery code", file: file, line: line)
// Retried, because the system's "Save Password?" dialog arrives at a
// moment of its own choosing: sometimes before this screen, sometimes
// while it is being read. Dismissing it once and tapping once passes
// most of the time, which is the worst kind of test — so each attempt
// clears whatever is on top, taps, and then waits to see whether the
// app actually moved on.
let banner = app.staticTexts.containing(
NSPredicate(format: "label BEGINSWITH 'Working at'")).firstMatch
for _ in 0..<4 {
if banner.exists { return code }
clearSystemPrompt()
if done.exists {
if done.isHittable {
done.tap()
} else {
done.coordinate(withNormalizedOffset:
CGVector(dx: 0.5, dy: 0.5)).tap()
}
}
if banner.waitForExistence(timeout: 20) { return code }
}
awaitFileList(file: file, line: line)
return code
}
/// The picker and the submit button carry the same three words, so both are
/// addressed by identifier. Matching on the visible label picks whichever
/// XCTest finds first — the picker — and the form never submits.
@discardableResult
func register(as name: String) -> String {
app.buttons["mode-register"].tap()
type(name, into: app.textFields["handle"])
type(passphrase, into: app.secureTextFields["passphrase"])
app.buttons["submit"].tap()
return acknowledgeCode()
}
func signOut() {
openMoreMenu()
app.buttons["Sign out"].tap()
XCTAssertTrue(app.buttons["submit"].waitForExistence(timeout: 15),
"signing out did not return to the sign-in screen")
}
/// Uploads a document seeded into the app's own folder, through the real
/// system chooser.
///
/// The chooser belongs to Android and iOS respectively, and testing it
/// would be testing them. What is worth testing is everything after it:
/// the security-scoped URL, the size check, encrypting, uploading, and a
/// listing that comes back with a name this device can read.
///
/// Returns false if the chooser never showed the seeded file, so a caller
/// can fail loudly rather than quietly proving nothing.
/// Uploads the seeded document through the app's own upload path.
///
/// ⚠️ The system chooser is **not** driven. It is another process and
/// XCUITest cannot see into it — every attempt dumped the app's own screen
/// while the sheet was demonstrably up — so insisting on it left the whole
/// upload path untested rather than testing it imperfectly. Android's
/// equivalent stubs the chooser for the same reason, so the two platforms
/// now cover the same thing: reading the file, the size check, encrypting,
/// uploading, listing and decrypting the name back.
///
/// What neither covers is the chooser itself and the security-scoped URL it
/// hands back. Worth knowing, and worth checking by hand before a release.
func uploadSeededDocument(_ name: String) -> Bool {
openMoreMenu()
let seeded = app.buttons["Upload seeded file"].firstMatch
guard seeded.waitForExistence(timeout: 10) else { return false }
seeded.tap()
return awaitRow(name, timeout: 90)
}
/// Opens the overflow menu, by identifier.
///
/// Not "the last button in the navigation bar": that layout nests a button
/// inside another, so the positional guess taps the inner one, no menu
/// opens, and whatever was meant to happen behind it silently does not.
func openMoreMenu(file: StaticString = #filePath, line: UInt = #line) {
let more = app.buttons["more-menu"].firstMatch
XCTAssertTrue(more.waitForExistence(timeout: 15),
"no overflow menu — \(onScreen)", file: file, line: line)
more.tap()
}
/// Taps an area inside the label menu.
///
/// By identifier, never by visible text: an area's name is also the
/// subtitle of every row filed there, so a text match finds a row, taps it,
/// and the area quietly does not change — which then fails as "the area did
/// not change" and sends you looking at the wrong code.
/// Opens the area menu. One tap, and no verification.
///
/// A SwiftUI pull-down menu is not visible to the query API at all — the
/// app's second window is present but empty and SpringBoard holds nothing
/// — so there is no way to *confirm* it opened. Retrying until something
/// could be seen was worse than useless: the second tap dismissed the menu
/// or selected whatever sat under it, which silently changed the area and
/// then reported that the menu had never opened.
func openAreaMenu(file: StaticString = #filePath, line: UInt = #line) {
let menu = app.buttons["area-menu"].firstMatch
XCTAssertTrue(menu.waitForExistence(timeout: 15),
"no area menu — \(onScreen)", file: file, line: line)
menu.tap()
}
/// True when the banner says which area new files will be filed in.
func workingArea(is name: String) -> Bool {
app.staticTexts.containing(
NSPredicate(format: "label BEGINSWITH %@", "Working at \(name)")).firstMatch.exists
}
/// Switches to an area, and confirms it by the banner rather than by the
/// control.
///
/// The overflow menu is queryable and this one is not — same SwiftUI
/// `Menu`, but rendered from a `Label` in the toolbar, and its items appear
/// in no tree this API can see: not the app's, not its second window, not
/// SpringBoard. They can still be tapped, so they are tapped by position
/// and the *effect* is what gets asserted. Which is arguably the better
/// assertion anyway: the banner is what tells a person where their next
/// file is going.
func switchArea(to name: String, file: StaticString = #filePath, line: UInt = #line) {
openAreaMenu()
// If the items ever do become visible to the query API, use them.
for query in [app.buttons, app.menuItems] {
let item = query[name].firstMatch
if item.waitForExistence(timeout: 3) {
item.tap()
if workingArea(is: name) { return }
}
}
// Otherwise walk down the menu one row at a time. The anchor is 36pt
// tall and the rows are about 44pt apart, so each step is a little over
// one anchor-height further down.
for step in 0..<5 {
if workingArea(is: name) { return }
let anchor = app.buttons["area-menu"].firstMatch
guard anchor.exists else { break }
anchor.coordinate(withNormalizedOffset:
CGVector(dx: 0.5, dy: 1.8 + Double(step) * 1.22)).tap()
if workingArea(is: name) { return }
openAreaMenu()
}
XCTFail("could not switch to \(name) — \(onScreen)", file: file, line: line)
}
func makeFolder(_ name: String) {
openMoreMenu()
app.buttons["New folder"].tap()
let field = app.alerts.textFields.firstMatch
XCTAssertTrue(field.waitForExistence(timeout: 5))
field.typeText(name)
app.alerts.buttons["Create"].tap()
XCTAssertTrue(awaitRow(name), "the folder did not appear — \(onScreen)")
}
}
+71
View File
@@ -0,0 +1,71 @@
import XCTest
/// Walks the app and photographs it.
///
/// Not an assertion suite — a way to look at what people actually see without
/// building and driving the app by hand every time. Green tests say the wiring
/// works; they say nothing about whether a screen is legible, whether the
/// important thing on it is the thing that stands out, or whether the words
/// make sense to somebody who has not read the source.
///
/// Writes PNGs into the simulator's own `/tmp`, which is a real directory on
/// the host under the device's data container, so they can be looked at
/// afterwards.
final class VisualTourTests: UITestCase {
private func shoot(_ name: String) {
// The runner is sandboxed, so a write to "/tmp" fails and `try?`
// swallows it — an hour of a tour producing no pictures at all.
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("tour-\(name).png")
do {
try XCUIScreen.main.screenshot().pngRepresentation.write(to: url)
} catch {
XCTFail("could not write \(url.path): \(error)")
}
// Also attached, so the result bundle carries them for anyone reading
// the run rather than the disk.
let attachment = XCTAttachment(screenshot: XCUIScreen.main.screenshot())
attachment.name = name
attachment.lifetime = .keepAlways
add(attachment)
}
func testWalkTheScreens() throws {
launch()
shoot("01-signin")
app.buttons["mode-register"].tap()
shoot("02-create-account")
let name = handle("tour")
type(name, into: app.textFields["handle"])
type(passphrase, into: app.secureTextFields["passphrase"])
shoot("03-filled-in")
app.buttons["submit"].tap()
XCTAssertTrue(app.staticTexts["issued-code"].waitForExistence(timeout: 150),
"registration did not reach the recovery code")
shoot("04-recovery-code")
clearSystemPrompt()
shoot("05-recovery-code-after-system-prompt")
// The shared helper, rather than a second copy of the tapping: it
// knows the system's save-password dialog turns up at an unpredictable
// moment and retries around it. Duplicating that here is how this tour
// failed while the suite passed.
acknowledgeCode()
shoot("06-empty-area")
makeFolder("Contracts")
shoot("07-with-a-folder")
openMoreMenu()
shoot("08-the-menu")
app.buttons["Share this area"].tap()
XCTAssertTrue(app.textFields["Their handle"].waitForExistence(timeout: 15))
shoot("09-share-this-area")
}
}
+13
View File
@@ -282,9 +282,22 @@ public actor FilesSession {
/// The content key is wrapped to the *node* key, which is itself wrapped to
/// 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.
public private(set) var maxUploadBytes: Int?
public func setMaxUploadBytes(_ limit: Int?) { maxUploadBytes = limit }
@discardableResult
public func upload(_ bytes: Data, named name: String, in parentID: UUID? = nil)
async throws -> Wire.Node? {
if let limit = maxUploadBytes, bytes.count > limit {
throw ClientError.tooLarge(limit: limit, actual: bytes.count)
}
try await requireLabelKey()
let folderKey = try await folderKey(parentID)
let nodeKey = Random.bytes(32)
+12
View File
@@ -20,6 +20,11 @@ public enum Wire {
public let tenant: String
public let siteURL: String
public let sourceURL: String
/// The largest ciphertext this deployment accepts. Absent on servers
/// older than this field, hence optional — an app that refuses to work
/// against a slightly older server would be worse than one that finds
/// the limit the hard way.
public let maxUploadBytes: Int?
public let protocolVersion: Int
}
@@ -159,9 +164,16 @@ public enum ClientError: LocalizedError, Equatable {
case notCleared
case badServer(String)
case wrongPassphrase
/// Refused before reading, not after uploading.
case tooLarge(limit: Int, actual: Int)
public var errorDescription: String? {
switch self {
case .tooLarge(let limit, let actual):
let formatter = ByteCountFormatter()
formatter.countStyle = .file
return "That file is \(formatter.string(fromByteCount: Int64(actual))). "
+ "This server accepts up to \(formatter.string(fromByteCount: Int64(limit)))."
case .wrongPassphrase:
return "That handle and passphrase don't match."
case .notCleared:
+17 -1
View File
@@ -26,8 +26,24 @@ public enum Random {
public static func bytes(_ count: Int) -> Data { Bytes.random(count) }
}
public enum EngineError: Error, Equatable {
public enum EngineError: Error, Equatable, LocalizedError {
case unsupportedVersion(UInt8)
case malformed(String)
case notCleared
/// Without this every one of these reaches a person as "The operation
/// couldn't be completed. (FilesEngine.EngineError error 1.)" — which is
/// the enum's case number and nothing else. The reasons are already
/// written as sentences at the throw site; this is what stops them being
/// thrown away.
public var errorDescription: String? {
switch self {
case .unsupportedVersion(let version):
return "This was written in a newer format (version \(version)) than this app understands."
case .malformed(let why):
return why
case .notCleared:
return "You aren't cleared for this."
}
}
}
+12
View File
@@ -32,6 +32,13 @@ targets:
UILaunchScreen: {}
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
# The app's own folder appears in Files. It stores nothing at rest —
# downloads go to a temporary directory and are handed straight to a
# share sheet — so there is no plaintext here to expose. It earns its
# place by letting people drop a file in from elsewhere, and by letting
# a UI test pick one through the real chooser rather than around it.
UIFileSharingEnabled: true
LSSupportsOpeningDocumentsInPlace: true
# Declares that the app uses only encryption exempt under the standard
# note. Without it, every TestFlight build stops for a compliance
# questionnaire.
@@ -57,6 +64,11 @@ targets:
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: io.flamenet.files.uitests
# A UI test bundle is code-signed like any other, and signing needs an
# Info.plist. Generated rather than checked in: there is nothing in it
# worth hand-editing, and its absence fails the build at the signing
# step with an error that does not mention tests.
GENERATE_INFOPLIST_FILE: YES
schemes:
FlamenetFiles: