diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index 3e762e0013..d516c685ee 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 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/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..047eb2b1bf --- /dev/null +++ b/apps/rustgis-mobile/java/org/rustgis/mobile/SecretVault.java @@ -0,0 +1,204 @@ +package org.rustgis.mobile; + +/** + * Secrets kept for the Rust side's secret store (src/secrets.rs): each one encrypted with + * AES-GCM under a key in the Android Keystore, made once and never leaving it, and kept in the + * file of its own as "1.." (Base64), the account name bound to it. The files + * are in the app's no-backup folder, which Android's backups leave out (the key couldn't open + * them elsewhere), named by a SHA-256 of the account. A new entry is written whole beside the old + * and renamed over it, so a failed save or removal leaves the entry as it was, and is said as a + * failure. Nothing is kept unencrypted: when the keystore can't be used, the Rust side says so + * and the secret lasts for the session. An entry a newer RustGIS wrote (a version above 1) is + * neither read, written over nor removed. + * + * Each call answers with a line: "ok" (with the secret after a tab, for a load that found one), + * "none" (a load that found none), "unavailable" with the system's reason after a tab, or + * "failed" with a code after a tab (newer, unwritten, damaged, no-key, undecryptable, error) and + * the system's reason, if any, after another: the Rust side words them (src/vaultanswer.rs). + * Called on any thread, one call at a time. + */ +final class SecretVault { + /** The keystore's name for the one key. */ + private static final String KEY = "rustgis-secrets"; + /** The folder, in the app's no-backup folder, the encrypted secrets are kept in. */ + private static final String FOLDER = "rustgis-secrets"; + /** The version of the entries this one writes. */ + private static final int VERSION = 1; + private static final String CIPHER = "AES/GCM/NoPadding"; + private static final int TAG_BITS = 128; + private static final String NEWER = "failed\tnewer"; + private static final String UNWRITTEN = "failed\tunwritten"; + + private SecretVault() {} + + static synchronized String load(android.content.Context context, String account) { + try { + String kept = kept(file(context, account)); + if (kept == null) { + return "none"; + } + int version = version(kept); + if (version > VERSION) { + return NEWER; + } + String[] parts = kept.split("\\.", -1); + if (version != VERSION || parts.length != 3) { + return "failed\tdamaged"; + } + javax.crypto.SecretKey key = key(false); + if (key == null) { + // Restored to another device, say: the key never leaves the one it was made on. + return "failed\tno-key"; + } + byte[] iv = android.util.Base64.decode(parts[1], android.util.Base64.NO_WRAP); + byte[] sealed = android.util.Base64.decode(parts[2], android.util.Base64.NO_WRAP); + javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER); + cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new javax.crypto.spec.GCMParameterSpec(TAG_BITS, iv)); + cipher.updateAAD(account.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + byte[] plain = cipher.doFinal(sealed); + return "ok\t" + new String(plain, java.nio.charset.StandardCharsets.UTF_8); + } catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException + | java.security.ProviderException e) { + return "unavailable\t" + reason(e); + } catch (java.security.GeneralSecurityException | IllegalArgumentException e) { + // A damaged entry, or one sealed with a key the keystore no longer has. + return "failed\tundecryptable\t" + reason(e); + } catch (RuntimeException e) { + return "failed\terror\t" + reason(e); + } + } + + static synchronized String save(android.content.Context context, String account, String value) { + try { + java.io.File file = file(context, account); + if (version(kept(file)) > VERSION) { + return NEWER; + } + javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER); + // The keystore chooses the nonce, a new one for each secret. + cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key(true)); + // Bound to its account: an entry copied under another account doesn't decrypt. + cipher.updateAAD(account.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + byte[] sealed = cipher.doFinal(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String kept = VERSION + "." + android.util.Base64.encodeToString(cipher.getIV(), android.util.Base64.NO_WRAP) + "." + + android.util.Base64.encodeToString(sealed, android.util.Base64.NO_WRAP); + return write(file, kept); + } catch (java.security.KeyStoreException | java.security.NoSuchProviderException | java.io.IOException + | java.security.ProviderException e) { + return "unavailable\t" + reason(e); + } catch (java.security.GeneralSecurityException | RuntimeException e) { + return "failed\terror\t" + reason(e); + } + } + + static synchronized String delete(android.content.Context context, String account) { + try { + java.io.File file = file(context, account); + String before = kept(file); + if (version(before) > VERSION) { + return NEWER; + } + return before == null || file.delete() || !file.exists() ? "ok" : UNWRITTEN; + } catch (java.io.IOException | RuntimeException e) { + return "failed\terror\t" + reason(e); + } + } + + /** + * Writes the account's entry whole to a file beside its own and renames it over it, so the + * entry is either the new one or, after a failure, still the one before. + */ + private static String write(java.io.File file, String kept) { + java.io.File folder = file.getParentFile(); + java.io.File part = new java.io.File(folder, file.getName() + ".part"); + try { + if (folder == null || !(folder.isDirectory() || folder.mkdirs())) { + return UNWRITTEN; + } + try (java.io.FileOutputStream out = new java.io.FileOutputStream(part)) { + out.write(kept.getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + // On the disk before the rename makes it the entry. + out.getFD().sync(); + } + java.nio.file.Files.move(part.toPath(), file.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE); + // The rename on the disk too. It is made whatever this comes to: only a power cut + // before Android writes the folder could still undo it. + try (java.nio.channels.FileChannel dir = + java.nio.channels.FileChannel.open(folder.toPath(), java.nio.file.StandardOpenOption.READ)) { + dir.force(true); + } catch (java.io.IOException | RuntimeException e) { + android.util.Log.w("rustgis", "the secrets' folder wasn't synced: " + reason(e)); + } + return "ok"; + } catch (java.io.IOException | RuntimeException e) { + part.delete(); + return UNWRITTEN + "\t" + reason(e); + } + } + + /** The account's entry, or null when there is none. */ + private static String kept(java.io.File file) throws java.io.IOException { + if (!file.exists()) { + return null; + } + byte[] bytes = java.nio.file.Files.readAllBytes(file.toPath()); + return new String(bytes, java.nio.charset.StandardCharsets.US_ASCII); + } + + /** The account's file: its name a SHA-256 of the account, as an account may hold any character. */ + private static java.io.File file(android.content.Context context, String account) { + byte[] digest; + try { + digest = java.security.MessageDigest.getInstance("SHA-256").digest(account.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } catch (java.security.NoSuchAlgorithmException e) { + // Every Android has SHA-256. + throw new IllegalStateException(e); + } + StringBuilder name = new StringBuilder(); + for (byte b : digest) { + name.append(String.format(java.util.Locale.ROOT, "%02x", b)); + } + return new java.io.File(new java.io.File(context.getApplicationContext().getNoBackupFilesDir(), FOLDER), name.toString()); + } + + /** The version an entry was written in: the number before its first point, 0 if none. */ + private static int version(String kept) { + if (kept == null) { + return 0; + } + int dot = kept.indexOf('.'); + try { + return dot <= 0 ? 0 : Integer.parseInt(kept.substring(0, dot)); + } catch (NumberFormatException e) { + return 0; + } + } + + /** The keystore's key, made the first time it is asked for when {@code make}; else null when there is none. */ + private static synchronized javax.crypto.SecretKey key(boolean make) throws java.security.GeneralSecurityException, java.io.IOException { + java.security.KeyStore store = java.security.KeyStore.getInstance("AndroidKeyStore"); + store.load(null); + java.security.Key key = store.getKey(KEY, null); + if (key instanceof javax.crypto.SecretKey) { + return (javax.crypto.SecretKey) key; + } + if (!make) { + return null; + } + javax.crypto.KeyGenerator maker = javax.crypto.KeyGenerator.getInstance( + android.security.keystore.KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); + maker.init(new android.security.keystore.KeyGenParameterSpec.Builder(KEY, + android.security.keystore.KeyProperties.PURPOSE_ENCRYPT | android.security.keystore.KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(android.security.keystore.KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(android.security.keystore.KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build()); + return maker.generateKey(); + } + + /** What went wrong, on one line. */ + private static String reason(Throwable e) { + String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + return message.replaceAll("[\\t\\r\\n]", " "); + } +} 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..f1e7c25d64 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,10 @@ mod shell; mod android; #[cfg(target_os = "android")] mod phone; +#[cfg(target_os = "android")] +mod secrets; +#[cfg(any(target_os = "android", test))] +mod vaultanswer; #[cfg(target_os = "ios")] mod ios; 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..9102cacb04 --- /dev/null +++ b/apps/rustgis-mobile/src/secrets.rs @@ -0,0 +1,79 @@ +//! 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 crate::vaultanswer::answer; +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())) + } +} + +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..061311ccfc 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,10 @@ impl App

{ for text in self.refusals.borrow_mut().drain(..) { self.app.session.notify(text, true); } + 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 }; // Positions out of sight follow what the interface asks for (a track being recorded). if self.app.keep_locating != self.keeping { @@ -691,6 +696,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 +851,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 +870,89 @@ 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 { + // Read once and kept, as the desktop keeps its snapshot: the Assistant's settings ask for + // 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| { + 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); + *kept.lock().unwrap_or_else(|e| e.into_inner()) = None; + settings_saved(result); + })); + } + 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. @@ -949,6 +1034,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>); @@ -1008,6 +1100,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(), @@ -1050,6 +1143,24 @@ 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() { + let _held = settings_notices_held(); + 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/apps/rustgis-mobile/src/vaultanswer.rs b/apps/rustgis-mobile/src/vaultanswer.rs new file mode 100644 index 0000000000..f62779f97f --- /dev/null +++ b/apps/rustgis-mobile/src/vaultanswer.rs @@ -0,0 +1,53 @@ +//! 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}; +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`, `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(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::*; + + #[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("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"))); + } +} diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 74bf210c1a..cd48c97ec6 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -305,9 +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."), }); - if *reading { + // 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.")); @@ -1047,6 +1052,26 @@ 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}"); + // 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. #[cfg(not(target_arch = "wasm32"))] #[test] 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