A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(admin): parse API error details once, drop unit tests
Hampus17892fd3e1cc
diff --git a/fluxer_admin/src/api/client.rs b/fluxer_admin/src/api/client.rsindex f54738151..c372f3e00 100644--- a/fluxer_admin/src/api/client.rs+++ b/fluxer_admin/src/api/client.rs@@ -11,10 +11,139 @@ use serde::de::DeserializeOwned;#[derive(Debug)]pub enum ApiError {Network(String),- Http { status: u16, message: String },+ Http {+ status: u16,+ message: String,+ details: Option<Box<ApiErrorDetails>>,+ },Parse(String),}+#[derive(Debug)]+pub struct ApiErrorDetails {+ message: Option<String>,+ errors: Vec<ApiFieldError>,+}++#[derive(Debug)]+struct ApiFieldError {+ path: Option<String>,+ message: Option<String>,+}++impl ApiErrorDetails {+ fn parse(message: &str) -> Option<Self> {+ let body: serde_json::Value = serde_json::from_str(message).ok()?;+ let errors = body["errors"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|error| ApiFieldError {+ path: error["path"].as_str().map(str::to_owned),+ message: error["message"].as_str().map(str::to_owned),+ })+ .collect();+ Some(Self {+ message: body["message"].as_str().map(str::to_owned),+ errors,+ })+ }+}++impl ApiError {+ pub fn http(status: u16, message: impl Into<String>) -> Self {+ let message = message.into();+ let details = ApiErrorDetails::parse(&message).map(Box::new);+ Self::Http {+ status,+ message,+ details,+ }+ }++ pub fn refusal_message(&self, fallback: &str) -> String {+ let Self::Http {+ details: Some(details),+ ..+ } = self+ else {+ return fallback.to_owned();+ };+ details.message.as_ref().map_or_else(+ || fallback.to_owned(),+ |detail| format!("{fallback}: {detail}"),+ )+ }++ pub fn validation_message(&self) -> Option<String> {+ let Self::Http {+ status: 400,+ details: Some(details),+ ..+ } = self+ else {+ return None;+ };+ let detail = details.errors.first().and_then(|error| {+ let message = error.message.as_ref()?;+ Some(+ match error.path.as_deref().filter(|path| !path.is_empty()) {+ Some(path) => format!("{path}: {message}"),+ None => message.to_owned(),+ },+ )+ });+ detail.or_else(|| details.message.clone())+ }++ pub fn detail_message(&self) -> Option<String> {+ let Self::Http {+ status: 400 | 403 | 404 | 409,+ details: Some(details),+ ..+ } = self+ else {+ return None;+ };+ details+ .errors+ .first()+ .and_then(|error| error.message.as_ref())+ .or(details.message.as_ref())+ .cloned()+ }++ pub fn field_errors(&self) -> Vec<(String, String)> {+ let Self::Http {+ status: 400,+ details: Some(details),+ ..+ } = self+ else {+ return Vec::new();+ };+ details+ .errors+ .iter()+ .filter_map(|error| Some((error.path.clone()?, error.message.clone()?)))+ .collect()+ }++ pub fn has_field_error(&self, path: &str) -> bool {+ let Self::Http {+ details: Some(details),+ ..+ } = self+ else {+ return false;+ };+ details+ .errors+ .iter()+ .any(|error| error.path.as_deref() == Some(path))+ }+}+pub type ApiResult<T> = Result<T, ApiError>;const INTERNAL_ADMIN_PROXY_CLIENT_IP: &str = "127.0.0.1";@@ -136,6 +265,22 @@ impl AdminApiClient {Self::parse_response(response).await}+ pub async fn get_bytes(&self, path: &str) -> ApiResult<(String, Vec<u8>)> {+ let response = Self::send_request(self.request(Method::GET, path, None, None)?).await?;+ let response = Self::check_response_status(response).await?;+ let content_type = response+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|value| value.to_str().ok())+ .unwrap_or("application/octet-stream")+ .to_owned();+ let body = response+ .bytes()+ .await+ .map_err(|e| ApiError::Network(e.to_string()))?;+ Ok((content_type, body.to_vec()))+ }+pub async fn send<T, B>(&self,method: Method,@@ -174,7 +319,7 @@ impl AdminApiClient {let message = response.text().await.map_err(|error| {ApiError::Network(format!("failed to read error response body: {error}"))})?;- Err(ApiError::Http { status, message })+ Err(ApiError::http(status, message))}pub(crate) fn generated(&self) -> &GeneratedClient {@@ -206,10 +351,7 @@ impl AdminApiClient {error: progenitor_client::Error<E>,) -> ApiError {match error.status() {- Some(status) => ApiError::Http {- status: status.as_u16(),- message: format!("{error:?}"),- },+ Some(status) => ApiError::http(status.as_u16(), format!("{error:?}")),None => ApiError::Network(format!("{error:?}")),}}@@ -284,7 +426,9 @@ impl std::fmt::Display for ApiError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {Self::Network(msg) => write!(f, "network error: {msg}"),- Self::Http { status, message } => write!(f, "HTTP {status}: {message}"),+ Self::Http {+ status, message, ..+ } => write!(f, "HTTP {status}: {message}"),Self::Parse(msg) => write!(f, "parse error: {msg}"),}}@@ -296,93 +440,3 @@ fn audit_log_reason_header(reason: &str) -> ApiResult<HeaderValue> {value.set_sensitive(true);Ok(value)}--#[cfg(test)]-mod tests {- use super::*;- use serde_json::{Value, json};-- #[test]- fn audit_log_reason_header_keeps_utf8_bytes() {- let reason = "§ 3 Regel – wiederholt 日本";- let value = audit_log_reason_header(reason).expect("valid reason header");- assert_eq!(value.as_bytes(), reason.as_bytes());- assert!(value.is_sensitive());- assert!(audit_log_reason_header("line one\nline two").is_err());- }-- fn response(status: u16, body: &'static str) -> reqwest::Response {- axum::http::Response::builder()- .status(status)- .body(body)- .expect("valid response")- .into()- }-- #[tokio::test]- async fn parses_successful_json_and_empty_responses() {- for (status, body, expected) in [- (200, r#"{"value":1}"#, json!({"value": 1})),- (201, "[1,2]", json!([1, 2])),- (202, "null", Value::Null),- (200, "", Value::Null),- (204, "ignored body", Value::Null),- ] {- let actual: Value = AdminApiClient::parse_response(response(status, body))- .await- .expect("valid response body");- assert_eq!(actual, expected, "HTTP {status}: {body}");- }- }-- #[tokio::test]- async fn empty_responses_preserve_null_deserialization_errors() {- let expected = serde_json::from_value::<Vec<String>>(Value::Null)- .expect_err("null is not a list")- .to_string();- for (status, body) in [(200, ""), (204, "ignored body")] {- let error = AdminApiClient::parse_response::<Vec<String>>(response(status, body))- .await- .expect_err("missing list");- assert_eq!(error.to_string(), format!("parse error: {expected}"));- }- }-- #[tokio::test]- async fn malformed_json_preserves_deserialization_errors() {- for body in [" ", "{", "not JSON"] {- let expected = serde_json::from_str::<Value>(body)- .expect_err("malformed JSON")- .to_string();- let error = AdminApiClient::parse_response::<Value>(response(200, body))- .await- .expect_err("malformed response");- assert_eq!(error.to_string(), format!("parse error: {expected}"));- }- }-- #[tokio::test]- async fn void_responses_do_not_parse_successful_bodies() {- for status in [200, 201, 202, 204] {- AdminApiClient::parse_void_response(response(status, "not JSON"))- .await- .expect("successful void response");- }- }-- #[tokio::test]- async fn typed_and_void_responses_preserve_http_errors() {- for status in [302, 400, 403, 404, 500] {- for body in ["", "plain error", r#"{"code":"FORBIDDEN"}"#] {- let typed = AdminApiClient::parse_response::<Value>(response(status, body))- .await- .map(drop);- let empty = AdminApiClient::parse_void_response(response(status, body)).await;- for result in [typed, empty] {- let error = result.expect_err("unsuccessful response");- assert_eq!(error.to_string(), format!("HTTP {status}: {body}"));- }- }- }- }-}diff --git a/fluxer_admin/src/api/guilds.rs b/fluxer_admin/src/api/guilds.rsindex 43f7b0f70..b6194fe93 100644--- a/fluxer_admin/src/api/guilds.rs+++ b/fluxer_admin/src/api/guilds.rs@@ -35,10 +35,7 @@ impl AdminApiClient {self.lookup_guild(guild_id).await?.map(GuildInfo::from)- .ok_or_else(|| super::client::ApiError::Http {- status: 404,- message: "Guild not found".to_owned(),- })+ .ok_or_else(|| ApiError::http(404, "Guild not found"))}pub async fn lookup_guild(&self, guild_id: &str) -> ApiResult<Option<GuildDetailInfo>> {@@ -335,31 +332,3 @@ fn guild_settings_request(..Default::default()})}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn guild_settings_adapter_preserves_dynamic_patch_fields() {- let settings = serde_json::json!({- "disabled_operations": 5,- "nsfw": true,- "verification_level": 2,- });- let request = guild_settings_request(&settings).unwrap();- let json = serde_json::to_value(request).unwrap();- assert_eq!(json["disabled_operations"], 5);- assert_eq!(json["nsfw"], true);- assert_eq!(json["verification_level"], 2);- }-- #[test]- fn guild_search_adapter_rejects_lossy_totals() {- let response = generated_types::SearchGuildsResponse {- guilds: Vec::new(),- total: 1.5,- };- assert!(search_guilds_response(response).is_err());- }-}diff --git a/fluxer_admin/src/api/users.rs b/fluxer_admin/src/api/users.rsindex 34edba11e..b35a7c521 100644--- a/fluxer_admin/src/api/users.rs+++ b/fluxer_admin/src/api/users.rs@@ -29,6 +29,7 @@ impl AdminApiClient {let response = self.generated().list_admin_users(+ None,nonempty(email),nonempty(last_active_ip),Some(limit.as_str()),@@ -69,10 +70,7 @@ impl AdminApiClient {resp.users.into_iter().next()- .ok_or_else(|| super::client::ApiError::Http {- status: 404,- message: "User not found".to_owned(),- })+ .ok_or_else(|| super::client::ApiError::http(404, "User not found"))}pub async fn get_current_admin(&self) -> ApiResult<AdminUser> {diff --git a/fluxer_admin/src/routes/billing_actions.rs b/fluxer_admin/src/routes/billing_actions.rsindex a8cdab4ba..d214b6eab 100644--- a/fluxer_admin/src/routes/billing_actions.rs+++ b/fluxer_admin/src/routes/billing_actions.rs@@ -133,7 +133,7 @@ pub(super) fn billing_result<T>(result: Result<T, ApiError>) -> FlashData {Ok(_) => FlashData::success("Premium and billing settings updated"),Err(error) => {tracing::warn!(%error, "admin API request failed: update billing config");- match validation_message(&error) {+ match error.validation_message() {Some(message) => FlashData::error(format!("Failed to update premium and billing settings: {message}")),@@ -143,28 +143,6 @@ pub(super) fn billing_result<T>(result: Result<T, ApiError>) -> FlashData {}}-pub(super) fn validation_message(error: &ApiError) -> Option<String> {- let ApiError::Http {- status: 400,- message,- } = error- else {- return None;- };- let body: serde_json::Value = serde_json::from_str(message).ok()?;- let first = body["errors"].as_array().and_then(|errors| errors.first());- let detail = first.and_then(|error| {- let message = error["message"].as_str()?;- Some(- match error["path"].as_str().filter(|path| !path.is_empty()) {- Some(path) => format!("{path}: {message}"),- None => message.to_owned(),- },- )- });- detail.or_else(|| body["message"].as_str().map(str::to_owned))-}-fn secret_update(form: &MultiValueForm, key: &str, clear_key: &str) -> Option<Option<String>> {match form.clean(key) {Some(secret) => Some(Some(secret)),@@ -354,244 +332,3 @@ fn parse_legacy_prices(value: &str) -> Result<Option<BTreeMap<String, Vec<String}Ok((!legacy.is_empty()).then_some(legacy))}--#[cfg(test)]-mod tests {- use super::*;- use crate::api::generated::types as generated_types;- use serde_json::json;-- fn full_form(extra: &str) -> MultiValueForm {- let base = "billing_premium_product_name=%20Gold%20\- &billing_premium_info_url=https%3A%2F%2Fexample.com%2Fgold\- &billing_enabled=on\- &billing_automatic_tax=default&billing_tax_id_collection=on&billing_terms_consent_required=off\- &billing_stripe_secret_key=\- &billing_stripe_webhook_secret=whsec_new\- &billing_default_currency=gbp\- &billing_price_currency=gbp&billing_price_monthly=price_1GbpM&billing_price_yearly=price_1GbpY\- &billing_price_gift_1_month=&billing_price_gift_1_year=price_1GbpG\- &billing_price_currency=SEK&billing_price_monthly=price_1SekM&billing_price_yearly=price_1SekY\- &billing_price_gift_1_month=&billing_price_gift_1_year=\- &billing_price_currency=&billing_price_monthly=&billing_price_yearly=\- &billing_price_gift_1_month=&billing_price_gift_1_year=\- &billing_country_currencies=se%3Dsek%0D%0AGB%20%3D%20GBP%0D%0A\- &billing_legacy_prices=monthly_GBP%3Dprice_1OldA%0Amonthly_gbp%3Dprice_1OldB%2Cprice_1OldA%0Ayearly_SEK%3Dprice_1OldC";- MultiValueForm::parse(format!("{base}{extra}").as_bytes())- }-- #[test]- fn full_billing_form_builds_the_expected_patch() {- let update = build_billing_update(&full_form("")).expect("valid form");- let value = serde_json::to_value(&update).expect("serializable");- serde_json::from_value::<generated_types::InstanceConfigUpdateRequest>(value.clone())- .expect("generated update contract");- assert_eq!(- value,- json!({- "app_public": {- "branding": {- "premium_product_name": "Gold",- "premium_info_url": "https://example.com/gold"- }- },- "billing": {- "enabled": true,- "stripe_webhook_secret": "whsec_new",- "default_currency": "GBP",- "prices": {- "GBP": {- "monthly": "price_1GbpM",- "yearly": "price_1GbpY",- "gift_1_month": null,- "gift_1_year": "price_1GbpG"- },- "SEK": {- "monthly": "price_1SekM",- "yearly": "price_1SekY",- "gift_1_month": null,- "gift_1_year": null- }- },- "country_currencies": {"GB": "GBP", "SE": "SEK"},- "legacy_prices": {- "monthly_GBP": ["price_1OldA", "price_1OldB"],- "yearly_SEK": ["price_1OldC"]- },- "automatic_tax": null,- "tax_id_collection": true,- "terms_consent_required": false- }- })- );- }-- #[test]- fn blank_fields_clear_and_the_default_choice_sends_null() {- let form = MultiValueForm::parse(- b"billing_premium_product_name=&billing_premium_info_url=&billing_enabled=default\- &billing_stripe_secret_key=&billing_clear_stripe_secret_key=true\- &billing_stripe_webhook_secret=\- &billing_default_currency=\- &billing_price_currency=&billing_price_monthly=price_1Ignored\- &billing_country_currencies=&billing_legacy_prices=",- );- let value = serde_json::to_value(build_billing_update(&form).expect("valid form")).unwrap();- assert_eq!(- value,- json!({- "app_public": {- "branding": {"premium_product_name": null, "premium_info_url": null}- },- "billing": {- "enabled": null,- "stripe_secret_key": null,- "default_currency": null,- "prices": null,- "country_currencies": null,- "legacy_prices": null- }- })- );- }-- #[test]- fn a_new_secret_wins_over_the_clear_checkbox() {- let form = MultiValueForm::parse(- b"billing_stripe_secret_key=%20sk_live_x%20&billing_clear_stripe_secret_key=true",- );- let billing = build_billing_update(&form)- .expect("valid form")- .billing- .expect("billing");- assert_eq!(- billing.stripe_secret_key,- Some(Some("sk_live_x".to_owned()))- );- assert_eq!(billing.stripe_webhook_secret, None);- }-- #[test]- fn absent_form_keys_leave_their_fields_untouched() {- let update = build_billing_update(&MultiValueForm::parse(b"billing_enabled=off"))- .expect("valid form");- assert!(update.app_public.is_none());- assert_eq!(- serde_json::to_value(update.billing).unwrap(),- json!({"enabled": false})- );- let untouched = build_billing_update(&MultiValueForm::parse(b"")).expect("valid form");- assert_eq!(serde_json::to_value(untouched.billing).unwrap(), json!({}));- }-- #[test]- fn invalid_input_is_rejected_with_a_message() {- let cases: &[(&str, &str)] = &[- (- "billing_premium_info_url=ftp%3A%2F%2Fexample.com",- "http or https",- ),- ("billing_premium_info_url=example.com", "http or https"),- ("billing_default_currency=GB", "Invalid currency"),- ("billing_enabled=true", "Invalid choice"),- ("billing_automatic_tax=maybe", "Invalid choice"),- (- "billing_price_currency=GBPX&billing_price_monthly=price_1A",- "Invalid currency",- ),- (- "billing_price_currency=GBP&billing_price_monthly=prod_1A",- "Invalid Stripe price ID",- ),- (- "billing_price_currency=GBP&billing_price_monthly=price_1-A",- "Invalid Stripe price ID",- ),- ("billing_price_currency=GBP", "needs at least one price ID"),- (- "billing_price_currency=GBP&billing_price_monthly=price_1A&billing_price_currency=gbp&billing_price_monthly=price_1B",- "more than once",- ),- ("billing_country_currencies=SWE%3DSEK", "Invalid country"),- ("billing_country_currencies=SE", "KEY=VALUE"),- (- "billing_country_currencies=SE%3DSEK%0ASE%3DEUR",- "mapped more than once",- ),- (- "billing_legacy_prices=weekly_GBP%3Dprice_1A",- "Invalid legacy price slot",- ),- (- "billing_legacy_prices=monthly_GBP%3D",- "needs at least one price ID",- ),- (- "billing_default_currency=EUR&billing_price_currency=GBP&billing_price_monthly=price_1A",- "Default currency EUR has no row",- ),- (- "billing_country_currencies=SE%3DSEK&billing_price_currency=GBP&billing_price_monthly=price_1A",- "SE maps to SEK",- ),- ];- let long_name = format!("billing_premium_product_name={}", "A".repeat(41));- let emoji_name = format!(- "billing_premium_product_name=Gold{}",- "%F0%9F%92%8E".repeat(20)- );- let long_case = [- (long_name.as_str(), "at most 40"),- (emoji_name.as_str(), "at most 40"),- ];- for (body, expected) in long_case.iter().chain(cases.iter()) {- let error =- build_billing_update(&MultiValueForm::parse(body.as_bytes())).expect_err(body);- assert!(error.contains(expected), "{body}: {error}");- }- }-- #[test]- fn premium_name_limit_counts_utf16_units() {- let name = format!("{}{}", "A".repeat(39), "\u{1F48E}");- assert_eq!(name.chars().count(), 40);- assert!(parse_premium_product_name(Some(name)).is_err());- let fits = format!("{}{}", "A".repeat(38), "\u{E9}\u{E9}");- assert_eq!(- parse_premium_product_name(Some(fits.clone())),- Ok(Some(fits))- );- }-- #[test]- fn country_currencies_are_not_cross_checked_without_a_price_table() {- let form = MultiValueForm::parse(b"billing_country_currencies=SE%3DSEK");- let billing = build_billing_update(&form).unwrap().billing.unwrap();- assert_eq!(- billing.country_currencies,- Some(Some(BTreeMap::from([("SE".to_owned(), "SEK".to_owned())])))- );- }-- #[test]- fn validation_errors_surface_the_first_api_message() {- let error = ApiError::Http {- status: 400,- message: json!({- "code": "VALIDATION_ERROR",- "message": "Validation failed",- "errors": [{"path": "billing.enabled", "code": "X", "message": "Switch the premium model to mirror first"}]- })- .to_string(),- };- assert_eq!(- validation_message(&error).as_deref(),- Some("billing.enabled: Switch the premium model to mirror first")- );- let server_error = ApiError::Http {- status: 500,- message: "{}".to_owned(),- };- assert_eq!(validation_message(&server_error), None);- }-}diff --git a/fluxer_admin/src/routes/guilds.rs b/fluxer_admin/src/routes/guilds.rsindex dcf000321..4567a5ad6 100644--- a/fluxer_admin/src/routes/guilds.rs+++ b/fluxer_admin/src/routes/guilds.rs@@ -3,7 +3,6 @@use crate::{api::{client::{AdminApiClient, ApiResultExt},- enforcement::api_error_message,generated::types::CommunityRemovalBasis,},middleware::{@@ -481,7 +480,7 @@ async fn remove_community(Ok(_) => FlashData::success("Community removed"),Err(error) => {tracing::warn!(%error, guild_id, "admin API request failed: remove community");- FlashData::error(api_error_message(&error).map_or_else(+ FlashData::error(error.detail_message().map_or_else(|| "Failed to remove the community".to_owned(),|message| format!("Failed to remove the community: {message}"),))diff --git a/fluxer_admin/src/routes/message_actions.rs b/fluxer_admin/src/routes/message_actions.rsindex 3b051eebb..f63071356 100644--- a/fluxer_admin/src/routes/message_actions.rs+++ b/fluxer_admin/src/routes/message_actions.rs@@ -4,7 +4,6 @@ use crate::{acl,api::{client::AdminApiClient,- enforcement::api_error_message,generated::types::{BulkModerationBasis, MessageDeletionBasis},},middleware::{@@ -114,7 +113,7 @@ pub(crate) async fn messages_post(Ok(()) => FlashData::success("Message deleted"),Err(error) => {tracing::warn!(%error, "admin API request failed: delete message");- FlashData::error(api_error_message(&error).map_or_else(+ FlashData::error(error.detail_message().map_or_else(|| "Failed to delete the message".to_owned(),|message| format!("Failed to delete the message: {message}"),))@@ -158,7 +157,10 @@ pub(crate) async fn system_dms_post(Ok(_) => FlashData::success("System DM sent"),Err(error) => {tracing::warn!(%error, "admin API request failed: send system DM");- FlashData::error("Failed to send system DM")+ FlashData::error(error.detail_message().map_or_else(+ || "Failed to send system DM".to_owned(),+ |message| format!("Failed to send system DM: {message}"),+ ))}}} else {@@ -412,23 +414,3 @@ pub(crate) async fn archives_download(}}}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn form_list_values_accepts_repeated_comma_and_newline_values() {- let form = MultiValueForm::parse(b"user_ids%5B%5D=1&user_ids%5B%5D=2%2C3&user_ids=4%0A5");- assert_eq!(- form.list_values_any(&["user_ids[]", "user_ids"]),- vec![- "1".to_owned(),- "2".to_owned(),- "3".to_owned(),- "4".to_owned(),- "5".to_owned()- ]- );- }-}