fix #14740: fixed backend url per build, key bound to its server

- the backend URL is no longer a setting: one constant per build
  (release/dev) in src-tauri/src/backend.rs; Settings shows the server
  read-only; an old backend_url in settings.json is ignored
- the stored key records the backend it was created for; a key of
  another backend is discarded before any use and never stored
- a refused key is discarded only if it still is the stored one
- the keyring is never called while the settings are locked
- one upload per call at a time, also visible after a view switch
- opener plugin without its link-click script (it also ran in the
  remote login page); a login error says to reload the login page

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-06 15:18:05 +01:00
co-authored by Claude Opus 5.5
parent f045424e97
commit 3358de7888
10 changed files with 399 additions and 217 deletions
+72 -17
View File
@@ -20,7 +20,8 @@ use recorder_core::model::CallId;
use serde::Serialize;
use tauri::webview::PageLoadEvent;
use tauri::{
AppHandle, Emitter, Manager, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent,
AppHandle, Emitter, Manager, State, Url, WebviewUrl, WebviewWindow, WebviewWindowBuilder,
WindowEvent,
};
use tauri_plugin_opener::OpenerExt;
use tokio::sync::oneshot;
@@ -28,6 +29,20 @@ use tokio::sync::oneshot;
use crate::processing;
use crate::state::AppState;
// The backend this build talks to: the one place to change it. It is not a
// setting; a key created on one backend is never sent to another.
/// Release builds. Switch to "https://backend.euvinopro.eu" here, then
/// release, once that backend is live.
const RELEASE_BACKEND_URL: &str = "https://test.euvinopro.eu";
/// Debug builds (`cargo tauri dev`) always use the test backend.
const DEV_BACKEND_URL: &str = "https://test.euvinopro.eu";
/// The backend of this build (no trailing slash).
pub const BACKEND_URL: &str = if cfg!(debug_assertions) {
DEV_BACKEND_URL
} else {
RELEASE_BACKEND_URL
};
/// Label of the login window.
pub const LOGIN_WINDOW: &str = "backend-login";
const CANCELLED: &str = "Anmeldung abgebrochen";
@@ -85,6 +100,14 @@ impl Drop for CreatingClaim<'_> {
}
}
/// Answer of `backend_server`: the backend of this build.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct BackendServer {
pub base_url: String,
/// Where the admin manages their keys.
pub keys_url: String,
}
/// Answer of `backend_status`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct BackendStatus {
@@ -94,8 +117,6 @@ pub struct BackendStatus {
/// `false` if the stored key could not be checked; username and expiry
/// are then the stored ones.
pub reachable: bool,
/// Where the admin manages their keys.
pub keys_url: String,
}
/// Payload of `backend-login-error`: creating the key failed, the login
@@ -105,8 +126,18 @@ struct LoginError {
message: String,
}
/// The backend this build talks to, for the settings (no network).
#[tauri::command]
pub fn backend_server(state: State<'_, AppState>) -> BackendServer {
BackendServer {
base_url: state.backend_url().to_string(),
keys_url: state.backend_client().keys_page_url(),
}
}
/// Whether a backend key is stored, and whose it is: checked with the
/// backend. A key the backend refuses is discarded.
/// backend. A key the backend refuses, or one of another backend, is
/// discarded.
#[tauri::command]
pub async fn backend_status(app: AppHandle) -> CmdResult<BackendStatus> {
let state = app.state::<AppState>();
@@ -117,7 +148,6 @@ pub async fn backend_status(app: AppHandle) -> CmdResult<BackendStatus> {
username: None,
expires_at: None,
reachable: true,
keys_url: client.keys_page_url(),
};
let Some(stored) = stored else {
return Ok(status);
@@ -131,7 +161,11 @@ pub async fn backend_status(app: AppHandle) -> CmdResult<BackendStatus> {
}
KeyCheck::Invalid => {
log::info!("backend: the stored key was refused, discarding it");
blocking(&app, |state| state.discard_backend_key()).await?;
let refused = stored.key;
blocking(&app, move |state| {
state.discard_refused_backend_key(&refused)
})
.await?;
}
KeyCheck::Unknown(e) => {
log::info!(
@@ -175,24 +209,33 @@ pub fn open_backend_keys_page(app: AppHandle) -> CmdResult<()> {
/// "Transkript hochladen": uploads the call's transcript as the user sees
/// it, logging in first if needed, and records the CRM's id on the call.
/// One upload per call at a time; `call-updated` tells the views when it
/// starts and ends.
#[tauri::command]
pub async fn upload_transcript(app: AppHandle, id: CallId) -> CmdResult<()> {
let state = app.state::<AppState>();
let claim = state.claim_upload(id)?;
processing::emit_updated(&app, id);
let result = upload(&app, &state, id).await;
drop(claim);
processing::emit_updated(&app, id);
result
}
async fn upload(app: &AppHandle, state: &AppState, id: CallId) -> CmdResult<()> {
let detail = state.call_detail(id)?;
if detail.call.transcribed_at.is_none() {
return Err("Das Gespräch ist noch nicht transkribiert".to_string());
}
let text = detail.upload_text()?;
let client = state.backend_client();
let stored = blocking(&app, |state| Ok(state.backend_key())).await?;
let stored = blocking(app, |state| Ok(state.backend_key())).await?;
let login = AppLogin { app: app.clone() };
let crm_id = backend::upload_with_login(&client, &login, stored, Local::now(), &text)
.await
.inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?;
log::info!("call {id}: transcript uploaded (CRM id {crm_id})");
state.mark_uploaded(id, &crm_id)?;
processing::emit_updated(&app, id);
Ok(())
state.mark_uploaded(id, &crm_id)
}
/// [`Login`] through the login window, for the upload.
@@ -206,12 +249,20 @@ impl Login for AppLogin {
login(&self.app).await
}
async fn discard_key(&self) {
log::info!("backend: the key was refused, discarding it");
if let Err(e) = blocking(&self.app, |state| state.discard_backend_key()).await {
log::error!("backend: {e}");
async fn discard_key(&self, refused: &str) {
let refused = refused.to_string();
match blocking(&self.app, move |state| {
state.discard_refused_backend_key(&refused)
})
.await
{
Ok(true) => {
log::info!("backend: the key was refused, discarded it");
emit_changed(&self.app);
}
Ok(false) => log::info!("backend: the refused key was already replaced"),
Err(e) => log::error!("backend: {e}"),
}
emit_changed(&self.app);
}
}
@@ -294,6 +345,7 @@ fn create_key(window: WebviewWindow, client: BackendClient) {
}
LoginStep::Retry(message) => {
log::warn!("backend: creating the key failed: {message}");
let message = format!("{message} – bitte die Seite im Anmeldefenster neu laden");
let _ = app.emit_to("main", "backend-login-error", LoginError { message });
}
}
@@ -340,8 +392,11 @@ async fn store_key(app: &AppHandle, client: &BackendClient, key: &NewKey) -> Res
None
}
};
let key = key.clone();
blocking(app, move |state| state.store_backend_key(&key, username)).await?;
let (key, base_url) = (key.clone(), client.base_url().to_string());
blocking(app, move |state| {
state.store_backend_key(&key, &base_url, username)
})
.await?;
log::info!("backend: logged in, key stored");
Ok(())
}
+9 -16
View File
@@ -37,23 +37,16 @@ pub fn get_settings(state: State<'_, AppState>) -> Settings {
state.settings()
}
/// Saves the settings. A changed backend URL ends the backend login
/// (`backend-changed`). May delete from the keyring, so it runs on the
/// blocking pool.
#[tauri::command]
pub async fn save_settings(app: AppHandle, settings: Settings) -> CmdResult<()> {
blocking(app, move |app| {
let autostart = settings.autostart;
let backend_changed = app.state::<AppState>().save_settings(settings)?;
apply_autostart(app, autostart);
if backend_changed {
if let Err(e) = app.emit_to("main", "backend-changed", ()) {
log::error!("could not emit backend-changed: {e}");
}
}
Ok(())
})
.await
pub fn save_settings(
app: AppHandle,
state: State<'_, AppState>,
settings: Settings,
) -> CmdResult<()> {
let autostart = settings.autostart;
state.save_settings(settings)?;
apply_autostart(&app, autostart);
Ok(())
}
/// Stores `key` in the keyring; an empty key deletes the entry.
+8 -2
View File
@@ -36,8 +36,13 @@ pub fn run() {
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_updater::Builder::new().build())
// Only for `open_backend_keys_page`: no capability grants the UI
// the plugin's commands.
.plugin(tauri_plugin_opener::init())
// the plugin's commands, and no link-click script is injected (it
// would also run in the remote login page).
.plugin(
tauri_plugin_opener::Builder::new()
.open_js_links_on_click(false)
.build(),
)
.setup(|app| {
// Release builds log to a file in the app log directory (on
// Windows %LOCALAPPDATA%\eu.euvino.callrecorder\logs), debug
@@ -147,6 +152,7 @@ pub fn run() {
commands::merge_speakers,
commands::unmerge_speaker,
commands::rename_call,
backend::backend_server,
backend::backend_status,
backend::backend_login,
backend::backend_logout,
+216 -46
View File
@@ -157,6 +157,26 @@ pub struct AppState {
/// Set while a recording starts or the devices are tested, so neither
/// runs twice and `current` is never locked for longer than a moment.
devices_busy: AtomicBool,
/// The backend this build talks to ([`crate::backend::BACKEND_URL`]).
backend_url: String,
/// Held while the stored backend key and its login change, so a
/// compare-and-delete never removes a key stored meanwhile.
backend_key_lock: Mutex<()>,
/// Calls whose transcript is being uploaded; one upload per call.
uploading: Mutex<HashSet<CallId>>,
}
/// An upload reserved with [`AppState::claim_upload`]; released when
/// dropped, also if the upload fails or panics.
pub struct UploadClaim<'a> {
state: &'a AppState,
id: CallId,
}
impl Drop for UploadClaim<'_> {
fn drop(&mut self) {
lock(&self.state.uploading).remove(&self.id);
}
}
/// Releases [`AppState::devices_busy`] when dropped.
@@ -189,6 +209,9 @@ impl AppState {
pending_prompts: Mutex::new(VecDeque::new()),
processing: Mutex::new(HashSet::new()),
devices_busy: AtomicBool::new(false),
backend_url: crate::backend::BACKEND_URL.to_string(),
backend_key_lock: Mutex::new(()),
uploading: Mutex::new(HashSet::new()),
}
}
@@ -198,50 +221,78 @@ impl AppState {
/// Validates, saves and applies the settings the user edited; the
/// detector picks up the new allowlist and delays immediately. The
/// backend login is kept, unless the backend URL changed: then its key
/// is discarded (it belongs to the old backend) and `true` returned.
/// Deletes from the keyring, so call it off the UI thread.
pub fn save_settings(&self, edited: Settings) -> Result<bool, String> {
/// backend login (managed by the app) is kept.
pub fn save_settings(&self, edited: Settings) -> Result<(), String> {
let mut current = lock(&self.settings);
let (settings, backend_changed) = current.edited(edited)?;
if backend_changed {
self.secrets
.delete(Service::Backend)
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
}
let settings = current.edited(edited)?;
save(&settings, &self.settings_path)?;
lock(&self.detector).set_config(detector_config(&settings));
*current = settings;
Ok(backend_changed)
Ok(())
}
/// Client of the configured backend.
/// The backend this build talks to.
pub fn backend_url(&self) -> &str {
&self.backend_url
}
/// Client of this build's backend.
pub fn backend_client(&self) -> BackendClient {
BackendClient::new(self.transport.clone(), &self.settings().backend_url)
BackendClient::new(self.transport.clone(), &self.backend_url)
}
/// The stored backend key with its expiry. Reads the keyring, so call
/// it off the UI thread.
/// The stored backend key with its expiry, if it was created for this
/// build's backend. A key of another backend is discarded instead (as
/// if expired), so it is never sent anywhere else. Reads the keyring,
/// so call it off the UI thread.
pub fn backend_key(&self) -> Option<StoredKey> {
let _key_lock = lock(&self.backend_key_lock);
let key = self
.secrets
.get(Service::Backend)
.filter(|key| !key.trim().is_empty())?;
let settings = self.settings();
if settings.backend_key_base_url.as_deref() != Some(self.backend_url.as_str()) {
log::info!(
"backend: the stored key belongs to {:?}, not {:?}: discarding it",
settings.backend_key_base_url,
self.backend_url
);
if let Err(e) = self.forget_backend_key() {
log::error!("backend: {e}");
}
return None;
}
Some(StoredKey {
key,
expires_at: self.settings().backend_key_expires_at,
expires_at: settings.backend_key_expires_at,
})
}
/// Stores a key the login created (in the keyring) and whose it is and
/// when it expires (in the settings).
pub fn store_backend_key(&self, key: &NewKey, username: Option<String>) -> Result<(), String> {
/// Stores a key the login created for the backend at `base_url` (in
/// the keyring) with whose it is, when it expires and its backend (in
/// the settings). A key of another backend than this build's is
/// refused and nothing stored.
pub fn store_backend_key(
&self,
key: &NewKey,
base_url: &str,
username: Option<String>,
) -> Result<(), String> {
let base_url = base_url.trim_end_matches('/');
if base_url != self.backend_url {
return Err(format!(
"Der Schlüssel gehört zu einem anderen Server ({base_url}) und wurde nicht gespeichert."
));
}
let _key_lock = lock(&self.backend_key_lock);
self.secrets
.set(Service::Backend, &key.key)
.map_err(|e| format!("Backend-Schlüssel konnte nicht gespeichert werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = username;
s.backend_key_expires_at = Some(key.expires_at);
s.backend_key_base_url = Some(base_url.to_string());
})
}
@@ -254,17 +305,51 @@ impl AppState {
})
}
/// Forgets the backend key (keyring) and its login (settings).
/// "Abmelden": forgets the backend key (keyring) and its login
/// (settings).
pub fn discard_backend_key(&self) -> Result<(), String> {
let _key_lock = lock(&self.backend_key_lock);
self.forget_backend_key()
}
/// Forgets the stored backend key only if it still is `refused`, the
/// key the backend just refused; a key stored meanwhile (by a login)
/// stays. Returns whether it was forgotten.
pub fn discard_refused_backend_key(&self, refused: &str) -> Result<bool, String> {
let _key_lock = lock(&self.backend_key_lock);
if self.secrets.get(Service::Backend).as_deref() != Some(refused) {
return Ok(false);
}
self.forget_backend_key().map(|()| true)
}
/// Deletes the key and its login; the caller holds `backend_key_lock`.
/// The keyring is never called while the settings are locked.
fn forget_backend_key(&self) -> Result<(), String> {
self.secrets
.delete(Service::Backend)
.map_err(|e| format!("Backend-Schlüssel konnte nicht entfernt werden: {e}"))?;
self.update_settings(|s| {
s.backend_username = None;
s.backend_key_expires_at = None;
s.backend_key_base_url = None;
})
}
/// Reserves call `id` for one upload; released when the claim is
/// dropped. A second upload of the same call is refused meanwhile.
pub fn claim_upload(&self, id: CallId) -> Result<UploadClaim<'_>, String> {
if !lock(&self.uploading).insert(id) {
return Err("Wird bereits hochgeladen".to_string());
}
Ok(UploadClaim { state: self, id })
}
/// Whether call `id`'s transcript is being uploaded.
pub fn is_uploading(&self, id: CallId) -> bool {
lock(&self.uploading).contains(&id)
}
/// Changes and saves settings the app manages itself; saves only if
/// something changed.
fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> {
@@ -511,14 +596,16 @@ impl AppState {
Ok(calls.iter().map(CallListItem::of).collect())
}
/// The selected call with its transcript (speaker merges applied) and
/// speaker names.
/// The selected call with its transcript (speaker merges applied),
/// speaker names and whether it is being uploaded.
pub fn call_detail(&self, id: CallId) -> Result<CallDetail, String> {
let call = self.find_call(id)?;
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?;
Ok(CallDetail::of(&call, &segments, names, &merges))
let mut detail = CallDetail::of(&call, &segments, names, &merges);
detail.uploading = self.is_uploading(id);
Ok(detail)
}
/// Renames a speaker of call `id`; a blank `name` restores the default
@@ -1337,7 +1424,7 @@ mod tests {
end_after_secs: 30,
..Settings::default()
};
assert_eq!(f.state.save_settings(valid.clone()), Ok(false));
assert_eq!(f.state.save_settings(valid.clone()), Ok(()));
assert_eq!(f.state.settings(), valid);
}
@@ -1348,13 +1435,19 @@ mod tests {
}
}
const BASE: &str = crate::backend::BACKEND_URL;
#[test]
fn a_stored_backend_key_comes_with_its_login() {
fn a_stored_backend_key_comes_with_its_login_and_server() {
let f = fixture();
assert_eq!(f.state.backend_key(), None);
f.state
.store_backend_key(&new_key("euv_k"), Some("hinrichs".into()))
.store_backend_key(
&new_key("euv_k"),
&format!("{BASE}/"),
Some("hinrichs".into()),
)
.unwrap();
let expires_at = Local.with_ymd_and_hms(2027, 11, 6, 10, 0, 0).unwrap();
@@ -1368,16 +1461,55 @@ mod tests {
let saved = Settings::load(&f.dir.path().join("settings.json"));
assert_eq!(saved.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(saved.backend_key_expires_at, Some(expires_at));
assert_eq!(saved.backend_key_base_url.as_deref(), Some(BASE));
assert!(!fs::read_to_string(f.dir.path().join("settings.json"))
.unwrap()
.contains("euv_k"));
assert_eq!(f.state.settings(), saved);
}
#[test]
fn a_key_of_another_server_is_not_stored() {
let f = fixture();
let err = f
.state
.store_backend_key(&new_key("euv_k"), "https://other.example", None)
.unwrap_err();
assert!(err.contains("anderen Server"), "{err}");
assert_eq!(f.state.secrets.get(Service::Backend), None);
assert_eq!(f.state.settings(), Settings::default());
}
#[test]
fn a_stored_key_of_another_server_is_discarded_before_use() {
for recorded in [Some("https://other.example"), None] {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
// As if stored by a build for another backend.
f.state
.update_settings(|s| s.backend_key_base_url = recorded.map(str::to_string))
.unwrap();
assert_eq!(f.state.backend_key(), None, "{recorded:?}");
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
assert_eq!(settings.backend_key_base_url, None);
}
}
#[test]
fn the_backend_login_is_refreshed_from_the_key_info() {
let f = fixture();
f.state.store_backend_key(&new_key("euv_k"), None).unwrap();
f.state
.store_backend_key(&new_key("euv_k"), BASE, None)
.unwrap();
let later = Local.with_ymd_and_hms(2028, 1, 1, 0, 0, 0).unwrap();
f.state
@@ -1393,13 +1525,14 @@ mod tests {
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_expires_at, Some(later));
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
}
#[test]
fn a_discarded_backend_key_is_gone_with_its_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), Some("hinrichs".into()))
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
f.state.discard_backend_key().unwrap();
@@ -1409,13 +1542,33 @@ mod tests {
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_expires_at, None);
assert_eq!(settings.backend_key_base_url, None);
}
#[test]
fn saving_settings_keeps_the_backend_login_unless_the_url_changes() {
fn only_the_refused_key_is_discarded() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), Some("hinrichs".into()))
.store_backend_key(&new_key("euv_new"), BASE, None)
.unwrap();
// A login stored a new key after the old one was refused.
assert_eq!(f.state.discard_refused_backend_key("euv_old"), Ok(false));
assert_eq!(
f.state.backend_key().map(|k| k.key).as_deref(),
Some("euv_new")
);
assert_eq!(f.state.discard_refused_backend_key("euv_new"), Ok(true));
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.settings().backend_key_base_url, None);
}
#[test]
fn saving_settings_keeps_the_backend_login() {
let f = fixture();
f.state
.store_backend_key(&new_key("euv_k"), BASE, Some("hinrichs".into()))
.unwrap();
// The settings page sends what it loaded, maybe before the login.
let edited = Settings {
@@ -1423,28 +1576,45 @@ mod tests {
..Settings::default()
};
assert_eq!(f.state.save_settings(edited.clone()), Ok(false));
assert!(f.state.backend_key().is_some());
assert_eq!(
f.state.settings().backend_username.as_deref(),
Some("hinrichs")
);
assert_eq!(f.state.settings().retention_days, 14);
assert_eq!(f.state.save_settings(edited), Ok(()));
let other_backend = Settings {
backend_url: "https://other.example/".into(),
..edited
};
assert_eq!(f.state.save_settings(other_backend), Ok(true));
assert_eq!(f.state.backend_key(), None);
assert_eq!(f.state.settings().backend_url, "https://other.example");
assert_eq!(f.state.settings().backend_username, None);
assert!(f.state.backend_key().is_some());
let settings = f.state.settings();
assert_eq!(settings.backend_username.as_deref(), Some("hinrichs"));
assert_eq!(settings.backend_key_base_url.as_deref(), Some(BASE));
assert_eq!(settings.retention_days, 14);
}
#[test]
fn the_backend_is_fixed_per_build() {
let f = fixture();
assert_eq!(f.state.backend_url(), "https://test.euvinopro.eu");
assert_eq!(
f.state.backend_client().login_url(),
"https://other.example/euvadm"
"https://test.euvinopro.eu/euvadm"
);
}
#[test]
fn a_call_is_uploaded_once_at_a_time() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
assert!(!f.state.call_detail(id).unwrap().uploading);
let claim = f.state.claim_upload(id).unwrap();
assert!(f.state.is_uploading(id));
assert!(f.state.call_detail(id).unwrap().uploading);
assert_eq!(
f.state.claim_upload(id).err(),
Some("Wird bereits hochgeladen".to_string())
);
assert!(f.state.claim_upload(id + 1).is_ok(), "other calls are free");
drop(claim);
assert!(!f.state.is_uploading(id));
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn an_upload_is_recorded_on_the_call() {
let f = fixture();