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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/rustgis-mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,8 @@ own was used outside the area) is said, as a later package from the same phone r
| GeoLibre tools, GDAL formats, DuckDB | Not available: a phone can't run their programs. `rustgis_data::RUNS_PROGRAMS` is false on Android and iOS, so no program is looked for, and each place they would appear says so: a file read through GDAL or a DuckDB database is refused with the reason (convert it on a computer), the SQL pane says why it can't query, and the Geoprocessing pane shows a card in place of the GeoLibre tools. Add Data's Database… stays: its PostGIS, MySQL and SQL Server connections need no program. The app is built without the engine's `geolibre` feature |
| Memory limits | The app tells the engine what Android allows (`rustgis_data::memory::set_phone`): `ActivityManager.MemoryInfo`'s `totalMem` in place of the computer's memory, and `availMem` less `threshold` as what is free, asked again for each job. (`getMemoryClass` bounds only the Java heap; the engine's memory is native.) Where the browser's floor is lower than the desktop's, the phone takes it; the Undo budget is planned from what is free at start, and the threads' scratch memory is the browser's. On a low-memory warning the app drops the tile and drawing caches: `onTrimMemory` and `onLowMemory` through Android 13, and, as Android 14 and later send an app in use neither, `MemoryInfo.lowMemory`, asked every five seconds while the app is in sight (an idle window wakes that often to ask) |
| Recovery copies | The first foreground edit submits a recovery copy in app-private storage immediately. Edits within two seconds of a submission are grouped into a copy due at the end of that interval. When the exit hook runs, it submits the latest edit immediately and gives the writer up to two seconds to finish. Suspending or destroying the Android activity can skip this hook, so edits still waiting to be submitted can be lost. The next launch offers the last complete copy, if one exists. |
| Preferences, the keychain | Not wired up yet |
| Preferences | `prefs.json` in the app's settings folder, as on the desktop (`rustgis_engine::prefs`) |
| Secrets | `Services::secrets` is `src/secrets.rs`: the Java half (`SecretVault.java`) encrypts each secret with AES-GCM under a key the Android Keystore makes once and never lets out, bound to its account name, and keeps it in a file of its own in the app's no-backup folder, written whole and renamed into place, so a failed save leaves the secret as it was. Nothing is kept unencrypted: when the keystore can't be used, a secret lasts for the session and the app says so. Uninstalling the app removes both. On iOS there is no store yet: the keychain crate's Apple store needs its `protected` feature there |
| Soft keyboard | It opens for a text field, and the touch interface keeps the field above it. The Capture form's fields are typed into Android's own text box (see Typing above), with suggestions, composing, paste and dictation. Fields the desktop interface draws still get `NativeActivity`'s poor text input (no suggestions, no composing) |

## What phase 0 found
Expand Down
16 changes: 16 additions & 0 deletions apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,22 @@ public void copyText(final String text) {
});
}

/**
* The Rust side's secret store (src/secrets.rs), kept by SecretVault: called on any of its
* threads, each answering with a line ("ok", "none", "unavailable" or "failed").
*/
public String loadSecret(String account) {
return SecretVault.load(this, account);
}

public String saveSecret(String account, String value) {
return SecretVault.save(this, account, value);
}

public String deleteSecret(String account) {
return SecretVault.delete(this, account);
}

