feat #14740: admin backend client and transcript upload text
recorder-core side of linking the app to the euvino admin backend: - backend: BackendClient (create a key with the admin's session cookie, check a key, upload a transcript; redirects never followed), German error messages, the login-window decision (LoginStep) and the upload flow with login, one retry after a refused key and no loop - call_view: the upload text (header + merged, renamed lines) and the upload fields on the call - store: schema v3 with crm_transcript_id and uploaded_at - settings: backend_url (validated https), the app-managed login fields, kept on edit and cleared when the backend URL changes - secrets: Service::Backend; http: per-request follow_redirects; FakeTransport can script transport errors Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,991 @@
|
||||
//! The euvino admin backend: an admin's API key, minted with their browser
|
||||
//! session, and the upload of call transcripts to the CRM with that key.
|
||||
//!
|
||||
//! The key goes only into the `X-Admin-Api-Key` header of `/admin/api/…`
|
||||
//! requests, the session cookie only into the one request that creates the
|
||||
//! key. Neither is ever logged or part of an error message.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Duration, Local};
|
||||
use reqwest::Url;
|
||||
use serde::Deserialize;
|
||||
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 {
|
||||
let app = "Gesprächsrekorder";
|
||||
let label = match hostname.map(str::trim).filter(|host| !host.is_empty()) {
|
||||
Some(host) => format!("{app} ({host})"),
|
||||
None => app.to_string(),
|
||||
};
|
||||
label.chars().take(MAX_LABEL_CHARS).collect()
|
||||
}
|
||||
|
||||
/// A key the backend just created. The key is shown only in this response.
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct NewKey {
|
||||
pub key: String,
|
||||
pub expires_at: DateTime<Local>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for NewKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("NewKey")
|
||||
.field("key", &"<redacted>")
|
||||
.field("expires_at", &self.expires_at)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the backend knows about a key (`GET /admin/api/key`).
|
||||
#[derive(Deserialize, Clone, Debug, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KeyInfo {
|
||||
pub label: String,
|
||||
/// The key's last characters, safe to show.
|
||||
pub hint: String,
|
||||
pub username: String,
|
||||
pub created_at: DateTime<Local>,
|
||||
pub expires_at: DateTime<Local>,
|
||||
}
|
||||
|
||||
/// Why a backend request failed.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BackendError {
|
||||
/// Creating a key: the session is not (yet) logged in (redirect to the
|
||||
/// login page, or 401).
|
||||
NotLoggedIn,
|
||||
/// Creating a key: the session cannot create one (not an admin, or an
|
||||
/// impersonation).
|
||||
Forbidden,
|
||||
/// The key is unknown, expired or deleted, or its admin was disabled.
|
||||
InvalidKey,
|
||||
/// The backend cannot check the key right now (503).
|
||||
Unavailable,
|
||||
/// The backend refused the transcript (400/422), with its reason.
|
||||
Rejected(String),
|
||||
/// Any other status, with the backend's `error` message if it sent one.
|
||||
Http(u16, String),
|
||||
/// The backend could not be reached.
|
||||
Transport(String),
|
||||
}
|
||||
|
||||
impl BackendError {
|
||||
/// The German message shown to the user.
|
||||
pub fn user_message(&self) -> String {
|
||||
match self {
|
||||
BackendError::NotLoggedIn => "Nicht beim Backend angemeldet".to_string(),
|
||||
BackendError::Forbidden => "Diese Anmeldung kann keinen Schlüssel erzeugen (z. B. bei \
|
||||
Impersonation) – bitte als Admin selbst anmelden."
|
||||
.to_string(),
|
||||
BackendError::InvalidKey => {
|
||||
"Backend-Schlüssel ungültig oder abgelaufen – bitte neu anmelden.".to_string()
|
||||
}
|
||||
BackendError::Unavailable => "Backend kann die Anmeldung gerade nicht prüfen – bitte \
|
||||
später erneut versuchen."
|
||||
.to_string(),
|
||||
BackendError::Rejected(reason) => {
|
||||
format!("Backend hat das Transkript abgelehnt: {reason}")
|
||||
}
|
||||
BackendError::Http(status, msg) if msg.is_empty() => {
|
||||
format!("Backend-Fehler (HTTP {status})")
|
||||
}
|
||||
BackendError::Http(status, msg) => format!("Backend-Fehler (HTTP {status}): {msg}"),
|
||||
BackendError::Transport(msg) => format!("Backend nicht erreichbar: {msg}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Client of the admin backend at one base URL.
|
||||
#[derive(Clone)]
|
||||
pub struct BackendClient {
|
||||
transport: Arc<dyn HttpTransport>,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
impl BackendClient {
|
||||
/// `base_url` as checked by [`normalize_url`]; a trailing slash is
|
||||
/// ignored.
|
||||
pub fn new(transport: Arc<dyn HttpTransport>, base_url: &str) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
base_url: base_url.trim_end_matches('/').to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The admin login page the login window opens.
|
||||
pub fn login_url(&self) -> String {
|
||||
format!("{}{LOGIN_PATH}", self.base_url)
|
||||
}
|
||||
|
||||
/// Where admins see and delete their keys (in the browser).
|
||||
pub fn keys_page_url(&self) -> String {
|
||||
format!("{}/admin/api-keys", self.base_url)
|
||||
}
|
||||
|
||||
/// Whether `url`, a page the login window loaded, shows that the admin
|
||||
/// is logged in: a page of the backend other than the login page.
|
||||
pub fn is_logged_in_page(&self, url: &str) -> bool {
|
||||
let (Ok(page), Ok(base)) = (Url::parse(url), Url::parse(&self.base_url)) else {
|
||||
return false;
|
||||
};
|
||||
if page.origin() != base.origin() {
|
||||
return false;
|
||||
}
|
||||
let login = format!("{}{LOGIN_PATH}", base.path().trim_end_matches('/'));
|
||||
page.path() != login && !page.path().starts_with(&format!("{login}/"))
|
||||
}
|
||||
|
||||
/// Creates a key with the admin's browser session (`cookie_header`, the
|
||||
/// session's cookies as a `Cookie` header value). Redirects are not
|
||||
/// followed: one to the login page means not logged in.
|
||||
pub async fn create_key(
|
||||
&self,
|
||||
cookie_header: &str,
|
||||
label: &str,
|
||||
) -> Result<NewKey, BackendError> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Created {
|
||||
key: String,
|
||||
expires_at: DateTime<Local>,
|
||||
}
|
||||
|
||||
let resp = self
|
||||
.send(
|
||||
Method::Post,
|
||||
self.keys_page_url(),
|
||||
("Cookie", cookie_header),
|
||||
json!({ "label": label }),
|
||||
)
|
||||
.await?;
|
||||
match resp.status {
|
||||
200..=299 => match resp.json::<Created>() {
|
||||
Ok(created) if !created.key.is_empty() => Ok(NewKey {
|
||||
key: created.key,
|
||||
expires_at: created.expires_at,
|
||||
}),
|
||||
_ => Err(unexpected(&resp)),
|
||||
},
|
||||
300..=399 | 401 => Err(BackendError::NotLoggedIn),
|
||||
403 => Err(BackendError::Forbidden),
|
||||
_ => Err(http_error(&resp)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks `key` and returns what the backend knows about it.
|
||||
pub async fn key_info(&self, key: &str) -> Result<KeyInfo, BackendError> {
|
||||
let url = format!("{}/admin/api/key", self.base_url);
|
||||
let resp = self
|
||||
.send(Method::Get, url, (KEY_HEADER, key), Value::Null)
|
||||
.await?;
|
||||
match resp.status {
|
||||
200..=299 => resp.json().map_err(|_| unexpected(&resp)),
|
||||
_ => Err(api_error(&resp)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads a transcript; returns the id the CRM gave it.
|
||||
pub async fn upload_transcript(&self, key: &str, text: &str) -> Result<String, BackendError> {
|
||||
let url = format!("{}/admin/api/phone-transcripts", self.base_url);
|
||||
let resp = self
|
||||
.send(
|
||||
Method::Post,
|
||||
url,
|
||||
(KEY_HEADER, key),
|
||||
json!({ "text": text }),
|
||||
)
|
||||
.await?;
|
||||
match resp.status {
|
||||
200..=299 => match resp.json::<Value>().ok().and_then(|v| v.get("id").cloned()) {
|
||||
Some(Value::Number(id)) => Ok(id.to_string()),
|
||||
Some(Value::String(id)) if !id.is_empty() => Ok(id),
|
||||
_ => Err(unexpected(&resp)),
|
||||
},
|
||||
400 | 422 => Err(BackendError::Rejected(rejection_reason(&resp))),
|
||||
_ => Err(api_error(&resp)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a request with one credential header (`auth`) and a JSON body
|
||||
/// (none for `Value::Null`). Redirects are never followed, so neither
|
||||
/// the key nor the cookie can be forwarded to another host.
|
||||
async fn send(
|
||||
&self,
|
||||
method: Method,
|
||||
url: String,
|
||||
auth: (&str, &str),
|
||||
body: Value,
|
||||
) -> Result<HttpResponse, BackendError> {
|
||||
let req = HttpRequest {
|
||||
method,
|
||||
url,
|
||||
headers: vec![
|
||||
(auth.0.to_string(), auth.1.to_string()),
|
||||
("Accept".to_string(), "application/json".to_string()),
|
||||
],
|
||||
body: match body {
|
||||
Value::Null => HttpBody::Empty,
|
||||
body => HttpBody::Json(body),
|
||||
},
|
||||
follow_redirects: false,
|
||||
};
|
||||
self.transport
|
||||
.send(req)
|
||||
.await
|
||||
.map_err(|e| BackendError::Transport(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a page load in the login window leads to, given the result of
|
||||
/// trying to create a key there.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum LoginStep {
|
||||
/// The key: store it, close the window.
|
||||
Done(NewKey),
|
||||
/// Not logged in yet: keep waiting for the admin.
|
||||
Wait,
|
||||
/// The session can never create a key: close the window and fail with
|
||||
/// this message.
|
||||
Fail(String),
|
||||
/// Something else went wrong: show this message and keep the window
|
||||
/// open, so the admin can try again.
|
||||
Retry(String),
|
||||
}
|
||||
|
||||
impl LoginStep {
|
||||
pub fn of(result: Result<NewKey, BackendError>) -> Self {
|
||||
match result {
|
||||
Ok(key) => LoginStep::Done(key),
|
||||
Err(BackendError::NotLoggedIn) => LoginStep::Wait,
|
||||
Err(e @ BackendError::Forbidden) => LoginStep::Fail(e.user_message()),
|
||||
Err(e) => LoginStep::Retry(e.user_message()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a stored key fared when checked with the backend.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum KeyCheck {
|
||||
Valid(KeyInfo),
|
||||
/// Refused by the backend: forget it.
|
||||
Invalid,
|
||||
/// Not checkable right now (unreachable, 503, other error).
|
||||
Unknown(BackendError),
|
||||
}
|
||||
|
||||
impl BackendClient {
|
||||
/// Checks a stored key ([`BackendClient::key_info`]).
|
||||
pub async fn check_key(&self, key: &str) -> KeyCheck {
|
||||
match self.key_info(key).await {
|
||||
Ok(info) => KeyCheck::Valid(info),
|
||||
Err(BackendError::InvalidKey) => KeyCheck::Invalid,
|
||||
Err(e) => KeyCheck::Unknown(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A key from the keyring and the expiry stored with it.
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub struct StoredKey {
|
||||
pub key: String,
|
||||
pub expires_at: Option<DateTime<Local>>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for StoredKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("StoredKey")
|
||||
.field("key", &"<redacted>")
|
||||
.field("expires_at", &self.expires_at)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `stored` is missing or expires within a minute of `now`, so a
|
||||
/// login has to come first.
|
||||
pub fn needs_login(stored: Option<&StoredKey>, now: DateTime<Local>) -> bool {
|
||||
match stored {
|
||||
None => true,
|
||||
Some(stored) => stored
|
||||
.expires_at
|
||||
.is_some_and(|expires_at| expires_at <= now + Duration::minutes(1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's side of a login, for [`upload_with_login`].
|
||||
#[async_trait]
|
||||
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);
|
||||
}
|
||||
|
||||
/// Uploads `text` with the stored key, logging in first when there is no
|
||||
/// usable key. A key the backend refuses is discarded, and after a new
|
||||
/// login the upload is tried once more. Returns the CRM's id, or the
|
||||
/// message to show.
|
||||
pub async fn upload_with_login(
|
||||
client: &BackendClient,
|
||||
login: &dyn Login,
|
||||
stored: Option<StoredKey>,
|
||||
now: DateTime<Local>,
|
||||
text: &str,
|
||||
) -> Result<String, String> {
|
||||
let key = match stored.filter(|stored| !needs_login(Some(stored), now)) {
|
||||
Some(stored) => stored.key,
|
||||
None => login.login().await?,
|
||||
};
|
||||
match client.upload_transcript(&key, text).await {
|
||||
Err(BackendError::InvalidKey) => {
|
||||
login.discard_key().await;
|
||||
let key = login.login().await?;
|
||||
let result = client.upload_transcript(&key, text).await;
|
||||
if result == Err(BackendError::InvalidKey) {
|
||||
login.discard_key().await;
|
||||
}
|
||||
result.map_err(|e| e.user_message())
|
||||
}
|
||||
result => result.map_err(|e| e.user_message()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 2xx answer whose body is not what the contract says.
|
||||
fn unexpected(resp: &HttpResponse) -> BackendError {
|
||||
BackendError::Http(resp.status, "unerwartete Antwort".to_string())
|
||||
}
|
||||
|
||||
/// The error of an `/admin/api/…` request: refused key, backend unable to
|
||||
/// check it, or any other status.
|
||||
fn api_error(resp: &HttpResponse) -> BackendError {
|
||||
match resp.status {
|
||||
401 => BackendError::InvalidKey,
|
||||
503 => BackendError::Unavailable,
|
||||
_ => http_error(resp),
|
||||
}
|
||||
}
|
||||
|
||||
/// An unexpected status with the backend's `error` message, if any. Other
|
||||
/// bodies (e.g. an HTML error page) are not passed on.
|
||||
fn http_error(resp: &HttpResponse) -> BackendError {
|
||||
let message = resp
|
||||
.json::<Value>()
|
||||
.ok()
|
||||
.and_then(|body| body.get("error")?.as_str().map(str::to_string))
|
||||
.unwrap_or_default();
|
||||
BackendError::Http(resp.status, message)
|
||||
}
|
||||
|
||||
/// Why the backend refused a transcript: its `errors`, else its `error`.
|
||||
fn rejection_reason(resp: &HttpResponse) -> String {
|
||||
let Ok(body) = resp.json::<Value>() else {
|
||||
return String::new();
|
||||
};
|
||||
let errors: Vec<String> = body
|
||||
.get("errors")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|error| match error {
|
||||
Value::String(text) => text.clone(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.collect();
|
||||
if errors.is_empty() {
|
||||
body.get("error")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
} else {
|
||||
errors.join("; ")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chrono::TimeZone;
|
||||
|
||||
use super::*;
|
||||
use crate::http::TransportError;
|
||||
use crate::testing::FakeTransport;
|
||||
|
||||
const BASE: &str = "https://backend.example";
|
||||
const KEYS: &str = "https://backend.example/admin/api-keys";
|
||||
const KEY_INFO: &str = "https://backend.example/admin/api/key";
|
||||
const UPLOAD: &str = "https://backend.example/admin/api/phone-transcripts";
|
||||
|
||||
fn client() -> (Arc<FakeTransport>, BackendClient) {
|
||||
let transport = Arc::new(FakeTransport::new());
|
||||
let client = BackendClient::new(transport.clone(), BASE);
|
||||
(transport, client)
|
||||
}
|
||||
|
||||
fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32) -> DateTime<Local> {
|
||||
Local.with_ymd_and_hms(y, mo, d, h, mi, 0).unwrap()
|
||||
}
|
||||
|
||||
fn json_body(req: &HttpRequest) -> Value {
|
||||
match &req.body {
|
||||
HttpBody::Json(value) => value.clone(),
|
||||
other => panic!("expected a JSON body, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[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!(
|
||||
key_label(Some("PC-VERTRIEB-3")),
|
||||
"Gesprächsrekorder (PC-VERTRIEB-3)"
|
||||
);
|
||||
assert_eq!(key_label(Some(" ")), "Gesprächsrekorder");
|
||||
assert_eq!(key_label(None), "Gesprächsrekorder");
|
||||
let long = key_label(Some(&"x".repeat(200)));
|
||||
assert_eq!(long.chars().count(), 100);
|
||||
assert!(long.starts_with("Gesprächsrekorder (xxx"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_and_keys_pages_are_under_the_base_url() {
|
||||
let (_, client) = client();
|
||||
assert_eq!(client.login_url(), "https://backend.example/euvadm");
|
||||
assert_eq!(client.keys_page_url(), KEYS);
|
||||
let slash = BackendClient::new(Arc::new(FakeTransport::new()), "https://backend.example/");
|
||||
assert_eq!(slash.login_url(), "https://backend.example/euvadm");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backend_page_other_than_the_login_page_means_logged_in() {
|
||||
let (_, client) = client();
|
||||
assert!(client.is_logged_in_page("https://backend.example/admin"));
|
||||
assert!(client.is_logged_in_page("https://backend.example/admin/dashboard?x=1"));
|
||||
assert!(client.is_logged_in_page("https://backend.example/"));
|
||||
assert!(!client.is_logged_in_page("https://backend.example/euvadm"));
|
||||
assert!(!client.is_logged_in_page("https://backend.example/euvadm/login_check"));
|
||||
assert!(!client.is_logged_in_page("https://other.example/admin"));
|
||||
assert!(!client.is_logged_in_page("http://backend.example/admin"));
|
||||
assert!(!client.is_logged_in_page("https://backend.example:8443/admin"));
|
||||
assert!(!client.is_logged_in_page("about:blank"));
|
||||
assert!(!client.is_logged_in_page("not a url"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_key_sends_the_session_cookie_and_label_without_following_redirects() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(
|
||||
Method::Post,
|
||||
KEYS,
|
||||
201,
|
||||
r#"{"key":"euv_secret","expiresAt":"2027-11-06T10:00:00+01:00","label":"Gesprächsrekorder (PC)"}"#,
|
||||
);
|
||||
|
||||
let key = client
|
||||
.create_key("PHPSESSID=abc; other=1", "Gesprächsrekorder (PC)")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(key.key, "euv_secret");
|
||||
assert_eq!(
|
||||
key.expires_at,
|
||||
DateTime::parse_from_rfc3339("2027-11-06T10:00:00+01:00").unwrap()
|
||||
);
|
||||
let req = &transport.requests()[0];
|
||||
assert_eq!(req.header("Cookie"), Some("PHPSESSID=abc; other=1"));
|
||||
assert_eq!(req.header(KEY_HEADER), None);
|
||||
assert!(!req.follow_redirects);
|
||||
assert_eq!(json_body(req), json!({"label": "Gesprächsrekorder (PC)"}));
|
||||
assert!(!format!("{key:?}").contains("euv_secret"));
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_key_maps_redirects_and_refusals() {
|
||||
for (status, body, expected) in [
|
||||
(302, "", BackendError::NotLoggedIn),
|
||||
(401, "", BackendError::NotLoggedIn),
|
||||
(
|
||||
403,
|
||||
r#"{"error":"admin session required"}"#,
|
||||
BackendError::Forbidden,
|
||||
),
|
||||
(
|
||||
500,
|
||||
"<html>boom</html>",
|
||||
BackendError::Http(500, String::new()),
|
||||
),
|
||||
(
|
||||
400,
|
||||
r#"{"error":"label too long"}"#,
|
||||
BackendError::Http(400, "label too long".into()),
|
||||
),
|
||||
(
|
||||
201,
|
||||
r#"{"key":"euv_x"}"#,
|
||||
BackendError::Http(201, "unerwartete Antwort".into()),
|
||||
),
|
||||
] {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, KEYS, status, body);
|
||||
assert_eq!(
|
||||
client.create_key("s=1", "l").await,
|
||||
Err(expected),
|
||||
"{status}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn key_info_sends_the_key_and_parses_the_answer() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(
|
||||
Method::Get,
|
||||
KEY_INFO,
|
||||
200,
|
||||
r#"{"label":"Gesprächsrekorder (PC)","hint":"…x9f2","username":"hinrichs","createdAt":"2026-11-06T10:00:00+01:00","expiresAt":"2027-11-06T10:00:00+01:00"}"#,
|
||||
);
|
||||
|
||||
let info = client.key_info("euv_secret").await.unwrap();
|
||||
|
||||
assert_eq!(info.username, "hinrichs");
|
||||
assert_eq!(info.hint, "…x9f2");
|
||||
assert_eq!(info.expires_at, at(2027, 11, 6, 10, 0));
|
||||
let req = &transport.requests()[0];
|
||||
assert_eq!(req.header(KEY_HEADER), Some("euv_secret"));
|
||||
assert_eq!(req.header("Cookie"), None);
|
||||
assert!(!req.follow_redirects);
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn key_info_maps_refused_and_unavailable() {
|
||||
for (status, body, expected) in [
|
||||
(
|
||||
401,
|
||||
r#"{"error":"invalid api key"}"#,
|
||||
BackendError::InvalidKey,
|
||||
),
|
||||
(
|
||||
401,
|
||||
r#"{"error":"api key required"}"#,
|
||||
BackendError::InvalidKey,
|
||||
),
|
||||
(
|
||||
503,
|
||||
r#"{"error":"admin status unavailable"}"#,
|
||||
BackendError::Unavailable,
|
||||
),
|
||||
] {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Get, KEY_INFO, status, body);
|
||||
assert_eq!(client.key_info("euv_k").await, Err(expected), "{status}");
|
||||
}
|
||||
let (transport, client) = client();
|
||||
transport.fail(Method::Get, KEY_INFO, TransportError::Timeout);
|
||||
assert_eq!(
|
||||
client.key_info("euv_k").await,
|
||||
Err(BackendError::Transport("Zeitüberschreitung".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upload_posts_the_text_with_the_key_and_returns_the_id() {
|
||||
for (body, id) in [
|
||||
(r#"{"id":4711}"#, "4711"),
|
||||
(r#"{"id":"crm-0815"}"#, "crm-0815"),
|
||||
] {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, 201, body);
|
||||
|
||||
assert_eq!(
|
||||
client.upload_transcript("euv_k", "Titel: Test").await,
|
||||
Ok(id.into())
|
||||
);
|
||||
|
||||
let req = &transport.requests()[0];
|
||||
assert_eq!(req.header(KEY_HEADER), Some("euv_k"));
|
||||
assert_eq!(req.header("Cookie"), None);
|
||||
assert!(!req.follow_redirects);
|
||||
assert_eq!(json_body(req), json!({"text": "Titel: Test"}));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upload_maps_rejections_and_auth_errors() {
|
||||
for (status, body, expected) in [
|
||||
(
|
||||
400,
|
||||
r#"{"error":"text required"}"#,
|
||||
BackendError::Rejected("text required".into()),
|
||||
),
|
||||
(
|
||||
422,
|
||||
r#"{"error":"transcript rejected","errors":["Text zu lang","Kein Admin"]}"#,
|
||||
BackendError::Rejected("Text zu lang; Kein Admin".into()),
|
||||
),
|
||||
(
|
||||
422,
|
||||
r#"{"error":"transcript rejected","errors":[]}"#,
|
||||
BackendError::Rejected("transcript rejected".into()),
|
||||
),
|
||||
(
|
||||
422,
|
||||
r#"{"error":"transcript rejected","errors":[{"field":"text"}]}"#,
|
||||
BackendError::Rejected(r#"{"field":"text"}"#.into()),
|
||||
),
|
||||
(
|
||||
401,
|
||||
r#"{"error":"invalid api key"}"#,
|
||||
BackendError::InvalidKey,
|
||||
),
|
||||
(
|
||||
503,
|
||||
r#"{"error":"admin status unavailable"}"#,
|
||||
BackendError::Unavailable,
|
||||
),
|
||||
(
|
||||
201,
|
||||
r#"{"id":null}"#,
|
||||
BackendError::Http(201, "unerwartete Antwort".into()),
|
||||
),
|
||||
] {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, status, body);
|
||||
assert_eq!(
|
||||
client.upload_transcript("euv_k", "x").await,
|
||||
Err(expected),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_have_german_messages_without_secrets() {
|
||||
assert_eq!(
|
||||
BackendError::Forbidden.user_message(),
|
||||
"Diese Anmeldung kann keinen Schlüssel erzeugen (z. B. bei Impersonation) – bitte als Admin selbst anmelden."
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::Unavailable.user_message(),
|
||||
"Backend kann die Anmeldung gerade nicht prüfen – bitte später erneut versuchen."
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::Rejected("text required".into()).user_message(),
|
||||
"Backend hat das Transkript abgelehnt: text required"
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::Transport("Zeitüberschreitung".into()).user_message(),
|
||||
"Backend nicht erreichbar: Zeitüberschreitung"
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::Http(500, String::new()).user_message(),
|
||||
"Backend-Fehler (HTTP 500)"
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::Http(400, "label too long".into()).user_message(),
|
||||
"Backend-Fehler (HTTP 400): label too long"
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::InvalidKey.user_message(),
|
||||
"Backend-Schlüssel ungültig oder abgelaufen – bitte neu anmelden."
|
||||
);
|
||||
assert_eq!(
|
||||
BackendError::NotLoggedIn.user_message(),
|
||||
"Nicht beim Backend angemeldet"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_login_step_follows_from_the_create_key_result() {
|
||||
let key = NewKey {
|
||||
key: "euv_k".into(),
|
||||
expires_at: at(2027, 1, 1, 0, 0),
|
||||
};
|
||||
assert_eq!(LoginStep::of(Ok(key.clone())), LoginStep::Done(key));
|
||||
assert_eq!(
|
||||
LoginStep::of(Err(BackendError::NotLoggedIn)),
|
||||
LoginStep::Wait
|
||||
);
|
||||
assert_eq!(
|
||||
LoginStep::of(Err(BackendError::Forbidden)),
|
||||
LoginStep::Fail(BackendError::Forbidden.user_message())
|
||||
);
|
||||
for err in [
|
||||
BackendError::Http(500, String::new()),
|
||||
BackendError::Transport("weg".into()),
|
||||
] {
|
||||
assert_eq!(
|
||||
LoginStep::of(Err(err.clone())),
|
||||
LoginStep::Retry(err.user_message())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_checked_key_is_valid_invalid_or_unknown() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(
|
||||
Method::Get,
|
||||
KEY_INFO,
|
||||
200,
|
||||
r#"{"label":"l","hint":"h","username":"u","createdAt":"2026-11-06T10:00:00+01:00","expiresAt":"2027-11-06T10:00:00+01:00"}"#,
|
||||
);
|
||||
transport.expect(Method::Get, KEY_INFO, 401, r#"{"error":"invalid api key"}"#);
|
||||
transport.expect(Method::Get, KEY_INFO, 503, "");
|
||||
transport.fail(Method::Get, KEY_INFO, TransportError::Network("dns".into()));
|
||||
|
||||
assert!(
|
||||
matches!(client.check_key("k").await, KeyCheck::Valid(info) if info.username == "u")
|
||||
);
|
||||
assert_eq!(client.check_key("k").await, KeyCheck::Invalid);
|
||||
assert_eq!(
|
||||
client.check_key("k").await,
|
||||
KeyCheck::Unknown(BackendError::Unavailable)
|
||||
);
|
||||
assert_eq!(
|
||||
client.check_key("k").await,
|
||||
KeyCheck::Unknown(BackendError::Transport("Netzwerkfehler: dns".into()))
|
||||
);
|
||||
}
|
||||
|
||||
fn stored(key: &str, expires_at: Option<DateTime<Local>>) -> StoredKey {
|
||||
StoredKey {
|
||||
key: key.into(),
|
||||
expires_at,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_expiring_key_needs_a_login() {
|
||||
let now = at(2026, 11, 6, 12, 0);
|
||||
assert!(needs_login(None, now));
|
||||
assert!(needs_login(Some(&stored("k", Some(now))), now));
|
||||
assert!(needs_login(
|
||||
Some(&stored("k", Some(now + chrono::Duration::seconds(60)))),
|
||||
now
|
||||
));
|
||||
assert!(!needs_login(
|
||||
Some(&stored("k", Some(now + chrono::Duration::seconds(61)))),
|
||||
now
|
||||
));
|
||||
assert!(!needs_login(Some(&stored("k", None)), now));
|
||||
assert!(!format!("{:?}", stored("euv_secret", None)).contains("euv_secret"));
|
||||
}
|
||||
|
||||
/// Scripted [`Login`]: hands out the given results in order and counts
|
||||
/// discards.
|
||||
struct FakeLogin {
|
||||
results: Mutex<Vec<Result<String, String>>>,
|
||||
logins: Mutex<usize>,
|
||||
discards: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl FakeLogin {
|
||||
fn new(results: Vec<Result<String, String>>) -> Self {
|
||||
Self {
|
||||
results: Mutex::new(results),
|
||||
logins: Mutex::new(0),
|
||||
discards: Mutex::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn counts(&self) -> (usize, usize) {
|
||||
(*self.logins.lock().unwrap(), *self.discards.lock().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Login for FakeLogin {
|
||||
async fn login(&self) -> Result<String, String> {
|
||||
*self.logins.lock().unwrap() += 1;
|
||||
self.results.lock().unwrap().remove(0)
|
||||
}
|
||||
|
||||
async fn discard_key(&self) {
|
||||
*self.discards.lock().unwrap() += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> DateTime<Local> {
|
||||
at(2026, 11, 6, 12, 0)
|
||||
}
|
||||
|
||||
fn valid(key: &str) -> Option<StoredKey> {
|
||||
Some(stored(key, Some(at(2027, 11, 6, 12, 0))))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_a_key_the_upload_logs_in_first() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":1}"#);
|
||||
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
|
||||
|
||||
let id = upload_with_login(&client, &login, None, now(), "t").await;
|
||||
|
||||
assert_eq!(id, Ok("1".into()));
|
||||
assert_eq!(login.counts(), (1, 0));
|
||||
assert_eq!(transport.requests()[0].header(KEY_HEADER), Some("euv_new"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_expired_key_is_replaced_before_the_upload() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":2}"#);
|
||||
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
|
||||
let expired = Some(stored("euv_old", Some(now() - chrono::Duration::days(1))));
|
||||
|
||||
let id = upload_with_login(&client, &login, expired, now(), "t").await;
|
||||
|
||||
assert_eq!(id, Ok("2".into()));
|
||||
assert_eq!(login.counts(), (1, 0));
|
||||
assert_eq!(transport.requests()[0].header(KEY_HEADER), Some("euv_new"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_valid_key_uploads_without_a_login() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":3}"#);
|
||||
let login = FakeLogin::new(vec![]);
|
||||
|
||||
let id = upload_with_login(&client, &login, valid("euv_k"), now(), "t").await;
|
||||
|
||||
assert_eq!(id, Ok("3".into()));
|
||||
assert_eq!(login.counts(), (0, 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refused_key_is_discarded_and_the_upload_retried_once_after_a_login() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, 401, r#"{"error":"invalid api key"}"#);
|
||||
transport.expect(Method::Post, UPLOAD, 201, r#"{"id":"crm-9"}"#);
|
||||
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
|
||||
|
||||
let id = upload_with_login(&client, &login, valid("euv_old"), now(), "t").await;
|
||||
|
||||
assert_eq!(id, Ok("crm-9".into()));
|
||||
assert_eq!(login.counts(), (1, 1));
|
||||
let keys: Vec<_> = transport
|
||||
.requests()
|
||||
.iter()
|
||||
.map(|r| r.header(KEY_HEADER).unwrap().to_string())
|
||||
.collect();
|
||||
assert_eq!(keys, ["euv_old", "euv_new"]);
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_key_refused_twice_ends_in_an_error_without_looping() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(Method::Post, UPLOAD, 401, r#"{"error":"invalid api key"}"#);
|
||||
transport.expect(Method::Post, UPLOAD, 401, r#"{"error":"invalid api key"}"#);
|
||||
let login = FakeLogin::new(vec![Ok("euv_new".into())]);
|
||||
|
||||
let result = upload_with_login(&client, &login, valid("euv_old"), now(), "t").await;
|
||||
|
||||
assert_eq!(result, Err(BackendError::InvalidKey.user_message()));
|
||||
assert_eq!(login.counts(), (1, 2));
|
||||
transport.assert_done();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unavailable_backend_fails_without_a_login() {
|
||||
let (transport, client) = client();
|
||||
transport.expect(
|
||||
Method::Post,
|
||||
UPLOAD,
|
||||
503,
|
||||
r#"{"error":"admin status unavailable"}"#,
|
||||
);
|
||||
let login = FakeLogin::new(vec![]);
|
||||
|
||||
let result = upload_with_login(&client, &login, valid("euv_k"), now(), "t").await;
|
||||
|
||||
assert_eq!(result, Err(BackendError::Unavailable.user_message()));
|
||||
assert_eq!(login.counts(), (0, 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_login_stops_the_upload() {
|
||||
let (transport, client) = client();
|
||||
let login = FakeLogin::new(vec![Err("Anmeldung abgebrochen".into())]);
|
||||
|
||||
let result = upload_with_login(&client, &login, None, now(), "t").await;
|
||||
|
||||
assert_eq!(result, Err("Anmeldung abgebrochen".into()));
|
||||
assert!(transport.requests().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreachable_backend_is_reported() {
|
||||
let (transport, client) = client();
|
||||
transport.fail(Method::Post, UPLOAD, TransportError::Network("dns".into()));
|
||||
let login = FakeLogin::new(vec![]);
|
||||
|
||||
let result = upload_with_login(&client, &login, valid("euv_k"), now(), "t").await;
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
Err("Backend nicht erreichbar: Netzwerkfehler: dns".into())
|
||||
);
|
||||
assert_eq!(login.counts(), (0, 0));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user