From 83e8306be675ef5d3e758a257a6bc8e81db20919 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 18:57:00 -0600 Subject: [PATCH 01/12] feat(mobile): remember secrets on Android in the Android Keystore The phone apps had no secret store and no preferences, so an Assistant key, a database password or a ChatGPT sign-in lasted until the app closed, and so did the Assistant's provider and its Remember choice. On Android, Services::secrets is now a store whose Java half 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 the app's private SharedPreferences. Nothing is kept unencrypted: when the keystore can't be used, the store says it is unavailable and a secret lasts for the session, as on a computer with no keychain. Both phone apps now keep their preferences in prefs.json in the app's settings folder, as the desktop does; a file that can't be read or saved is said in the window. iOS has no store yet: the keychain crate's Apple store needs its protected feature there. --- apps/rustgis-mobile/README.md | 3 +- .../java/org/rustgis/mobile/MainActivity.java | 16 ++ .../java/org/rustgis/mobile/SecretVault.java | 176 ++++++++++++++++++ apps/rustgis-mobile/src/android.rs | 9 +- apps/rustgis-mobile/src/ios.rs | 3 +- apps/rustgis-mobile/src/lib.rs | 8 +- apps/rustgis-mobile/src/phone.rs | 39 ++-- apps/rustgis-mobile/src/secrets.rs | 90 +++++++++ apps/rustgis-mobile/src/shell.rs | 95 +++++++++- docs/user-guide/assistant.md | 3 +- 10 files changed, 412 insertions(+), 30 deletions(-) create mode 100644 apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java create mode 100644 apps/rustgis-mobile/src/secrets.rs diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 3e762e0013..69d8c1ee26 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -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 the app's private `SharedPreferences`. 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 diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java index 747d180c7d..cde3c85f95 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/MainActivity.java @@ -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(() -> { diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java new file mode 100644 index 0000000000..3a80287cc9 --- /dev/null +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java @@ -0,0 +1,176 @@ +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 + * app's private preferences as "1.." (Base64), the account name bound to it. + * 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" or "failed", each with the reason after a tab. + * Called on any thread: one call at a time, so a write and the putting back of a write that + * failed see no other call's entry in between. + */ +final class SecretVault { + /** The keystore's name for the one key. */ + private static final String KEY = "rustgis-secrets"; + /** The app's private preferences the encrypted secrets are kept in. */ + private static final String FILE = "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\tit was kept by a newer RustGIS: update RustGIS to use it"; + private static final String UNWRITTEN = "failed\tthe app's storage can't be written to"; + private static final String UNCERTAIN = + "failed\tthe app's storage can't be written to, and the secret as it was couldn't be put back: it may still be kept"; + + private SecretVault() {} + + static synchronized String load(android.content.Context context, String account) { + try { + String kept = preferences(context).getString(account, null); + 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\tthe kept secret is damaged"; + } + 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\tthe kept secret can't be decrypted: the keystore no longer has its 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 | ClassCastException e) { + // A damaged entry, or one sealed with a key the keystore no longer has. + return "failed\tthe kept secret can't be decrypted: " + reason(e); + } catch (RuntimeException e) { + return "failed\t" + reason(e); + } + } + + static synchronized String save(android.content.Context context, String account, String value) { + try { + android.content.SharedPreferences preferences = preferences(context); + String before = kept(preferences, account); + if (version(before) > 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(preferences, account, kept, before); + } catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException + | java.security.ProviderException e) { + return "unavailable\t" + reason(e); + } catch (ClassCastException e) { + return "failed\tthe kept secret is damaged"; + } catch (java.security.GeneralSecurityException | RuntimeException e) { + return "failed\t" + reason(e); + } + } + + static synchronized String delete(android.content.Context context, String account) { + try { + android.content.SharedPreferences preferences = preferences(context); + String before = kept(preferences, account); + if (version(before) > VERSION) { + return NEWER; + } + return before == null ? "ok" : write(preferences, account, null, before); + } catch (ClassCastException e) { + return "failed\tthe kept secret is damaged"; + } catch (RuntimeException e) { + return "failed\t" + reason(e); + } + } + + /** + * Writes the account's entry (null removes it) and answers how it went. A write that isn't + * confirmed puts the entry as it was back (Android keeps what it was given in memory, and + * would write it with a later save of another account), so a secret said not to be kept isn't; + * when that fails too, the answer says it may be. + */ + private static String write(android.content.SharedPreferences preferences, String account, String kept, String before) { + if (put(preferences.edit(), account, kept).commit()) { + return "ok"; + } + return put(preferences.edit(), account, before).commit() ? UNWRITTEN : UNCERTAIN; + } + + private static android.content.SharedPreferences.Editor put(android.content.SharedPreferences.Editor editor, String account, String kept) { + return kept == null ? editor.remove(account) : editor.putString(account, kept); + } + + /** The account's entry, or null; one that isn't text (not this vault's) throws ClassCastException. */ + private static String kept(android.content.SharedPreferences preferences, String account) { + return preferences.getString(account, null); + } + + /** 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; + } + } + + private static android.content.SharedPreferences preferences(android.content.Context context) { + return context.getApplicationContext().getSharedPreferences(FILE, android.content.Context.MODE_PRIVATE); + } + + /** 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]", " "); + } +} diff --git a/apps/rustgis-mobile/src/android.rs b/apps/rustgis-mobile/src/android.rs index c610ef648a..5ffd323b73 100644 --- a/apps/rustgis-mobile/src/android.rs +++ b/apps/rustgis-mobile/src/android.rs @@ -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; @@ -61,6 +62,8 @@ fn set_folders(app: &AndroidApp) -> Option { 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 @@ -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); } diff --git a/apps/rustgis-mobile/src/ios.rs b/apps/rustgis-mobile/src/ios.rs index 44b390c675..c0665387bd 100644 --- a/apps/rustgis-mobile/src/ios.rs +++ b/apps/rustgis-mobile/src/ios.rs @@ -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); } diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 1351aed2fc..19d1430ea0 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -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))] @@ -17,6 +15,8 @@ mod shell; mod android; #[cfg(target_os = "android")] mod phone; +#[cfg(target_os = "android")] +mod secrets; #[cfg(target_os = "ios")] mod ios; diff --git a/apps/rustgis-mobile/src/phone.rs b/apps/rustgis-mobile/src/phone.rs index 35a6a689ee..0233afacaf 100644 --- a/apps/rustgis-mobile/src/phone.rs +++ b/apps/rustgis-mobile/src/phone.rs @@ -15,6 +15,27 @@ use std::cell::RefCell; use std::sync::Arc; use winit::platform::android::activity::AndroidApp; +/// A reference of RustGIS's own to the activity `android` runs, or why its Java side can't be +/// reached. +pub fn activity(android: &AndroidApp) -> Result>, String> { + let raw = android.activity_as_ptr().cast(); + JavaVM::singleton() + .and_then(|vm| { + vm.attach_current_thread(|env| { + // SAFETY: `android-activity` keeps this global reference to the activity alive + // for as long as `android_main` runs, and it is only borrowed here to make a + // global reference of our own. + #[expect(unsafe_code, reason = "see SAFETY above")] + let activity = unsafe { JObject::from_raw(env, raw) }; + let held = env.new_global_ref(&activity); + // The borrowed reference is `android-activity`'s to delete, not ours. + let _ = activity.into_raw(); + held + }) + }) + .map_err(|e| i18n::fmt("Android's Java side can't be reached: {error}", &[("error", &e.to_string())])) +} + /// The phone, through its activity. pub struct Phone { activity: Arc>>, @@ -27,23 +48,7 @@ impl Phone { /// The phone `android` runs on, or why its Java half can't be reached (an APK built without /// it): the app then runs without a file picker and says so. pub fn new(android: &AndroidApp) -> Result { - let raw = android.activity_as_ptr().cast(); - let activity = JavaVM::singleton() - .and_then(|vm| { - vm.attach_current_thread(|env| { - // SAFETY: `android-activity` keeps this global reference to the activity alive - // for as long as `android_main` runs, and it is only borrowed here to make a - // global reference of our own. - #[expect(unsafe_code, reason = "see SAFETY above")] - let activity = unsafe { JObject::from_raw(env, raw) }; - let held = env.new_global_ref(&activity); - // The borrowed reference is `android-activity`'s to delete, not ours. - let _ = activity.into_raw(); - held - }) - }) - .map_err(|e| i18n::fmt("Android's Java side can't be reached: {error}", &[("error", &e.to_string())]))?; - let phone = Phone { activity: Arc::new(activity), unreachable: RefCell::new(None) }; + let phone = Phone { activity: Arc::new(activity(android)?), unreachable: RefCell::new(None) }; let owner = phone.java(|env, activity| { let token = env.call_method(activity, jni_str!("copyOwner"), jni_sig!(() -> JString), &[])?.l()?; env.cast_local::(token)?.try_to_string(env) diff --git a/apps/rustgis-mobile/src/secrets.rs b/apps/rustgis-mobile/src/secrets.rs new file mode 100644 index 0000000000..ec2fc0a18d --- /dev/null +++ b/apps/rustgis-mobile/src/secrets.rs @@ -0,0 +1,90 @@ +//! Android's secret store, [`Vault`]: the activity's Java half (`java/…/SecretVault.java`) keeps +//! each secret encrypted with AES-GCM, under a key the Android Keystore makes once and never lets +//! out, in the app's private storage. + +use jni::objects::{JObject, JString}; +use jni::refs::Global; +use jni::{JValue, JavaVM, jni_sig, jni_str}; +use rustgis_engine::data::secrets::{Secret, SecretError, SecretStore, check_account}; + +/// `Services::secrets` on Android. When the keystore can't be used, it answers +/// [`SecretError::Unavailable`], and a secret then lasts for the session, as on a computer with +/// no keychain: nothing is kept unencrypted. +pub struct Vault { + activity: Global>, +} + +impl Vault { + /// The store, through the app's `activity`. + pub fn new(activity: Global>) -> Vault { + Vault { activity } + } + + /// Runs `call` with the Java environment and the activity, on any thread: the methods are the + /// activity's, so they are found through its class loader, which a class looked up by name + /// from a thread Rust started wouldn't use. Returns the Java half's answer, one line. + fn ask(&self, call: impl FnOnce(&mut jni::Env, &JObject) -> jni::errors::Result) -> Result { + JavaVM::singleton() + .and_then(|vm| vm.attach_current_thread(|env| call(env, &self.activity))) + .map_err(|e| SecretError::Unavailable(e.to_string())) + } +} + +/// Reads the Java half's answer: `ok` (with the secret after a tab, for a load that found one), +/// `none`, or `unavailable` or `failed` with the reason after a tab. +fn answer(line: &str) -> Result, SecretError> { + match line.split_once('\t') { + Some(("ok", secret)) => Ok(Some(Secret::new(secret))), + Some(("unavailable", why)) => Err(SecretError::Unavailable(why.to_string())), + Some(("failed", why)) => Err(SecretError::Failed(why.to_string())), + None if line == "ok" || line == "none" => Ok(None), + _ => Err(SecretError::Failed("the Android keystore gave an answer RustGIS doesn't know".into())), + } +} + +impl SecretStore for Vault { + /// Decrypts the account's secret; one the keystore's key no longer opens is a failure. + fn load(&self, account: &str) -> Result, SecretError> { + check_account(account)?; + let line = self.ask(|env, activity| { + let account = env.new_string(account)?; + let line = env + .call_method(activity, jni_str!("loadSecret"), jni_sig!((account: JString) -> JString), &[JValue::Object(&account)])? + .l()?; + env.cast_local::(line)?.try_to_string(env) + })?; + answer(&line) + } + + /// Encrypts the secret under a new nonce, bound to its account, and keeps it. + fn save(&self, account: &str, value: &Secret) -> Result<(), SecretError> { + check_account(account)?; + let line = self.ask(|env, activity| { + let account = env.new_string(account)?; + let value = env.new_string(value.expose())?; + let line = env + .call_method( + activity, + jni_str!("saveSecret"), + jni_sig!((account: JString, value: JString) -> JString), + &[JValue::Object(&account), JValue::Object(&value)], + )? + .l()?; + env.cast_local::(line)?.try_to_string(env) + })?; + answer(&line).map(|_| ()) + } + + /// Forgets the account's secret; the keystore's key stays for the others. + fn delete(&self, account: &str) -> Result<(), SecretError> { + check_account(account)?; + let line = self.ask(|env, activity| { + let account = env.new_string(account)?; + let line = env + .call_method(activity, jni_str!("deleteSecret"), jni_sig!((account: JString) -> JString), &[JValue::Object(&account)])? + .l()?; + env.cast_local::(line)?.try_to_string(env) + })?; + answer(&line).map(|_| ()) + } +} diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 03474cc07d..90404e2a71 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -3,6 +3,7 @@ //! stands for the web app. Each system's module makes its [`Phone`] and calls [`run`]. use eframe::egui; +use rustgis_engine::data::secrets::SecretStore; use rustgis_engine::platform::{Event, Platform}; use rustgis_ui_egui::{FolderStore, Inbox, RustGisApp, i18n, tl}; use std::cell::RefCell; @@ -193,6 +194,9 @@ impl App

{ for text in self.refusals.borrow_mut().drain(..) { self.app.session.notify(text, true); } + for text in std::mem::take(&mut *settings_notices()) { + self.app.session.notify(text, true); + } let Some(phone) = self.phone.clone() else { return }; // Positions out of sight follow what the interface asks for (a track being recorded). if self.app.keep_locating != self.keeping { @@ -691,6 +695,10 @@ impl eframe::App for App

{ phone.takes_back(back); } } + // A settings file that couldn't be read or saved in this frame is said in the next one. + if !settings_notices().is_empty() { + ctx.request_repaint(); + } // A second picker asked for while one was up was refused: what the front end kept for // the first is put back, so its file is read as it was asked for. if self.refused_picker.replace(false) @@ -842,13 +850,13 @@ pub fn pushed(dir: Option, app: &mut RustGisApp) -> Vec { } /// Makes the front end with the sample project and recovery in the phone's private storage. -pub fn front_end(root: Option<&Path>) -> RustGisApp { +pub fn front_end(root: Option<&Path>, secrets: Option>) -> RustGisApp { // Datum grids: the app's own folder, where downloaded ones are kept (#2032 A4); // a phone has no PROJ install to share. if root.is_some() { rustgis_engine::data::raster::crs::use_grid_folders(); } - let mut app = RustGisApp::with_sample(); + let mut app = RustGisApp::with_sample().with_services(services(root.is_some(), secrets)); if let Some(root) = root { match FolderStore::open(&root.join("recovery")) { Ok(store) => app = app.with_edit_recovery(Box::new(store)), @@ -861,13 +869,77 @@ pub fn front_end(root: Option<&Path>) -> RustGisApp { app.session.in_place_wait = false; app.session.on_window_thread = true; app.reads_off_frame = true; - if let Err(e) = app.start(&rustgis_ui_egui::Start { blank: Some(false), ..Default::default() }) { + // Start With's Blank Map or the sample; a project by its path (Last Project, a file) isn't one + // a phone can open at start, so the sample stands in for it. + let blank = app.ui.start_with == rustgis_ui_egui::StartWith::Blank; + if let Err(e) = app.start(&rustgis_ui_egui::Start { blank: Some(blank), ..Default::default() }) { log::warn!("start-up: {e}"); app.session.notify(e, true); } app } +/// The phone's settings and secrets, for [`RustGisApp::with_services`]: the preferences in +/// `prefs.json` in the app's settings folder, as on the desktop, where it has a folder of its own +/// (`settings`), and the system's secret store where it has one (`secrets`). With both, what the +/// Assistant keeps (its provider, Remember the key, the key) lasts from one start to the next. +/// Without a store, a key lasts for the session, as on a computer with no keychain. +fn services(settings: bool, secrets: Option>) -> rustgis_ui_egui::Services { + // The ChatGPT sign-in's tokens go to the same store, as on the desktop. + rustgis_ui_egui::rustgis_assistant::chatgpt::set_secret_store(secrets.clone()); + let mut services = rustgis_ui_egui::Services { secrets, ..Default::default() }; + if settings { + services.load_pref = Some(Box::new(|key: &str| read_settings().get(key).and_then(serde_json::Value::as_str).map(str::to_string))); + services.save_pref = Some(Box::new(|key: &str, value: &str| settings_saved(rustgis_engine::prefs::write(key, value)))); + } + services +} + +/// What reading or saving the settings came to that the window is still to say (it may not be up +/// yet when they are first read). +fn settings_notices() -> std::sync::MutexGuard<'static, Vec> { + static NOTICES: Mutex> = Mutex::new(Vec::new()); + NOTICES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The saved settings, or none when the file can't be read: said once a run. +fn read_settings() -> serde_json::Map { + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + rustgis_engine::prefs::read().unwrap_or_else(|error| { + if !SAID.swap(true, Ordering::Relaxed) { + log::warn!("{error}"); + settings_notices() + .push(i18n::fmt("Your settings couldn't be read ({error}), so RustGIS is using its defaults.", &[("error", &error)])); + } + serde_json::Map::new() + }) +} + +/// Says what a save of the settings came to: an unreadable file set aside, or a failure, said +/// once until a save works again. +fn settings_saved(result: Result, String>) { + static LAST_FAILURE: Mutex> = Mutex::new(None); + let mut last = LAST_FAILURE.lock().unwrap_or_else(|e| e.into_inner()); + match result { + Ok(set_aside) => { + *last = None; + if let Some(path) = set_aside { + settings_notices().push(i18n::fmt( + "Your settings couldn't be read, so RustGIS started new ones. The old settings file was kept as {path}.", + &[("path", &path.display().to_string())], + )); + } + } + Err(error) => { + log::warn!("{error}"); + if last.as_deref() != Some(error.as_str()) { + settings_notices().push(i18n::fmt("Settings could not be saved reliably ({error}).", &[("error", &error)])); + *last = Some(error); + } + } + } +} + /// Runs `app` in the phone's window with the touch interface: `phone` (or why it can't be /// reached), the files `pushed` to open once the window is up, and the window's `options`. /// Returns when the window is gone (Android); on iOS it never returns. @@ -1050,6 +1122,23 @@ mod tests { assert!(said[0].text.contains("system's clipboard") && said[0].text.contains("no clipboard")); } + /// A settings save that fails is said once, not on every later save that fails the same way, + /// and again after one works; a file set aside is said where it went. + #[test] + fn a_failed_settings_save_is_said_once_until_one_works() { + settings_notices().clear(); + settings_saved(Err("no room".into())); + settings_saved(Err("no room".into())); + assert_eq!(std::mem::take(&mut *settings_notices()), vec!["Settings could not be saved reliably (no room).".to_string()]); + settings_saved(Ok(None)); + assert!(settings_notices().is_empty()); + settings_saved(Err("no room".into())); + settings_saved(Ok(Some(PathBuf::from("/data/settings/prefs.json.bad")))); + let said = std::mem::take(&mut *settings_notices()); + assert_eq!(said.len(), 2, "{said:?}"); + assert!(said[1].ends_with("kept as /data/settings/prefs.json.bad."), "{said:?}"); + } + #[test] fn same_frame_refused_picker_restores_the_options_of_the_admitted_request() { let mut app = RustGisApp::with_sample(); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index d3b6162ecc..9cd809509f 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -340,7 +340,8 @@ results such as rows the assistant reads, the pictures you attach to a message, assistant calls `view_map`, a picture of the map, basemap tiles included. Local agents use their own providers and tools, with their own data handling. A key typed in the settings is used for the session only unless you tick **Remember the key on this computer**. On the desktop, this saves it in the system -keychain (macOS Keychain, Windows Credential Manager, or the Secret Service on Linux). Clearing +keychain (macOS Keychain, Windows Credential Manager, or the Secret Service on Linux); on +Android, it is encrypted with a key the Android Keystore holds. Clearing the key or unticking **Remember** deletes the saved key; a failed deletion is shown in settings. Keys from the environment are never saved. If the keychain is unavailable, locked, or access is refused, a new key stays in memory for this session and the settings explain why it was not From a23945f4a05511d5a3d67e631832e9b9e51a0229 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 22:18:34 -0600 Subject: [PATCH 02/12] fix(mobile): a key save Android can't confirm is said as unconfirmed, not as forgotten Review of #3002: when a write and its rollback both went unconfirmed, the Assistant said the key wasn't remembered although it may be. SecretError gains Uncertain for that case. The Java half's answers are read in a module the host tests cover, and the settings notices are taken before they are shown. --- .../java/org/rustgis/mobile/SecretVault.java | 2 +- apps/rustgis-mobile/src/lib.rs | 2 ++ apps/rustgis-mobile/src/secrets.rs | 13 +------ apps/rustgis-mobile/src/shell.rs | 3 +- apps/rustgis-mobile/src/vaultanswer.rs | 35 +++++++++++++++++++ crates/data/src/secrets.rs | 4 +++ crates/ui-egui/src/assistantpane.rs | 24 +++++++++++++ 7 files changed, 69 insertions(+), 14 deletions(-) create mode 100644 apps/rustgis-mobile/src/vaultanswer.rs diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java index 3a80287cc9..9d9d6d7ede 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java @@ -25,7 +25,7 @@ final class SecretVault { private static final String NEWER = "failed\tit was kept by a newer RustGIS: update RustGIS to use it"; private static final String UNWRITTEN = "failed\tthe app's storage can't be written to"; private static final String UNCERTAIN = - "failed\tthe app's storage can't be written to, and the secret as it was couldn't be put back: it may still be kept"; + "uncertain\tthe app's storage can't be written to, and the secret as it was couldn't be put back: it may still be kept"; private SecretVault() {} diff --git a/apps/rustgis-mobile/src/lib.rs b/apps/rustgis-mobile/src/lib.rs index 19d1430ea0..f1e7c25d64 100644 --- a/apps/rustgis-mobile/src/lib.rs +++ b/apps/rustgis-mobile/src/lib.rs @@ -17,6 +17,8 @@ mod android; mod phone; #[cfg(target_os = "android")] mod secrets; +#[cfg(any(target_os = "android", test))] +mod vaultanswer; #[cfg(target_os = "ios")] mod ios; diff --git a/apps/rustgis-mobile/src/secrets.rs b/apps/rustgis-mobile/src/secrets.rs index ec2fc0a18d..9102cacb04 100644 --- a/apps/rustgis-mobile/src/secrets.rs +++ b/apps/rustgis-mobile/src/secrets.rs @@ -2,6 +2,7 @@ //! each secret encrypted with AES-GCM, under a key the Android Keystore makes once and never lets //! out, in the app's private storage. +use crate::vaultanswer::answer; use jni::objects::{JObject, JString}; use jni::refs::Global; use jni::{JValue, JavaVM, jni_sig, jni_str}; @@ -30,18 +31,6 @@ impl Vault { } } -/// Reads the Java half's answer: `ok` (with the secret after a tab, for a load that found one), -/// `none`, or `unavailable` or `failed` with the reason after a tab. -fn answer(line: &str) -> Result, SecretError> { - match line.split_once('\t') { - Some(("ok", secret)) => Ok(Some(Secret::new(secret))), - Some(("unavailable", why)) => Err(SecretError::Unavailable(why.to_string())), - Some(("failed", why)) => Err(SecretError::Failed(why.to_string())), - None if line == "ok" || line == "none" => Ok(None), - _ => Err(SecretError::Failed("the Android keystore gave an answer RustGIS doesn't know".into())), - } -} - impl SecretStore for Vault { /// Decrypts the account's secret; one the keystore's key no longer opens is a failure. fn load(&self, account: &str) -> Result, SecretError> { diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 90404e2a71..402d3efd9f 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -194,7 +194,8 @@ impl App

{ for text in self.refusals.borrow_mut().drain(..) { self.app.session.notify(text, true); } - for text in std::mem::take(&mut *settings_notices()) { + let notices = std::mem::take(&mut *settings_notices()); + for text in notices { self.app.session.notify(text, true); } let Some(phone) = self.phone.clone() else { return }; diff --git a/apps/rustgis-mobile/src/vaultanswer.rs b/apps/rustgis-mobile/src/vaultanswer.rs new file mode 100644 index 0000000000..49a4a9251e --- /dev/null +++ b/apps/rustgis-mobile/src/vaultanswer.rs @@ -0,0 +1,35 @@ +//! The answers of Android's secret store (`java/…/SecretVault.java`), read apart from the store +//! itself so the host's tests cover them. + +use rustgis_engine::data::secrets::{Secret, SecretError}; + +/// Reads the Java half's answer: `ok` (with the secret after a tab, for a load that found one), +/// `none`, or `unavailable`, `failed` or `uncertain` (a change that may or may not have been kept) +/// with the reason after a tab. +pub(crate) fn answer(line: &str) -> Result, SecretError> { + match line.split_once('\t') { + Some(("ok", secret)) => Ok(Some(Secret::new(secret))), + Some(("unavailable", why)) => Err(SecretError::Unavailable(why.to_string())), + Some(("failed", why)) => Err(SecretError::Failed(why.to_string())), + Some(("uncertain", why)) => Err(SecretError::Uncertain(why.to_string())), + None if line == "ok" || line == "none" => Ok(None), + _ => Err(SecretError::Failed("the Android keystore gave an answer RustGIS doesn't know".into())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_answer_of_the_java_half_is_read() { + assert_eq!(answer("ok\tsk-test").unwrap().map(|s| s.expose().to_string()), Some("sk-test".into())); + assert!(answer("ok").unwrap().is_none()); + assert!(answer("none").unwrap().is_none()); + assert_eq!(answer("unavailable\tno keystore"), Err(SecretError::Unavailable("no keystore".into()))); + assert_eq!(answer("failed\tdamaged"), Err(SecretError::Failed("damaged".into()))); + assert_eq!(answer("uncertain\tmay be kept"), Err(SecretError::Uncertain("may be kept".into()))); + assert!(matches!(answer("saved"), Err(SecretError::Failed(why)) if why.contains("doesn't know"))); + assert!(matches!(answer("later\tx"), Err(SecretError::Failed(why)) if why.contains("doesn't know"))); + } +} diff --git a/crates/data/src/secrets.rs b/crates/data/src/secrets.rs index 89fefe4496..c6e0e1f9cd 100644 --- a/crates/data/src/secrets.rs +++ b/crates/data/src/secrets.rs @@ -36,6 +36,9 @@ pub enum SecretError { Denied, InvalidAccount(String), Failed(String), + /// The store couldn't confirm whether the change was kept: a secret said to be saved, or one + /// said to be forgotten, may or may not be there next time. + Uncertain(String), } impl fmt::Display for SecretError { @@ -45,6 +48,7 @@ impl fmt::Display for SecretError { Self::Denied => f.write_str("the system keychain is locked or access to it was refused"), Self::InvalidAccount(account) => write!(f, "invalid secret name \"{account}\""), Self::Failed(why) => write!(f, "the system keychain failed: {why}"), + Self::Uncertain(why) => write!(f, "the system keychain couldn't confirm the change: {why}"), } } } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 74bf210c1a..a83083baa0 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -303,12 +303,17 @@ fn key_storage_note(app: &RustGisApp, provider: &str) -> String { notes.push(match error { SecretError::Denied => tl!("The system keychain is locked or access was refused."), SecretError::Unavailable(_) => tl!("The system keychain is unavailable."), + SecretError::Uncertain(_) => tl!("The system keychain couldn't confirm the change."), _ => tl!("The system keychain could not complete the request."), }); if *reading { notes.push(tl!("A saved key could not be read. A key entered now will be kept for this session only.")); } else if *deleting { notes.push(tl!("RustGIS could not confirm that any previously saved key was deleted from the system keychain.")); + } else if matches!(error, SecretError::Uncertain(_)) { + notes.push(tl!( + "RustGIS could not confirm whether the key was remembered: it may be there the next time RustGIS starts." + )); } else if !legacy || !plaintext { notes.push(tl!("The key is kept for this session only; it has not been remembered.")); } @@ -1069,6 +1074,25 @@ pub(crate) mod tests { } } + /// A save the store couldn't confirm isn't said to be lost: the key may be there next time. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_unconfirmed_save_is_not_said_to_be_forgotten() { + use rustgis_engine::data::secrets::{MemorySecrets, SecretError}; + let store = std::sync::Arc::new(MemorySecrets::failing(SecretError::Uncertain("synthetic-why".into()))); + let (mut app, _) = keys_app(None, Some(store)); + settle_keys(&mut app); + let mut cfg = app.assistant.agent.as_ref().unwrap().config.clone(); + cfg.key = "synthetic-new".into(); + app.assistant.keys.edit("custom", &cfg.key); + apply_config(&mut app, cfg.clone()); + save_config(&mut app, &cfg, &egui::Context::default()); + settle_keys(&mut app); + let note = key_storage_note(&app, "custom"); + assert!(note.contains("could not confirm whether the key was remembered"), "{note}"); + assert!(!note.contains("has not been remembered") && !note.contains("synthetic-new")); + } + /// A failed replacement is session-only even when a different legacy key still needs migration. #[cfg(not(target_arch = "wasm32"))] #[test] From 51cfcd8fbfcebda248c90f33a4ffdd6bb8208f3c Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 23:12:29 -0600 Subject: [PATCH 03/12] fix(tiles): an unconfirmed Copernicus or Earthdata save isn't said to be forgotten Review of #3002: the two sign-ins sharing the credential store reported a save the store couldn't confirm as not remembered. They say it couldn't be confirmed, and Copernicus never signs in with it this session. --- crates/tiles/src/copernicus.rs | 7 ++++++- crates/tiles/src/copernicus/tests.rs | 4 ++++ crates/tiles/src/earthdata.rs | 9 +++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/tiles/src/copernicus.rs b/crates/tiles/src/copernicus.rs index a59403384a..11fdc46d3c 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -177,6 +177,9 @@ pub const NO_STORE: &str = "The sign-in is kept for this session only: there is pub const NOT_REMEMBERED: &str = "The sign-in is kept for this session, but the system's credential store didn't remember it."; /// `login` with `remember` and a one-time code. pub const TWO_FACTOR: &str = "The sign-in is kept for this session only: an account with two-factor authentication needs its one-time code at each sign-in, so it isn't remembered."; +/// `login` with `remember`, when the credential store couldn't confirm what it kept. +pub const UNCONFIRMED: &str = + "The sign-in is kept for this session; the system's credential store couldn't confirm whether it remembered it."; /// The credential store didn't delete the sign-in remembered earlier. pub const NOT_FORGOTTEN: &str = "The sign-in remembered on this computer couldn't be deleted from the system's credential store."; @@ -308,7 +311,8 @@ fn remember_after(known: &mut Known, username: &str, password: &str, totp: bool, let deleted = store.delete(ACCOUNT); // Unread: an earlier run may have remembered one, unless there's no store at all. let unknown = matches!(*known, Known::Unread | Known::Unreadable); - let lingers = |e: &SecretError| was || (unknown && !matches!(e, SecretError::Unavailable(_))); + // One the store couldn't confirm may be there whatever this session knew. + let lingers = |e: &SecretError| was || matches!(e, SecretError::Uncertain(_)) || (unknown && !matches!(e, SecretError::Unavailable(_))); let left = deleted.as_ref().err().is_some_and(lingers); // One known to be there that couldn't be deleted is never signed in with again this session; // one that may be there stays unknown (`remembered` reports only what was found). @@ -318,6 +322,7 @@ fn remember_after(known: &mut Known, username: &str, password: &str, totp: bool, _ => Known::Nothing, }; match deleted { + Err(SecretError::Uncertain(_)) if remember && !was => Some(UNCONFIRMED), // Said first: a password remembered before may still be there. Err(_) if left => Some(NOT_FORGOTTEN), _ if remember && totp => Some(TWO_FACTOR), diff --git a/crates/tiles/src/copernicus/tests.rs b/crates/tiles/src/copernicus/tests.rs index 2ef81e4e0a..eb715851ed 100644 --- a/crates/tiles/src/copernicus/tests.rs +++ b/crates/tiles/src/copernicus/tests.rs @@ -426,6 +426,10 @@ fn a_sign_in_not_to_be_remembered_deletes_the_one_before_and_two_factor_is_never set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Unavailable("none".into()))))); assert_eq!(login_remembering_at(&base, USER, PASSWORD, None, true).unwrap().1, Some(NOT_REMEMBERED)); assert!(signed_in().is_some()); + // A store that can't confirm what it kept: not said to be forgotten, nor claimed remembered. + set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Uncertain("unconfirmed".into()))))); + assert_eq!(login_remembering_at(&base, USER, PASSWORD, None, true).unwrap().1, Some(UNCONFIRMED)); + assert!(!is_remembered()); } #[test] diff --git a/crates/tiles/src/earthdata.rs b/crates/tiles/src/earthdata.rs index 681f93a4a5..32726e477f 100644 --- a/crates/tiles/src/earthdata.rs +++ b/crates/tiles/src/earthdata.rs @@ -170,6 +170,9 @@ pub const ACCOUNT: &str = "earthdata/token"; pub const NO_STORE: &str = "The token is kept for this session only: there is no credential store here to remember it in."; /// [`login`] with `remember`, when the credential store didn't keep the token. pub const NOT_REMEMBERED: &str = "The token is kept for this session, but the system's credential store didn't remember it."; +/// `login` with `remember`, when the credential store couldn't confirm what it kept. +pub const UNCONFIRMED: &str = + "The token is kept for this session; the system's credential store couldn't confirm whether it remembered it."; /// The credential store didn't delete the token remembered earlier. pub const NOT_FORGOTTEN: &str = "The token remembered on this computer couldn't be deleted from the system's credential store."; @@ -304,6 +307,7 @@ pub fn login(token: &str, remember: bool) -> Result, String let deleted = store.delete(ACCOUNT); REMEMBERED.kept.store(kept && deleted.is_err(), Ordering::SeqCst); match deleted { + Err(rustgis_data::secrets::SecretError::Uncertain(_)) if remember => Ok(Some(UNCONFIRMED)), _ if remember => Ok(Some(NOT_REMEMBERED)), Ok(()) => Ok(None), // A system without a credential store had nowhere to keep one. @@ -1071,6 +1075,11 @@ mod tests { assert_eq!(login(LASTING, true), Ok(Some(NOT_REMEMBERED))); assert!(has_token() && !is_remembered()); assert_eq!(logout(), Err(NOT_FORGOTTEN)); + // A store that can't confirm what it kept: not said to have forgotten it. + set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Uncertain("unconfirmed".into()))))); + assert_eq!(login(LASTING, true), Ok(Some(UNCONFIRMED))); + assert!(has_token() && !is_remembered()); + let _ = logout(); assert!(!has_token()); assert!(login("", true).is_err() && login("two words", true).is_err()); } From ca110e4e30244ec6df8abc2d2e02a792dcc28fac Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 23:46:48 -0600 Subject: [PATCH 04/12] fix(tiles): a two-factor Copernicus sign-in isn't said to be unconfirmed Review of #3002: with a one-time code nothing is saved, so an unconfirmed delete of the one before says that one may still be there. --- crates/tiles/src/copernicus.rs | 3 ++- crates/tiles/src/copernicus/tests.rs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/tiles/src/copernicus.rs b/crates/tiles/src/copernicus.rs index 11fdc46d3c..77734b55d5 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -322,7 +322,8 @@ fn remember_after(known: &mut Known, username: &str, password: &str, totp: bool, _ => Known::Nothing, }; match deleted { - Err(SecretError::Uncertain(_)) if remember && !was => Some(UNCONFIRMED), + // A two-factor sign-in was never saved: only the delete of the one before is unconfirmed. + Err(SecretError::Uncertain(_)) if remember && !totp && !was => Some(UNCONFIRMED), // Said first: a password remembered before may still be there. Err(_) if left => Some(NOT_FORGOTTEN), _ if remember && totp => Some(TWO_FACTOR), diff --git a/crates/tiles/src/copernicus/tests.rs b/crates/tiles/src/copernicus/tests.rs index eb715851ed..9563a38f14 100644 --- a/crates/tiles/src/copernicus/tests.rs +++ b/crates/tiles/src/copernicus/tests.rs @@ -430,6 +430,8 @@ fn a_sign_in_not_to_be_remembered_deletes_the_one_before_and_two_factor_is_never set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Uncertain("unconfirmed".into()))))); assert_eq!(login_remembering_at(&base, USER, PASSWORD, None, true).unwrap().1, Some(UNCONFIRMED)); assert!(!is_remembered()); + // With a one-time code nothing was saved: it's the one before that may still be there. + assert_eq!(login_remembering_at(&base, USER, PASSWORD, Some("123456"), true).unwrap().1, Some(NOT_FORGOTTEN)); } #[test] From 771b1e8824aaefb4b82c3f095fd26e5c86a97b06 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 07:46:33 -0600 Subject: [PATCH 05/12] fix(mobile): keep each Android secret in a file of its own, renamed into place Review of #3002: a SharedPreferences write that isn't confirmed may still be written later, so a failed save couldn't always say whether the secret was kept, and that doubt reached every caller of the secret store. Each secret is now written whole beside its file and renamed over it: a failed save or removal leaves the entry as it was, and is a plain failure. The files are in the app's no-backup folder, where the keystore's key could open them. This drops SecretError::Uncertain and the Assistant, Copernicus and Earthdata wording for it. --- apps/rustgis-mobile/README.md | 2 +- .../java/org/rustgis/mobile/SecretVault.java | 98 +++++++++++-------- apps/rustgis-mobile/src/vaultanswer.rs | 5 +- crates/data/src/secrets.rs | 4 - crates/tiles/src/copernicus.rs | 8 +- crates/tiles/src/copernicus/tests.rs | 6 -- crates/tiles/src/earthdata.rs | 9 -- crates/ui-egui/src/assistantpane.rs | 24 ----- 8 files changed, 61 insertions(+), 95 deletions(-) diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 69d8c1ee26..d516c685ee 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -250,7 +250,7 @@ own was used outside the area) is said, as a later package from the same phone r | 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 | `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 the app's private `SharedPreferences`. 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 | +| 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 diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java index 9d9d6d7ede..149dd66b94 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java @@ -3,35 +3,35 @@ /** * 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 - * app's private preferences as "1.." (Base64), the account name bound to it. - * 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. + * file of its own as "1.." (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" or "failed", each with the reason after a tab. - * Called on any thread: one call at a time, so a write and the putting back of a write that - * failed see no other call's entry in between. + * 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 app's private preferences the encrypted secrets are kept in. */ - private static final String FILE = "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\tit was kept by a newer RustGIS: update RustGIS to use it"; private static final String UNWRITTEN = "failed\tthe app's storage can't be written to"; - private static final String UNCERTAIN = - "uncertain\tthe app's storage can't be written to, and the secret as it was couldn't be put back: it may still be kept"; private SecretVault() {} static synchronized String load(android.content.Context context, String account) { try { - String kept = preferences(context).getString(account, null); + String kept = kept(file(context, account)); if (kept == null) { return "none"; } @@ -58,7 +58,7 @@ static synchronized String load(android.content.Context context, String account) } catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException | java.security.ProviderException e) { return "unavailable\t" + reason(e); - } catch (java.security.GeneralSecurityException | IllegalArgumentException | ClassCastException e) { + } catch (java.security.GeneralSecurityException | IllegalArgumentException e) { // A damaged entry, or one sealed with a key the keystore no longer has. return "failed\tthe kept secret can't be decrypted: " + reason(e); } catch (RuntimeException e) { @@ -68,9 +68,8 @@ static synchronized String load(android.content.Context context, String account) static synchronized String save(android.content.Context context, String account, String value) { try { - android.content.SharedPreferences preferences = preferences(context); - String before = kept(preferences, account); - if (version(before) > VERSION) { + java.io.File file = file(context, account); + if (version(kept(file)) > VERSION) { return NEWER; } javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER); @@ -81,12 +80,10 @@ static synchronized String save(android.content.Context context, String account, 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(preferences, account, kept, before); + return write(file, kept); } catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException | java.security.ProviderException e) { return "unavailable\t" + reason(e); - } catch (ClassCastException e) { - return "failed\tthe kept secret is damaged"; } catch (java.security.GeneralSecurityException | RuntimeException e) { return "failed\t" + reason(e); } @@ -94,39 +91,64 @@ static synchronized String save(android.content.Context context, String account, static synchronized String delete(android.content.Context context, String account) { try { - android.content.SharedPreferences preferences = preferences(context); - String before = kept(preferences, account); + java.io.File file = file(context, account); + String before = kept(file); if (version(before) > VERSION) { return NEWER; } - return before == null ? "ok" : write(preferences, account, null, before); - } catch (ClassCastException e) { - return "failed\tthe kept secret is damaged"; - } catch (RuntimeException e) { + return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN; + } catch (java.io.IOException | RuntimeException e) { return "failed\t" + reason(e); } } /** - * Writes the account's entry (null removes it) and answers how it went. A write that isn't - * confirmed puts the entry as it was back (Android keeps what it was given in memory, and - * would write it with a later save of another account), so a secret said not to be kept isn't; - * when that fails too, the answer says it may be. + * 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(android.content.SharedPreferences preferences, String account, String kept, String before) { - if (put(preferences.edit(), account, kept).commit()) { + 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); return "ok"; + } catch (java.io.IOException | RuntimeException e) { + part.delete(); + return UNWRITTEN + ": " + reason(e); } - return put(preferences.edit(), account, before).commit() ? UNWRITTEN : UNCERTAIN; } - private static android.content.SharedPreferences.Editor put(android.content.SharedPreferences.Editor editor, String account, String kept) { - return kept == null ? editor.remove(account) : editor.putString(account, kept); + /** 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 entry, or null; one that isn't text (not this vault's) throws ClassCastException. */ - private static String kept(android.content.SharedPreferences preferences, String account) { - return preferences.getString(account, null); + /** 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. */ @@ -142,10 +164,6 @@ private static int version(String kept) { } } - private static android.content.SharedPreferences preferences(android.content.Context context) { - return context.getApplicationContext().getSharedPreferences(FILE, android.content.Context.MODE_PRIVATE); - } - /** 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"); diff --git a/apps/rustgis-mobile/src/vaultanswer.rs b/apps/rustgis-mobile/src/vaultanswer.rs index 49a4a9251e..1aed28449c 100644 --- a/apps/rustgis-mobile/src/vaultanswer.rs +++ b/apps/rustgis-mobile/src/vaultanswer.rs @@ -4,14 +4,12 @@ use rustgis_engine::data::secrets::{Secret, SecretError}; /// Reads the Java half's answer: `ok` (with the secret after a tab, for a load that found one), -/// `none`, or `unavailable`, `failed` or `uncertain` (a change that may or may not have been kept) -/// with the reason after a tab. +/// `none`, or `unavailable` or `failed` with the reason after a tab. pub(crate) fn answer(line: &str) -> Result, SecretError> { match line.split_once('\t') { Some(("ok", secret)) => Ok(Some(Secret::new(secret))), Some(("unavailable", why)) => Err(SecretError::Unavailable(why.to_string())), Some(("failed", why)) => Err(SecretError::Failed(why.to_string())), - Some(("uncertain", why)) => Err(SecretError::Uncertain(why.to_string())), None if line == "ok" || line == "none" => Ok(None), _ => Err(SecretError::Failed("the Android keystore gave an answer RustGIS doesn't know".into())), } @@ -28,7 +26,6 @@ mod tests { assert!(answer("none").unwrap().is_none()); assert_eq!(answer("unavailable\tno keystore"), Err(SecretError::Unavailable("no keystore".into()))); assert_eq!(answer("failed\tdamaged"), Err(SecretError::Failed("damaged".into()))); - assert_eq!(answer("uncertain\tmay be kept"), Err(SecretError::Uncertain("may be kept".into()))); assert!(matches!(answer("saved"), Err(SecretError::Failed(why)) if why.contains("doesn't know"))); assert!(matches!(answer("later\tx"), Err(SecretError::Failed(why)) if why.contains("doesn't know"))); } diff --git a/crates/data/src/secrets.rs b/crates/data/src/secrets.rs index c6e0e1f9cd..89fefe4496 100644 --- a/crates/data/src/secrets.rs +++ b/crates/data/src/secrets.rs @@ -36,9 +36,6 @@ pub enum SecretError { Denied, InvalidAccount(String), Failed(String), - /// The store couldn't confirm whether the change was kept: a secret said to be saved, or one - /// said to be forgotten, may or may not be there next time. - Uncertain(String), } impl fmt::Display for SecretError { @@ -48,7 +45,6 @@ impl fmt::Display for SecretError { Self::Denied => f.write_str("the system keychain is locked or access to it was refused"), Self::InvalidAccount(account) => write!(f, "invalid secret name \"{account}\""), Self::Failed(why) => write!(f, "the system keychain failed: {why}"), - Self::Uncertain(why) => write!(f, "the system keychain couldn't confirm the change: {why}"), } } } diff --git a/crates/tiles/src/copernicus.rs b/crates/tiles/src/copernicus.rs index 77734b55d5..a59403384a 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -177,9 +177,6 @@ pub const NO_STORE: &str = "The sign-in is kept for this session only: there is pub const NOT_REMEMBERED: &str = "The sign-in is kept for this session, but the system's credential store didn't remember it."; /// `login` with `remember` and a one-time code. pub const TWO_FACTOR: &str = "The sign-in is kept for this session only: an account with two-factor authentication needs its one-time code at each sign-in, so it isn't remembered."; -/// `login` with `remember`, when the credential store couldn't confirm what it kept. -pub const UNCONFIRMED: &str = - "The sign-in is kept for this session; the system's credential store couldn't confirm whether it remembered it."; /// The credential store didn't delete the sign-in remembered earlier. pub const NOT_FORGOTTEN: &str = "The sign-in remembered on this computer couldn't be deleted from the system's credential store."; @@ -311,8 +308,7 @@ fn remember_after(known: &mut Known, username: &str, password: &str, totp: bool, let deleted = store.delete(ACCOUNT); // Unread: an earlier run may have remembered one, unless there's no store at all. let unknown = matches!(*known, Known::Unread | Known::Unreadable); - // One the store couldn't confirm may be there whatever this session knew. - let lingers = |e: &SecretError| was || matches!(e, SecretError::Uncertain(_)) || (unknown && !matches!(e, SecretError::Unavailable(_))); + let lingers = |e: &SecretError| was || (unknown && !matches!(e, SecretError::Unavailable(_))); let left = deleted.as_ref().err().is_some_and(lingers); // One known to be there that couldn't be deleted is never signed in with again this session; // one that may be there stays unknown (`remembered` reports only what was found). @@ -322,8 +318,6 @@ fn remember_after(known: &mut Known, username: &str, password: &str, totp: bool, _ => Known::Nothing, }; match deleted { - // A two-factor sign-in was never saved: only the delete of the one before is unconfirmed. - Err(SecretError::Uncertain(_)) if remember && !totp && !was => Some(UNCONFIRMED), // Said first: a password remembered before may still be there. Err(_) if left => Some(NOT_FORGOTTEN), _ if remember && totp => Some(TWO_FACTOR), diff --git a/crates/tiles/src/copernicus/tests.rs b/crates/tiles/src/copernicus/tests.rs index 9563a38f14..2ef81e4e0a 100644 --- a/crates/tiles/src/copernicus/tests.rs +++ b/crates/tiles/src/copernicus/tests.rs @@ -426,12 +426,6 @@ fn a_sign_in_not_to_be_remembered_deletes_the_one_before_and_two_factor_is_never set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Unavailable("none".into()))))); assert_eq!(login_remembering_at(&base, USER, PASSWORD, None, true).unwrap().1, Some(NOT_REMEMBERED)); assert!(signed_in().is_some()); - // A store that can't confirm what it kept: not said to be forgotten, nor claimed remembered. - set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Uncertain("unconfirmed".into()))))); - assert_eq!(login_remembering_at(&base, USER, PASSWORD, None, true).unwrap().1, Some(UNCONFIRMED)); - assert!(!is_remembered()); - // With a one-time code nothing was saved: it's the one before that may still be there. - assert_eq!(login_remembering_at(&base, USER, PASSWORD, Some("123456"), true).unwrap().1, Some(NOT_FORGOTTEN)); } #[test] diff --git a/crates/tiles/src/earthdata.rs b/crates/tiles/src/earthdata.rs index 32726e477f..681f93a4a5 100644 --- a/crates/tiles/src/earthdata.rs +++ b/crates/tiles/src/earthdata.rs @@ -170,9 +170,6 @@ pub const ACCOUNT: &str = "earthdata/token"; pub const NO_STORE: &str = "The token is kept for this session only: there is no credential store here to remember it in."; /// [`login`] with `remember`, when the credential store didn't keep the token. pub const NOT_REMEMBERED: &str = "The token is kept for this session, but the system's credential store didn't remember it."; -/// `login` with `remember`, when the credential store couldn't confirm what it kept. -pub const UNCONFIRMED: &str = - "The token is kept for this session; the system's credential store couldn't confirm whether it remembered it."; /// The credential store didn't delete the token remembered earlier. pub const NOT_FORGOTTEN: &str = "The token remembered on this computer couldn't be deleted from the system's credential store."; @@ -307,7 +304,6 @@ pub fn login(token: &str, remember: bool) -> Result, String let deleted = store.delete(ACCOUNT); REMEMBERED.kept.store(kept && deleted.is_err(), Ordering::SeqCst); match deleted { - Err(rustgis_data::secrets::SecretError::Uncertain(_)) if remember => Ok(Some(UNCONFIRMED)), _ if remember => Ok(Some(NOT_REMEMBERED)), Ok(()) => Ok(None), // A system without a credential store had nowhere to keep one. @@ -1075,11 +1071,6 @@ mod tests { assert_eq!(login(LASTING, true), Ok(Some(NOT_REMEMBERED))); assert!(has_token() && !is_remembered()); assert_eq!(logout(), Err(NOT_FORGOTTEN)); - // A store that can't confirm what it kept: not said to have forgotten it. - set_secret_store(Some(Arc::new(MemorySecrets::failing(SecretError::Uncertain("unconfirmed".into()))))); - assert_eq!(login(LASTING, true), Ok(Some(UNCONFIRMED))); - assert!(has_token() && !is_remembered()); - let _ = logout(); assert!(!has_token()); assert!(login("", true).is_err() && login("two words", true).is_err()); } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index a83083baa0..74bf210c1a 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -303,17 +303,12 @@ fn key_storage_note(app: &RustGisApp, provider: &str) -> String { notes.push(match error { SecretError::Denied => tl!("The system keychain is locked or access was refused."), SecretError::Unavailable(_) => tl!("The system keychain is unavailable."), - SecretError::Uncertain(_) => tl!("The system keychain couldn't confirm the change."), _ => tl!("The system keychain could not complete the request."), }); if *reading { notes.push(tl!("A saved key could not be read. A key entered now will be kept for this session only.")); } else if *deleting { notes.push(tl!("RustGIS could not confirm that any previously saved key was deleted from the system keychain.")); - } else if matches!(error, SecretError::Uncertain(_)) { - notes.push(tl!( - "RustGIS could not confirm whether the key was remembered: it may be there the next time RustGIS starts." - )); } else if !legacy || !plaintext { notes.push(tl!("The key is kept for this session only; it has not been remembered.")); } @@ -1074,25 +1069,6 @@ pub(crate) mod tests { } } - /// A save the store couldn't confirm isn't said to be lost: the key may be there next time. - #[cfg(not(target_arch = "wasm32"))] - #[test] - fn an_unconfirmed_save_is_not_said_to_be_forgotten() { - use rustgis_engine::data::secrets::{MemorySecrets, SecretError}; - let store = std::sync::Arc::new(MemorySecrets::failing(SecretError::Uncertain("synthetic-why".into()))); - let (mut app, _) = keys_app(None, Some(store)); - settle_keys(&mut app); - let mut cfg = app.assistant.agent.as_ref().unwrap().config.clone(); - cfg.key = "synthetic-new".into(); - app.assistant.keys.edit("custom", &cfg.key); - apply_config(&mut app, cfg.clone()); - save_config(&mut app, &cfg, &egui::Context::default()); - settle_keys(&mut app); - let note = key_storage_note(&app, "custom"); - assert!(note.contains("could not confirm whether the key was remembered"), "{note}"); - assert!(!note.contains("has not been remembered") && !note.contains("synthetic-new")); - } - /// A failed replacement is session-only even when a different legacy key still needs migration. #[cfg(not(target_arch = "wasm32"))] #[test] From a3147a9c7199d9b8c325979f1d1334aa9a2170ea Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 11:46:14 -0600 Subject: [PATCH 06/12] test(mobile): the two tests sharing the settings notices take turns Review of #3002: the low-memory test's window says and empties the settings notices while the failed-save test may be checking them, and tests run in parallel. Both now hold one lock. --- apps/rustgis-mobile/src/shell.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 402d3efd9f..f79bd19825 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -1022,6 +1022,13 @@ mod tests { use serde_json::{Value, json}; use std::cell::Cell; + /// Held by a test that queues settings notices and by one that runs the window's events, + /// which say and empty them: the tests run in parallel. + fn settings_notices_held() -> std::sync::MutexGuard<'static, ()> { + static HELD: Mutex<()> = Mutex::new(()); + HELD.lock().unwrap_or_else(|e| e.into_inner()) + } + /// A phone that is busy once asked for a file, and reports the events put in it. #[derive(Default)] struct FakePhone(Cell, RefCell>); @@ -1081,6 +1088,7 @@ mod tests { let (clears, mark) = (cache::clears(), app.session.notice_mark()); let phone = Rc::new(FakePhone::default()); phone.1.borrow_mut().extend([Event::LowMemory, Event::LowMemory]); + let _held = settings_notices_held(); let mut window = App { app, pushed: Vec::new(), @@ -1127,6 +1135,7 @@ mod tests { /// and again after one works; a file set aside is said where it went. #[test] fn a_failed_settings_save_is_said_once_until_one_works() { + let _held = settings_notices_held(); settings_notices().clear(); settings_saved(Err("no room".into())); settings_saved(Err("no room".into())); From a99e7ed6fc6e9b4f3c63b42dd595e2e64ce0cdc9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 13:22:34 -0600 Subject: [PATCH 07/12] fix(mobile): the phone's settings are read once, not on every ask Review of #3002: load_pref read and parsed prefs.json on each call, and the Assistant's settings ask every frame they are up. The map is read on the first ask and kept, as the desktop keeps its snapshot, and a save that works updates it. --- apps/rustgis-mobile/src/shell.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index f79bd19825..e7bdb95e0f 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -890,8 +890,23 @@ fn services(settings: bool, secrets: Option>) -> rustgis_ui rustgis_ui_egui::rustgis_assistant::chatgpt::set_secret_store(secrets.clone()); let mut services = rustgis_ui_egui::Services { secrets, ..Default::default() }; if settings { - services.load_pref = Some(Box::new(|key: &str| read_settings().get(key).and_then(serde_json::Value::as_str).map(str::to_string))); - services.save_pref = Some(Box::new(|key: &str, value: &str| settings_saved(rustgis_engine::prefs::write(key, value)))); + // Read once and kept, as the desktop keeps its snapshot: the Assistant's settings ask for + // one every frame they are up. A save that works updates the copy kept. + let kept: Arc>>> = Arc::default(); + let read = kept.clone(); + services.load_pref = Some(Box::new(move |key: &str| { + let mut kept = read.lock().unwrap_or_else(|e| e.into_inner()); + kept.get_or_insert_with(read_settings).get(key).and_then(serde_json::Value::as_str).map(str::to_string) + })); + services.save_pref = Some(Box::new(move |key: &str, value: &str| { + let result = rustgis_engine::prefs::write(key, value); + if result.is_ok() + && let Some(settings) = kept.lock().unwrap_or_else(|e| e.into_inner()).as_mut() + { + settings.insert(key.to_string(), serde_json::Value::String(value.to_string())); + } + settings_saved(result); + })); } services } From 08ff3ce0de326b6f423dcc840f877be3da035b8c Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 13:53:42 -0600 Subject: [PATCH 08/12] fix(mobile): a failed settings save has the kept copy read again Review of #3002: prefs::write can replace the file and still fail (its folder's sync), so the copy kept is dropped on a failure and read again at the next ask. --- apps/rustgis-mobile/src/shell.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index e7bdb95e0f..859cb1406a 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -891,7 +891,8 @@ fn services(settings: bool, secrets: Option>) -> rustgis_ui let mut services = rustgis_ui_egui::Services { secrets, ..Default::default() }; if settings { // Read once and kept, as the desktop keeps its snapshot: the Assistant's settings ask for - // one every frame they are up. A save that works updates the copy kept. + // one every frame they are up. A save that works updates the copy kept; one that fails + // may still have replaced the file, so the copy is read again. let kept: Arc>>> = Arc::default(); let read = kept.clone(); services.load_pref = Some(Box::new(move |key: &str| { @@ -900,11 +901,15 @@ fn services(settings: bool, secrets: Option>) -> rustgis_ui })); services.save_pref = Some(Box::new(move |key: &str, value: &str| { let result = rustgis_engine::prefs::write(key, value); - if result.is_ok() - && let Some(settings) = kept.lock().unwrap_or_else(|e| e.into_inner()).as_mut() - { - settings.insert(key.to_string(), serde_json::Value::String(value.to_string())); + let mut kept = kept.lock().unwrap_or_else(|e| e.into_inner()); + match (&result, kept.as_mut()) { + (Ok(_), Some(settings)) => { + settings.insert(key.to_string(), serde_json::Value::String(value.to_string())); + } + (Err(_), _) => *kept = None, + (Ok(_), None) => {} } + drop(kept); settings_saved(result); })); } From e1b5d6f2edd1d553904317c07f7a6e0c4a00b866 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 14:08:13 -0600 Subject: [PATCH 09/12] fix(mobile): every settings save has the kept copy read again Review of #3002: a save can merge with the file or set a damaged one aside, so updating the kept copy with the one key could leave it unlike the file. Every save drops it, and the next ask reads the file. --- apps/rustgis-mobile/src/shell.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/apps/rustgis-mobile/src/shell.rs b/apps/rustgis-mobile/src/shell.rs index 859cb1406a..061311ccfc 100644 --- a/apps/rustgis-mobile/src/shell.rs +++ b/apps/rustgis-mobile/src/shell.rs @@ -891,8 +891,8 @@ fn services(settings: bool, secrets: Option>) -> rustgis_ui let mut services = rustgis_ui_egui::Services { secrets, ..Default::default() }; if settings { // Read once and kept, as the desktop keeps its snapshot: the Assistant's settings ask for - // one every frame they are up. A save that works updates the copy kept; one that fails - // may still have replaced the file, so the copy is read again. + // one every frame they are up. A save, which may have merged with, set aside or (failing) + // still replaced the file, has it read again at the next ask. let kept: Arc>>> = Arc::default(); let read = kept.clone(); services.load_pref = Some(Box::new(move |key: &str| { @@ -901,15 +901,7 @@ fn services(settings: bool, secrets: Option>) -> rustgis_ui })); services.save_pref = Some(Box::new(move |key: &str, value: &str| { let result = rustgis_engine::prefs::write(key, value); - let mut kept = kept.lock().unwrap_or_else(|e| e.into_inner()); - match (&result, kept.as_mut()) { - (Ok(_), Some(settings)) => { - settings.insert(key.to_string(), serde_json::Value::String(value.to_string())); - } - (Err(_), _) => *kept = None, - (Ok(_), None) => {} - } - drop(kept); + *kept.lock().unwrap_or_else(|e| e.into_inner()) = None; settings_saved(result); })); } From a619adf37b796f868f3ccdb93d30ed42f013ed16 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 14:18:35 -0600 Subject: [PATCH 10/12] fix(assistant): with no secret store, no saved key is said to be unreadable Review of #3002: on a phone without a store (iOS, or an Android keystore that can't be used), Remember is kept on, and the next start said a saved key couldn't be read although none was ever saved. With no store the note says the key is kept for the session. --- crates/ui-egui/src/assistantpane.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 74bf210c1a..97c86f0cbe 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -305,7 +305,10 @@ fn key_storage_note(app: &RustGisApp, provider: &str) -> String { SecretError::Unavailable(_) => tl!("The system keychain is unavailable."), _ => tl!("The system keychain could not complete the request."), }); - if *reading { + // With no store here (a phone without one), nothing was ever saved to be read. + if *reading && app.services.secrets.is_none() { + notes.push(tl!("A key entered now will be kept for this session only.")); + } else if *reading { notes.push(tl!("A saved key could not be read. A key entered now will be kept for this session only.")); } else if *deleting { notes.push(tl!("RustGIS could not confirm that any previously saved key was deleted from the system keychain.")); @@ -1047,6 +1050,17 @@ pub(crate) mod tests { assert_eq!(prefs.lock().unwrap().get("assistant_key_custom").map(String::as_str), Some("")); } + /// Remember kept on where there is no store at all: no saved key is said to be unreadable. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn remember_with_no_store_says_no_key_was_lost() { + let (mut app, _) = keys_app(None, None); + settle_keys(&mut app); + let note = key_storage_note(&app, "custom"); + assert!(note.contains("unavailable") && note.contains("for this session only"), "{note}"); + assert!(!note.contains("could not be read"), "{note}"); + } + /// A failed new-key write leaves the key in the session and never echoes backend payloads. #[cfg(not(target_arch = "wasm32"))] #[test] From d2eaa05130cf808ab2e8e2c734c3378d32052f7d Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 14:29:11 -0600 Subject: [PATCH 11/12] fix(mobile): the secret store's reasons are worded on the Rust side, and its folder synced Review of #3002: the Java half's reasons were English text that reached the user untranslated. It answers with a code and the system's own reason, and vaultanswer words the code with tl!. After the rename that makes a save, the folder is synced too, as the desktop's settings writer does; the save stands whatever that comes to, since the rename is made. --- .../java/org/rustgis/mobile/SecretVault.java | 30 ++++++++++++------- apps/rustgis-mobile/src/vaultanswer.rs | 27 +++++++++++++++-- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java index 149dd66b94..047eb2b1bf 100644 --- a/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java @@ -12,7 +12,9 @@ * 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" or "failed", each with the reason after a tab. + * "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 { @@ -24,8 +26,8 @@ final class SecretVault { 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\tit was kept by a newer RustGIS: update RustGIS to use it"; - private static final String UNWRITTEN = "failed\tthe app's storage can't be written to"; + private static final String NEWER = "failed\tnewer"; + private static final String UNWRITTEN = "failed\tunwritten"; private SecretVault() {} @@ -41,12 +43,12 @@ static synchronized String load(android.content.Context context, String account) } String[] parts = kept.split("\\.", -1); if (version != VERSION || parts.length != 3) { - return "failed\tthe kept secret is damaged"; + 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\tthe kept secret can't be decrypted: the keystore no longer has its key"; + 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); @@ -60,9 +62,9 @@ static synchronized String load(android.content.Context context, String account) 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\tthe kept secret can't be decrypted: " + reason(e); + return "failed\tundecryptable\t" + reason(e); } catch (RuntimeException e) { - return "failed\t" + reason(e); + return "failed\terror\t" + reason(e); } } @@ -85,7 +87,7 @@ static synchronized String save(android.content.Context context, String account, | java.security.ProviderException e) { return "unavailable\t" + reason(e); } catch (java.security.GeneralSecurityException | RuntimeException e) { - return "failed\t" + reason(e); + return "failed\terror\t" + reason(e); } } @@ -98,7 +100,7 @@ static synchronized String delete(android.content.Context context, String accoun } return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN; } catch (java.io.IOException | RuntimeException e) { - return "failed\t" + reason(e); + return "failed\terror\t" + reason(e); } } @@ -119,10 +121,18 @@ private static String write(java.io.File file, String kept) { 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"; } catch (java.io.IOException | RuntimeException e) { part.delete(); - return UNWRITTEN + ": " + reason(e); + return UNWRITTEN + "\t" + reason(e); } } diff --git a/apps/rustgis-mobile/src/vaultanswer.rs b/apps/rustgis-mobile/src/vaultanswer.rs index 1aed28449c..f62779f97f 100644 --- a/apps/rustgis-mobile/src/vaultanswer.rs +++ b/apps/rustgis-mobile/src/vaultanswer.rs @@ -2,19 +2,37 @@ //! itself so the host's tests cover them. use rustgis_engine::data::secrets::{Secret, SecretError}; +use rustgis_ui_egui::{i18n, tl}; /// Reads the Java half's answer: `ok` (with the secret after a tab, for a load that found one), -/// `none`, or `unavailable` or `failed` with the reason after a tab. +/// `none`, `unavailable` with the system's reason after a tab, or `failed` with a code after a +/// tab and the system's reason, if any, after another ([`failure`]). pub(crate) fn answer(line: &str) -> Result, SecretError> { match line.split_once('\t') { Some(("ok", secret)) => Ok(Some(Secret::new(secret))), Some(("unavailable", why)) => Err(SecretError::Unavailable(why.to_string())), - Some(("failed", why)) => Err(SecretError::Failed(why.to_string())), + Some(("failed", why)) => Err(SecretError::Failed(failure(why))), None if line == "ok" || line == "none" => Ok(None), _ => Err(SecretError::Failed("the Android keystore gave an answer RustGIS doesn't know".into())), } } +/// A failure's reason in the user's language, from the Java half's code and the system's reason. +/// A code this version doesn't know is passed on as it came. +fn failure(why: &str) -> String { + let (code, detail) = why.split_once('\t').unwrap_or((why, "")); + let text = match code { + "newer" => tl!("it was kept by a newer RustGIS: update RustGIS to use it"), + "unwritten" => tl!("the app's storage can't be written to"), + "damaged" => tl!("the kept secret is damaged"), + "no-key" => tl!("the kept secret can't be decrypted: the keystore no longer has its key"), + "undecryptable" => tl!("the kept secret can't be decrypted"), + "error" if !detail.is_empty() => return detail.to_string(), + _ => return why.to_string(), + }; + if detail.is_empty() { text.to_string() } else { i18n::fmt("{reason}: {detail}", &[("reason", text), ("detail", detail)]) } +} + #[cfg(test)] mod tests { use super::*; @@ -25,7 +43,10 @@ mod tests { assert!(answer("ok").unwrap().is_none()); assert!(answer("none").unwrap().is_none()); assert_eq!(answer("unavailable\tno keystore"), Err(SecretError::Unavailable("no keystore".into()))); - assert_eq!(answer("failed\tdamaged"), Err(SecretError::Failed("damaged".into()))); + assert_eq!(answer("failed\tdamaged"), Err(SecretError::Failed("the kept secret is damaged".into()))); + assert_eq!(answer("failed\tunwritten\tENOSPC"), Err(SecretError::Failed("the app's storage can't be written to: ENOSPC".into()))); + assert_eq!(answer("failed\terror\tBadPaddingException"), Err(SecretError::Failed("BadPaddingException".into()))); + assert_eq!(answer("failed\tlater code"), Err(SecretError::Failed("later code".into()))); assert!(matches!(answer("saved"), Err(SecretError::Failed(why)) if why.contains("doesn't know"))); assert!(matches!(answer("later\tx"), Err(SecretError::Failed(why)) if why.contains("doesn't know"))); } From 49438967b13b890cf0edd833bf701f653b06e015 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 14:39:00 -0600 Subject: [PATCH 12/12] fix(assistant): with no secret store, a cleared key isn't said to be left in a keychain Review of #3002: the twin of the read note. Clearing a key where there is no store said a saved key might not have been deleted from the system keychain, though nothing was saved and there is no keychain. --- crates/ui-egui/src/assistantpane.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 97c86f0cbe..cd48c97ec6 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -305,12 +305,14 @@ fn key_storage_note(app: &RustGisApp, provider: &str) -> String { SecretError::Unavailable(_) => tl!("The system keychain is unavailable."), _ => tl!("The system keychain could not complete the request."), }); - // With no store here (a phone without one), nothing was ever saved to be read. - if *reading && app.services.secrets.is_none() { + // With no store here (a phone without one), nothing was ever saved to be read + // or deleted. + let store = app.services.secrets.is_some(); + if *reading && !store { notes.push(tl!("A key entered now will be kept for this session only.")); } else if *reading { notes.push(tl!("A saved key could not be read. A key entered now will be kept for this session only.")); - } else if *deleting { + } else if *deleting && store { notes.push(tl!("RustGIS could not confirm that any previously saved key was deleted from the system keychain.")); } else if !legacy || !plaintext { notes.push(tl!("The key is kept for this session only; it has not been remembered.")); @@ -1059,6 +1061,15 @@ pub(crate) mod tests { let note = key_storage_note(&app, "custom"); assert!(note.contains("unavailable") && note.contains("for this session only"), "{note}"); assert!(!note.contains("could not be read"), "{note}"); + // Nor is a key cleared there said to be still in a keychain. + let mut cfg = app.assistant.agent.as_ref().unwrap().config.clone(); + cfg.key.clear(); + app.assistant.keys.edit("custom", &cfg.key); + apply_config(&mut app, cfg.clone()); + save_config(&mut app, &cfg, &egui::Context::default()); + settle_keys(&mut app); + let note = key_storage_note(&app, "custom"); + assert!(note.contains("for this session only") && !note.contains("deleted"), "{note}"); } /// A failed new-key write leaves the key in the session and never echoes backend payloads.