/** Asks the user for files with the system's picker; each arrives as a "picked" event. */
public void pick(final String purpose) {
runOnUiThread(() -> {
Expand Down
204 changes: 204 additions & 0 deletions apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
package org.rustgis.mobile;

/**
* Secrets kept for the Rust side's secret store (src/secrets.rs): each one encrypted with
* AES-GCM under a key in the Android Keystore, made once and never leaving it, and kept in the
* file of its own as "1.<nonce>.<ciphertext>" (Base64), the account name bound to it. The files
* are in the app's no-backup folder, which Android's backups leave out (the key couldn't open
* them elsewhere), named by a SHA-256 of the account. A new entry is written whole beside the old
* and renamed over it, so a failed save or removal leaves the entry as it was, and is said as a
* failure. Nothing is kept unencrypted: when the keystore can't be used, the Rust side says so
* and the secret lasts for the session. An entry a newer RustGIS wrote (a version above 1) is
* neither read, written over nor removed.
*
* Each call answers with a line: "ok" (with the secret after a tab, for a load that found one),
* "none" (a load that found none), "unavailable" with the system's reason after a tab, or
* "failed" with a code after a tab (newer, unwritten, damaged, no-key, undecryptable, error) and
* the system's reason, if any, after another: the Rust side words them (src/vaultanswer.rs).
* Called on any thread, one call at a time.
*/
final class SecretVault {
/** The keystore's name for the one key. */
private static final String KEY = "rustgis-secrets";
/** The folder, in the app's no-backup folder, the encrypted secrets are kept in. */
private static final String FOLDER = "rustgis-secrets";
/** The version of the entries this one writes. */
private static final int VERSION = 1;
private static final String CIPHER = "AES/GCM/NoPadding";
private static final int TAG_BITS = 128;
private static final String NEWER = "failed\tnewer";
private static final String UNWRITTEN = "failed\tunwritten";

private SecretVault() {}

static synchronized String load(android.content.Context context, String account) {
try {
String kept = kept(file(context, account));
if (kept == null) {
return "none";
}
int version = version(kept);
if (version > VERSION) {
return NEWER;
}
String[] parts = kept.split("\\.", -1);
if (version != VERSION || parts.length != 3) {
return "failed\tdamaged";
}
javax.crypto.SecretKey key = key(false);
if (key == null) {
// Restored to another device, say: the key never leaves the one it was made on.
return "failed\tno-key";
}
byte[] iv = android.util.Base64.decode(parts[1], android.util.Base64.NO_WRAP);
byte[] sealed = android.util.Base64.decode(parts[2], android.util.Base64.NO_WRAP);
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER);
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new javax.crypto.spec.GCMParameterSpec(TAG_BITS, iv));
cipher.updateAAD(account.getBytes(java.nio.charset.StandardCharsets.UTF_8));
byte[] plain = cipher.doFinal(sealed);
return "ok\t" + new String(plain, java.nio.charset.StandardCharsets.UTF_8);
} catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException
| java.security.ProviderException e) {
return "unavailable\t" + reason(e);
} catch (java.security.GeneralSecurityException | IllegalArgumentException e) {
// A damaged entry, or one sealed with a key the keystore no longer has.
return "failed\tundecryptable\t" + reason(e);
} catch (RuntimeException e) {
return "failed\terror\t" + reason(e);
}
}

static synchronized String save(android.content.Context context, String account, String value) {
try {
java.io.File file = file(context, account);
if (version(kept(file)) > VERSION) {
return NEWER;
}
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER);
// The keystore chooses the nonce, a new one for each secret.
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key(true));
// Bound to its account: an entry copied under another account doesn't decrypt.
cipher.updateAAD(account.getBytes(java.nio.charset.StandardCharsets.UTF_8));
byte[] sealed = cipher.doFinal(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
String kept = VERSION + "." + android.util.Base64.encodeToString(cipher.getIV(), android.util.Base64.NO_WRAP) + "."
+ android.util.Base64.encodeToString(sealed, android.util.Base64.NO_WRAP);
return write(file, kept);
} catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException
| java.security.ProviderException e) {
return "unavailable\t" + reason(e);
} catch (java.security.GeneralSecurityException | RuntimeException e) {
return "failed\terror\t" + reason(e);
}
}

static synchronized String delete(android.content.Context context, String account) {
try {
java.io.File file = file(context, account);
String before = kept(file);
if (version(before) > VERSION) {
return NEWER;
}
return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing a secret leaves a <hash>.part file behind when a save was interrupted between writing the .part and renaming it (a crash or power cut). write deletes its .part only when it throws, and delete never looks for one. The stale file holds the ciphertext of a secret the user has since removed, so "unticking Remember deletes the entry" isn't quite true after such a crash. The file is encrypted under the same keystore key, so the exposure is small, but removing the .part with the entry closes it.

Suggested change
return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN;
new java.io.File(file.getParentFile(), file.getName() + ".part").delete();
return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN;

Confidence: about 70% that this is reachable in practice, and low impact.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: the leftover holds only ciphertext under a key the keystore keeps, and the next save of that account replaces it.

} catch (java.io.IOException | RuntimeException e) {
return "failed\terror\t" + reason(e);
}
}

