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
+31 -59
View File
@@ -16,33 +16,12 @@ use serde_json::{json, Value};
use crate::http::{HttpBody, HttpRequest, HttpResponse, HttpTransport, Method};
/// The backend the app talks to unless the user sets another one.
pub const DEFAULT_URL: &str = "https://test.euvinopro.eu";
/// The admin login page, relative to the backend URL.
const LOGIN_PATH: &str = "/euvadm";
const KEY_HEADER: &str = "X-Admin-Api-Key";
/// Longest key label the backend accepts, in characters.
const MAX_LABEL_CHARS: usize = 100;
/// Checks a backend URL the user typed: `https` with a host, no user name,
/// query or fragment. Returns it without trailing slashes.
pub fn normalize_url(url: &str) -> Result<String, String> {
let invalid = || {
"Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben".to_string()
};
let parsed = Url::parse(url.trim()).map_err(|_| invalid())?;
let usable = parsed.scheme() == "https"
&& parsed.host_str().is_some_and(|host| !host.is_empty())
&& parsed.username().is_empty()
&& parsed.password().is_none()
&& parsed.query().is_none()
&& parsed.fragment().is_none();
if !usable {
return Err(invalid());
}
Ok(parsed.as_str().trim_end_matches('/').to_string())
}
/// The label of a key this app creates: "Gesprächsrekorder (<hostname>)",
/// at most 100 characters.
pub fn key_label(hostname: Option<&str>) -> String {
@@ -137,8 +116,8 @@ pub struct BackendClient {
}
impl BackendClient {
/// `base_url` as checked by [`normalize_url`]; a trailing slash is
/// ignored.
/// `base_url` is the backend's https origin (plus path prefix, if
/// any); a trailing slash is ignored.
pub fn new(transport: Arc<dyn HttpTransport>, base_url: &str) -> Self {
Self {
transport,
@@ -146,6 +125,12 @@ impl BackendClient {
}
}
/// The backend this client talks to, without trailing slash. A key it
/// creates belongs to this backend only.
pub fn base_url(&self) -> &str {
&self.base_url
}
/// The admin login page the login window opens.
pub fn login_url(&self) -> String {
format!("{}{LOGIN_PATH}", self.base_url)
@@ -351,8 +336,9 @@ pub trait Login: Send + Sync {
/// Runs the login flow; returns the new (already stored) key, or the
/// message why there is none.
async fn login(&self) -> Result<String, String>;
/// Forgets the stored key the backend refused.
async fn discard_key(&self);
/// Forgets the stored key if it still is `refused`, the key the backend
/// just refused (a login meanwhile may have stored a new one).
async fn discard_key(&self, refused: &str);
}
/// Uploads `text` with the stored key, logging in first when there is no
@@ -372,11 +358,11 @@ pub async fn upload_with_login(
};
match client.upload_transcript(&key, text).await {
Err(BackendError::InvalidKey) => {
login.discard_key().await;
login.discard_key(&key).await;
let key = login.login().await?;
let result = client.upload_transcript(&key, text).await;
if result == Err(BackendError::InvalidKey) {
login.discard_key().await;
login.discard_key(&key).await;
}
result.map_err(|e| e.user_message())
}
@@ -467,31 +453,6 @@ mod tests {
}
}
#[test]
fn urls_must_be_https_with_a_host() {
assert_eq!(
normalize_url(" https://test.euvinopro.eu/ "),
Ok("https://test.euvinopro.eu".to_string())
);
assert_eq!(
normalize_url("https://backend.example:8443/sub/"),
Ok("https://backend.example:8443/sub".to_string())
);
let invalid = "Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben";
for url in [
"",
"test.euvinopro.eu",
"http://test.euvinopro.eu",
"https://",
"https://user:pw@test.euvinopro.eu",
"https://test.euvinopro.eu/?a=1",
"https://test.euvinopro.eu/#x",
"ftp://test.euvinopro.eu",
] {
assert_eq!(normalize_url(url), Err(invalid.to_string()), "{url:?}");
}
}
#[test]
fn the_key_label_names_the_computer_within_100_chars() {
assert_eq!(
@@ -510,8 +471,10 @@ mod tests {
let (_, client) = client();
assert_eq!(client.login_url(), "https://backend.example/euvadm");
assert_eq!(client.keys_page_url(), KEYS);
assert_eq!(client.base_url(), BASE);
let slash = BackendClient::new(Arc::new(FakeTransport::new()), "https://backend.example/");
assert_eq!(slash.login_url(), "https://backend.example/euvadm");
assert_eq!(slash.base_url(), BASE);
}
#[test]
@@ -831,12 +794,12 @@ mod tests {
assert!(!format!("{:?}", stored("euv_secret", None)).contains("euv_secret"));
}
/// Scripted [`Login`]: hands out the given results in order and counts
/// discards.
/// Scripted [`Login`]: hands out the given results in order and
/// records the discarded keys.
struct FakeLogin {
results: Mutex<Vec<Result<String, String>>>,
logins: Mutex<usize>,
discards: Mutex<usize>,
discarded: Mutex<Vec<String>>,
}
impl FakeLogin {
@@ -844,12 +807,19 @@ mod tests {
Self {
results: Mutex::new(results),
logins: Mutex::new(0),
discards: Mutex::new(0),
discarded: Mutex::new(Vec::new()),
}
}
fn counts(&self) -> (usize, usize) {
(*self.logins.lock().unwrap(), *self.discards.lock().unwrap())
(
*self.logins.lock().unwrap(),
self.discarded.lock().unwrap().len(),
)
}
fn discarded(&self) -> Vec<String> {
self.discarded.lock().unwrap().clone()
}
}
@@ -860,8 +830,8 @@ mod tests {
self.results.lock().unwrap().remove(0)
}
async fn discard_key(&self) {
*self.discards.lock().unwrap() += 1;
async fn discard_key(&self, refused: &str) {
self.discarded.lock().unwrap().push(refused.to_string());
}
}
@@ -923,6 +893,7 @@ mod tests {
assert_eq!(id, Ok("crm-9".into()));
assert_eq!(login.counts(), (1, 1));
assert_eq!(login.discarded(), ["euv_old"]);
let keys: Vec<_> = transport
.requests()
.iter()
@@ -943,6 +914,7 @@ mod tests {
assert_eq!(result, Err(BackendError::InvalidKey.user_message()));
assert_eq!(login.counts(), (1, 2));
assert_eq!(login.discarded(), ["euv_old", "euv_new"]);
transport.assert_done();
}
+5
View File
@@ -97,6 +97,9 @@ pub struct CallDetail {
pub speaker_names: BTreeMap<String, String>,
/// The call's speaker merges, by source speaker number.
pub merges: Vec<MergeView>,
/// Whether the transcript is being uploaded right now. Set by the app,
/// which tracks its uploads; `false` from [`CallDetail::of`].
pub uploading: bool,
}
impl CallDetail {
@@ -126,6 +129,7 @@ impl CallDetail {
},
segments,
merges: merge_views(merges, &speaker_names),
uploading: false,
speaker_names,
}
}
@@ -440,6 +444,7 @@ mod tests {
"into_key": "remote:1",
"into_label": "Sprecher 1",
}],
"uploading": false,
})
);
}
+28 -56
View File
@@ -11,8 +11,6 @@ use std::path::Path;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use crate::backend;
/// Executables whose mic use counts as a call (matched case-insensitively).
const DEFAULT_ALLOWLIST: [&str; 6] = [
"ms-teams.exe",
@@ -41,13 +39,14 @@ pub struct Settings {
pub autostart: bool,
pub start_after_secs: u64,
pub end_after_secs: u64,
/// The euvino admin backend transcripts are uploaded to.
pub backend_url: String,
/// Whose backend key is stored (the key itself is in the keyring). Set
/// by the app at login, not by the user.
pub backend_username: Option<String>,
/// When the stored backend key expires. Set by the app at login.
pub backend_key_expires_at: Option<DateTime<Local>>,
/// The backend the stored key was created for: it is sent to that one
/// only. Set by the app at login.
pub backend_key_base_url: Option<String>,
}
impl Default for Settings {
@@ -62,9 +61,9 @@ impl Default for Settings {
autostart: true,
start_after_secs: 3,
end_after_secs: 10,
backend_url: backend::DEFAULT_URL.to_string(),
backend_username: None,
backend_key_expires_at: None,
backend_key_base_url: None,
}
}
}
@@ -86,28 +85,18 @@ impl Settings {
END_AFTER_SECS.end()
));
}
backend::normalize_url(&self.backend_url)?;
Ok(())
}
/// The settings after the user saved `edited` over these: checked, with
/// the backend URL normalized and the backend login (which only the app
/// changes) kept. If the backend URL changed, the login is cleared and
/// `true` returned: the stored key belongs to the old backend and must
/// be discarded.
pub fn edited(&self, mut edited: Settings) -> Result<(Settings, bool), String> {
/// the backend login (which only the app changes) kept, so a settings
/// page loaded before a login cannot undo it.
pub fn edited(&self, mut edited: Settings) -> Result<Settings, String> {
edited.validate()?;
edited.backend_url = backend::normalize_url(&edited.backend_url)?;
let backend_changed = backend::normalize_url(&self.backend_url)
.map_or(true, |current| current != edited.backend_url);
if backend_changed {
edited.backend_username = None;
edited.backend_key_expires_at = None;
} else {
edited.backend_username = self.backend_username.clone();
edited.backend_key_expires_at = self.backend_key_expires_at;
}
Ok((edited, backend_changed))
edited.backend_username = self.backend_username.clone();
edited.backend_key_expires_at = self.backend_key_expires_at;
edited.backend_key_base_url = self.backend_key_base_url.clone();
Ok(edited)
}
/// Reads the settings file. A missing or unreadable file yields the
@@ -158,23 +147,26 @@ mod tests {
assert!(s.autostart);
assert_eq!(s.start_after_secs, 3);
assert_eq!(s.end_after_secs, 10);
assert_eq!(s.backend_url, "https://test.euvinopro.eu");
assert_eq!(s.backend_username, None);
assert_eq!(s.backend_key_expires_at, None);
assert_eq!(s.backend_key_base_url, None);
}
#[test]
fn validate_rejects_a_backend_url_that_is_not_https() {
let s = Settings {
backend_url: "http://test.euvinopro.eu".into(),
..Settings::default()
};
fn a_backend_url_in_an_older_file_is_ignored() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::write(
&path,
r#"{"retention_days": 9, "backend_url": "https://other.example"}"#,
)
.unwrap();
assert_eq!(
s.validate(),
Err(
"Backend-URL: bitte eine https-Adresse wie https://test.euvinopro.eu angeben"
.to_string()
)
Settings::load(&path),
Settings {
retention_days: 9,
..Settings::default()
}
);
}
@@ -186,6 +178,7 @@ mod tests {
.unwrap()
.into(),
),
backend_key_base_url: Some("https://test.euvinopro.eu".into()),
..Settings::default()
}
}
@@ -195,15 +188,14 @@ mod tests {
let current = logged_in();
let edited = Settings {
retention_days: 30,
backend_url: "https://test.euvinopro.eu/".into(),
backend_username: None,
backend_key_expires_at: None,
backend_key_base_url: Some("https://elsewhere.example".into()),
..Settings::default()
};
let (saved, backend_changed) = current.edited(edited).unwrap();
let saved = current.edited(edited).unwrap();
assert!(!backend_changed);
assert_eq!(
saved,
Settings {
@@ -213,28 +205,8 @@ mod tests {
);
}
#[test]
fn an_edit_of_the_backend_url_ends_the_login() {
let edited = Settings {
backend_url: " https://other.example/ ".into(),
..logged_in()
};
let (saved, backend_changed) = logged_in().edited(edited).unwrap();
assert!(backend_changed);
assert_eq!(saved.backend_url, "https://other.example");
assert_eq!(saved.backend_username, None);
assert_eq!(saved.backend_key_expires_at, None);
}
#[test]
fn an_invalid_edit_is_refused() {
let edited = Settings {
backend_url: "test.euvinopro.eu".into(),
..Settings::default()
};
assert!(logged_in().edited(edited).is_err());
let edited = Settings {
start_after_secs: 0,
..Settings::default()