/**
* Writes the account's entry whole to a file beside its own and renames it over it, so the
* entry is either the new one or, after a failure, still the one before.
*/
private static String write(java.io.File file, String kept) {
java.io.File folder = file.getParentFile();
java.io.File part = new java.io.File(folder, file.getName() + ".part");
try {
if (folder == null || !(folder.isDirectory() || folder.mkdirs())) {
return UNWRITTEN;
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(part)) {
out.write(kept.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
// On the disk before the rename makes it the entry.
out.getFD().sync();
}
java.nio.file.Files.move(part.toPath(), file.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE);
// The rename on the disk too. It is made whatever this comes to: only a power cut
// before Android writes the folder could still undo it.
try (java.nio.channels.FileChannel dir =
java.nio.channels.FileChannel.open(folder.toPath(), java.nio.file.StandardOpenOption.READ)) {
dir.force(true);
} catch (java.io.IOException | RuntimeException e) {
android.util.Log.w("rustgis", "the secrets' folder wasn't synced: " + reason(e));
}
return "ok";
Comment on lines +129 to +132

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rename is reported as "ok" even when the folder's sync fails. The failure only reaches Log.w, and the Rust side never hears of it, so the Assistant says the key is remembered with no sign that its durability wasn't confirmed. The rest of the store answers with its failures. The prefs writer in crates/engine/src/prefs.rs says "preferences were replaced, but their durability could not be confirmed", so the two stores differ on this point.

AGENTS.md's "Never silent" rule asks a writer that approximates what it saves to say so, and Log.w alone does not count. The fix is for the Java half to answer a distinct line (for example ok followed by a tab and the reason), with Rust turning it into a notice, or to say in the doc comment and PR that this is an accepted limit.

Confidence about 50%: a power cut right after the rename is rare, and the rename itself has already happened.

Category: agents-md

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving it as an accepted limit, now said in the PR description as well as the comment above the sync. The rename is made before the sync, so the save stands; only a power cut before Android writes the folder could undo it. Answering it as a failure would tell the user the key wasn't remembered when it almost surely was, and a third "may or may not be kept" answer is what this store's design removes: the earlier version had one and it reached every caller of the secret store.

} catch (java.io.IOException | RuntimeException e) {
part.delete();
return UNWRITTEN + "\t" + reason(e);
}
}

/** The account's entry, or null when there is none. */
private static String kept(java.io.File file) throws java.io.IOException {
if (!file.exists()) {
return null;
}
byte[] bytes = java.nio.file.Files.readAllBytes(file.toPath());
return new String(bytes, java.nio.charset.StandardCharsets.US_ASCII);
}

/** The account's file: its name a SHA-256 of the account, as an account may hold any character. */
private static java.io.File file(android.content.Context context, String account) {
byte[] digest;
try {
digest = java.security.MessageDigest.getInstance("SHA-256").digest(account.getBytes(java.nio.charset.StandardCharsets.UTF_8));
} catch (java.security.NoSuchAlgorithmException e) {
// Every Android has SHA-256.
throw new IllegalStateException(e);
}
StringBuilder name = new StringBuilder();
for (byte b : digest) {
name.append(String.format(java.util.Locale.ROOT, "%02x", b));
}
return new java.io.File(new java.io.File(context.getApplicationContext().getNoBackupFilesDir(), FOLDER), name.toString());
}

/** The version an entry was written in: the number before its first point, 0 if none. */
private static int version(String kept) {
if (kept == null) {
return 0;
}
int dot = kept.indexOf('.');
try {
return dot <= 0 ? 0 : Integer.parseInt(kept.substring(0, dot));
} catch (NumberFormatException e) {
return 0;
}
}

/** The keystore's key, made the first time it is asked for when {@code make}; else null when there is none. */
private static synchronized javax.crypto.SecretKey key(boolean make) throws java.security.GeneralSecurityException, java.io.IOException {
java.security.KeyStore store = java.security.KeyStore.getInstance("AndroidKeyStore");
store.load(null);
java.security.Key key = store.getKey(KEY, null);
if (key instanceof javax.crypto.SecretKey) {
return (javax.crypto.SecretKey) key;
}
if (!make) {
return null;
}
javax.crypto.KeyGenerator maker = javax.crypto.KeyGenerator.getInstance(
android.security.keystore.KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
maker.init(new android.security.keystore.KeyGenParameterSpec.Builder(KEY,
android.security.keystore.KeyProperties.PURPOSE_ENCRYPT | android.security.keystore.KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(android.security.keystore.KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(android.security.keystore.KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build());
return maker.generateKey();
}

/** What went wrong, on one line. */
private static String reason(Throwable e) {
String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage();
return message.replaceAll("[\\t\\r\\n]", " ");
}
}
9 changes: 6 additions & 3 deletions apps/rustgis-mobile/src/android.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! The Android app: a `NativeActivity` whose Java half ([`Phone`]) shows the system's pickers
//! and text fields, finds the device's position and asks the camera.
//! and text fields, finds the device's position, asks the camera and keeps secrets ([`Vault`]).

use crate::phone::Phone;
use crate::phone::{self, Phone};
use crate::secrets::Vault;
use crate::shell;
use eframe::egui;
use eframe::wgpu;
Expand Down Expand Up @@ -61,6 +62,8 @@ fn set_folders(app: &AndroidApp) -> Option<std::path::PathBuf> {
fn android_main(android: AndroidApp) {
android_logger::init_once(android_logger::Config::default().with_max_level(log::LevelFilter::Info).with_tag("rustgis"));
let folders = set_folders(&android);
// The keystore's secrets, when the activity can be reached (else said below, by the phone).
let secrets = phone::activity(&android).ok().map(|activity| std::sync::Arc::new(Vault::new(activity)) as _);
let phone = Phone::new(&android);
// Before anything plans a job: the limits follow what Android allows, with the browser's
// floors. Without the activity's Java half nothing says what that is, and the stand-in
Expand All @@ -72,7 +75,7 @@ fn android_main(android: AndroidApp) {
false
}
};
let mut app = shell::front_end(folders.as_deref());
let mut app = shell::front_end(folders.as_deref(), secrets);
if !said {
shell::say_memory_unsaid(&mut app);
}
Expand Down
3 changes: 2 additions & 1 deletion apps/rustgis-mobile/src/ios.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1415,7 +1415,8 @@ pub fn main() {
let made = std::fs::create_dir_all(&folders.support).is_ok() && rustgis_engine::data::dirs::set_root(folders.support.clone());
// Before anything plans a job.
let said = plan_memory();
let mut app = shell::front_end(made.then_some(folders.support.as_path()));
// No secret store yet: the keychain crate's Apple store needs its `protected` feature on iOS.
let mut app = shell::front_end(made.then_some(folders.support.as_path()), None);
if !said {
shell::say_memory_unsaid(&mut app);
}
Expand Down
10 changes: 6 additions & 4 deletions apps/rustgis-mobile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
//! The desktop front end (`rustgis-ui-egui`) with the touch interface, in a `NativeActivity` on
//! Android and a UIKit window on iOS, with the phone (a `rustgis_engine::platform::Platform`)
//! standing where the browser stands for the web app: the system's file picker, the device's
//! position, the camera. `shell` is what both share. See `README.md` for how to build and install
//! them.
//!
//! Not here yet: preferences and the keychain.
//! position, the camera, and on Android a secret store. `shell` is what both share. See
//! `README.md` for how to build and install them.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]

#[cfg(any(target_os = "android", target_os = "ios", test))]
Expand All @@ -17,6 +15,10 @@ mod shell;
mod android;
#[cfg(target_os = "android")]
mod phone;
#[cfg(target_os = "android")]
mod secrets;
#[cfg(any(target_os = "android", test))]
mod vaultanswer;

#[cfg(target_os = "ios")]
mod ios;
Expand Down
Loading
Loading