From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 80E9A1FF0B7 for ; Fri, 13 Nov 2026 16:18:17 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id DFD7621DB5; Fri, 13 Nov 2026 16:10:23 +0100 (CET) From: Lukas Wagner To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox 22/55] notify: use typed SectionConfigData Date: Fri, 13 Nov 2026 16:07:55 +0100 Message-ID: <20261113150828.756836-23-l.wagner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261113150828.756836-1-l.wagner@proxmox.com> References: <20261113150828.756836-1-l.wagner@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1794582525802 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.201 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: EVEIFMKXEVAXSFNZLMOBATWQGTWTRHJK X-Message-ID-Hash: EVEIFMKXEVAXSFNZLMOBATWQGTWTRHJK X-MailFrom: l.wagner@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: This allows us to simplify working with the config quite a bit. Added a config-parsing roundtrip test while at it. Signed-off-by: Lukas Wagner --- proxmox-notify/Cargo.toml | 3 + proxmox-notify/src/api/gotify.rs | 103 ++--- proxmox-notify/src/api/matcher.rs | 54 +-- proxmox-notify/src/api/mod.rs | 41 +- proxmox-notify/src/api/sendmail.rs | 49 +-- proxmox-notify/src/api/smtp.rs | 93 ++--- proxmox-notify/src/api/webhook.rs | 147 +++---- proxmox-notify/src/config.rs | 393 +++++++++++------- proxmox-notify/src/send.rs | 183 ++++---- .../testdata/notifications-priv.cfg.ref | 8 + proxmox-notify/testdata/notifications.cfg.ref | 29 ++ 11 files changed, 540 insertions(+), 563 deletions(-) create mode 100644 proxmox-notify/testdata/notifications-priv.cfg.ref create mode 100644 proxmox-notify/testdata/notifications.cfg.ref diff --git a/proxmox-notify/Cargo.toml b/proxmox-notify/Cargo.toml index 6bb4871f7..5f7ea3176 100644 --- a/proxmox-notify/Cargo.toml +++ b/proxmox-notify/Cargo.toml @@ -40,6 +40,9 @@ proxmox-sys = { workspace = true, optional = true } proxmox-time.workspace = true proxmox-uuid = { workspace = true, features = ["serde"] } +[dev-dependencies] +pretty_assertions.workspace = true + [features] default = ["send-impl", "api-types"] api-impl = [ diff --git a/proxmox-notify/src/api/gotify.rs b/proxmox-notify/src/api/gotify.rs index e0f7cf16b..e4ac46328 100644 --- a/proxmox-notify/src/api/gotify.rs +++ b/proxmox-notify/src/api/gotify.rs @@ -1,12 +1,14 @@ use proxmox_config_digest::ConfigDigest; use proxmox_http_error::HttpError; +use proxmox_section_config::typed::{convert_to_typed_array, lookup}; use crate::Config; use crate::api::http_err; use crate::api_types::{ - DeleteableGotifyProperty, GOTIFY_TYPENAME, GotifyConfig, GotifyConfigUpdater, - GotifyPrivateConfig, GotifyPrivateConfigUpdater, + DeleteableGotifyProperty, GotifyConfig, GotifyConfigUpdater, GotifyPrivateConfig, + GotifyPrivateConfigUpdater, }; +use crate::config::{ConfigEntity, PrivateConfigEntity}; /// Get a list of all gotify endpoints. /// @@ -14,10 +16,10 @@ use crate::api_types::{ /// Returns a list of all gotify endpoints or a `HttpError` if the config is /// erroneous (`500 Internal server error`). pub fn get_endpoints(config: &Config) -> Result, HttpError> { - config - .config - .convert_to_typed_array(GOTIFY_TYPENAME) - .map_err(|e| http_err!(NOT_FOUND, "Could not fetch endpoints: {e}")) + Ok(convert_to_typed_array!(config.config, ConfigEntity::Gotify) + .into_iter() + .cloned() + .collect()) } /// Get gotify endpoint with given `name` @@ -25,10 +27,9 @@ pub fn get_endpoints(config: &Config) -> Result, HttpError> { /// The caller is responsible for any needed permission checks. /// Returns the endpoint or a `HttpError` if the endpoint was not found (`404 Not found`). pub fn get_endpoint(config: &Config, name: &str) -> Result { - config - .config - .lookup(GOTIFY_TYPENAME, name) - .map_err(|_| http_err!(NOT_FOUND, "endpoint '{name}' not found")) + lookup!(config.config, name, ConfigEntity::Gotify) + .cloned() + .ok_or_else(|| http_err!(NOT_FOUND, "endpoint '{name}' not found")) } /// Add a new gotify endpoint. @@ -52,18 +53,17 @@ pub fn add_endpoint( super::ensure_unique(config, &endpoint_config.name)?; - set_private_config_entry(config, &private_endpoint_config)?; + config.private_config.insert( + private_endpoint_config.name.clone(), + PrivateConfigEntity::Gotify(private_endpoint_config), + ); - config - .config - .set_data(&endpoint_config.name, GOTIFY_TYPENAME, &endpoint_config) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{}': {e}", - endpoint_config.name - ) - }) + config.config.insert( + endpoint_config.name.clone(), + ConfigEntity::Gotify(endpoint_config), + ); + + Ok(()) } /// Update existing gotify endpoint @@ -99,13 +99,13 @@ pub fn update_endpoint( } if let Some(token) = private_endpoint_config_updater.token { - set_private_config_entry( - config, - &GotifyPrivateConfig { + config.private_config.insert( + name, + PrivateConfigEntity::Gotify(GotifyPrivateConfig { name: name.into(), token, - }, - )?; + }), + ); } if let Some(comment) = endpoint_config_updater.comment { @@ -116,15 +116,9 @@ pub fn update_endpoint( endpoint.disable = Some(disable); } - config - .config - .set_data(name, GOTIFY_TYPENAME, &endpoint) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{name}': {e}" - ) - }) + config.config.insert(name, ConfigEntity::Gotify(endpoint)); + + Ok(()) } /// Delete existing gotify endpoint @@ -139,33 +133,12 @@ pub fn delete_gotify_endpoint(config: &mut Config, name: &str) -> Result<(), Htt let _ = get_endpoint(config, name)?; super::ensure_safe_to_delete(config, name)?; - remove_private_config_entry(config, name)?; - config.config.sections.remove(name); + config.private_config.remove(name); + config.config.remove(name); Ok(()) } -fn set_private_config_entry( - config: &mut Config, - private_config: &GotifyPrivateConfig, -) -> Result<(), HttpError> { - config - .private_config - .set_data(&private_config.name, GOTIFY_TYPENAME, private_config) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save private config for endpoint '{}': {e}", - private_config.name - ) - }) -} - -fn remove_private_config_entry(config: &mut Config, name: &str) -> Result<(), HttpError> { - config.private_config.sections.remove(name); - Ok(()) -} - #[cfg(test)] mod tests { use super::*; @@ -255,13 +228,15 @@ mod tests { assert_eq!(endpoint.server, "newhost".to_string()); - let token = config - .private_config - .lookup::(GOTIFY_TYPENAME, "gotify-endpoint") - .unwrap() - .token; + let token = &lookup!( + config.private_config, + "gotify-endpoint", + PrivateConfigEntity::Gotify + ) + .unwrap() + .token; - assert_eq!(token, "changedtoken".to_string()); + assert_eq!(token, "changedtoken"); assert_eq!(endpoint.comment, Some("newcomment".to_string())); // Test property deletion diff --git a/proxmox-notify/src/api/matcher.rs b/proxmox-notify/src/api/matcher.rs index f8bc06a9a..cdb66f368 100644 --- a/proxmox-notify/src/api/matcher.rs +++ b/proxmox-notify/src/api/matcher.rs @@ -1,11 +1,11 @@ use proxmox_config_digest::ConfigDigest; use proxmox_http_error::HttpError; +use proxmox_section_config::typed::{convert_to_typed_array, lookup}; use crate::Config; use crate::api::http_err; -use crate::api_types::{ - DeleteableMatcherProperty, MATCHER_TYPENAME, MatcherConfig, MatcherConfigUpdater, -}; +use crate::api_types::{DeleteableMatcherProperty, MatcherConfig, MatcherConfigUpdater}; +use crate::config::ConfigEntity; /// Get a list of all matchers /// @@ -13,10 +13,12 @@ use crate::api_types::{ /// Returns a list of all matchers or a `HttpError` if the config is /// (`500 Internal server error`). pub fn get_matchers(config: &Config) -> Result, HttpError> { - config - .config - .convert_to_typed_array(MATCHER_TYPENAME) - .map_err(|e| http_err!(INTERNAL_SERVER_ERROR, "Could not fetch matchers: {e}")) + Ok( + convert_to_typed_array!(config.config, ConfigEntity::Matcher) + .into_iter() + .cloned() + .collect(), + ) } /// Get matcher with given `name` @@ -24,10 +26,9 @@ pub fn get_matchers(config: &Config) -> Result, HttpError> { /// The caller is responsible for any needed permission checks. /// Returns the endpoint or a `HttpError` if the matcher was not found (`404 Not found`). pub fn get_matcher(config: &Config, name: &str) -> Result { - config - .config - .lookup(MATCHER_TYPENAME, name) - .map_err(|_| http_err!(NOT_FOUND, "matcher '{name}' not found")) + lookup!(config.config, name, ConfigEntity::Matcher) + .cloned() + .ok_or_else(|| http_err!(NOT_FOUND, "matcher '{name}' not found")) } /// Get matcher with given `name`, translating any existing 'match-*' keys into an @@ -37,10 +38,7 @@ pub fn get_matcher(config: &Config, name: &str) -> Result Result { - let mut matcher: MatcherConfig = config - .config - .lookup(MATCHER_TYPENAME, name) - .map_err(|_| http_err!(NOT_FOUND, "matcher '{name}' not found"))?; + let mut matcher = get_matcher(config, name)?; if matcher.expression.is_none() { let expression = matcher.generate_expression_from_legacy_config(); @@ -80,16 +78,10 @@ pub fn add_matcher( .ensure_valid() .map_err(|err| http_err!(BAD_REQUEST, "invalid matcher config: {err}"))?; - config - .config - .set_data(&matcher_config.name, MATCHER_TYPENAME, &matcher_config) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save matcher '{}': {e}", - matcher_config.name - ) - })?; + config.config.insert( + matcher_config.name.clone(), + ConfigEntity::Matcher(matcher_config), + ); Ok(()) } @@ -176,15 +168,7 @@ pub fn update_matcher( .ensure_valid() .map_err(|err| http_err!(BAD_REQUEST, "invalid matcher config: {err}"))?; - config - .config - .set_data(name, MATCHER_TYPENAME, &matcher) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save matcher '{name}': {e}" - ) - })?; + config.config.insert(name, ConfigEntity::Matcher(matcher)); Ok(()) } @@ -199,7 +183,7 @@ pub fn delete_matcher(config: &mut Config, name: &str) -> Result<(), HttpError> // Check if the matcher exists let _ = get_matcher(config, name)?; - config.config.sections.remove(name); + config.config.remove(name); Ok(()) } diff --git a/proxmox-notify/src/api/mod.rs b/proxmox-notify/src/api/mod.rs index b5b05e86f..5232098b4 100644 --- a/proxmox-notify/src/api/mod.rs +++ b/proxmox-notify/src/api/mod.rs @@ -1,12 +1,11 @@ use std::collections::HashSet; use proxmox_config_digest::ConfigDigest; -use serde::{Deserialize, Serialize}; - use proxmox_http_error::HttpError; use crate::Config; use crate::api_types::{EndpointType, Origin, Target}; +use crate::config::ConfigEntity; pub mod common; pub mod gotify; @@ -124,7 +123,7 @@ fn ensure_endpoints_exist>( } fn ensure_unique(config: &Config, entity: &str) -> Result<(), HttpError> { - if config.config.sections.contains_key(entity) { + if config.config.contains_key(entity) { http_bail!( BAD_REQUEST, "Cannot create '{entity}', an entity with the same name already exists" @@ -147,14 +146,11 @@ fn get_referrers(config: &Config, entity: &str) -> Result, HttpE } fn ensure_safe_to_delete(config: &Config, entity: &str) -> Result<(), HttpError> { - if let Some(entity_config) = config.config.sections.get(entity) { - if let Ok(origin) = Origin::deserialize(&entity_config.1["origin"]) { - // Built-ins are never actually removed, only reset to their default - // It is thus safe to do the reset if another entity depends - // on it - if origin == Origin::Builtin || origin == Origin::ModifiedBuiltin { - return Ok(()); - } + if let Some(entity_config) = config.config.get(entity) { + let origin = entity_config.origin().unwrap_or(Origin::UserCreated); + + if origin == Origin::Builtin || origin == Origin::ModifiedBuiltin { + return Ok(()); } } else { http_bail!(NOT_FOUND, "entity '{entity}' does not exist"); @@ -202,29 +198,6 @@ fn get_referenced_entities(config: &Config, entity: &str) -> HashSet { expanded } -fn set_private_config_entry( - config: &mut Config, - private_config: T, - typename: &str, - name: &str, -) -> Result<(), HttpError> { - config - .private_config - .set_data(name, typename, &private_config) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save private config for endpoint '{}': {e}", - name - ) - }) -} - -fn remove_private_config_entry(config: &mut Config, name: &str) -> Result<(), HttpError> { - config.private_config.sections.remove(name); - Ok(()) -} - #[cfg(test)] mod test_helpers { use crate::Config; diff --git a/proxmox-notify/src/api/sendmail.rs b/proxmox-notify/src/api/sendmail.rs index cff63b806..1d429c8f8 100644 --- a/proxmox-notify/src/api/sendmail.rs +++ b/proxmox-notify/src/api/sendmail.rs @@ -1,11 +1,11 @@ use proxmox_config_digest::ConfigDigest; use proxmox_http_error::HttpError; +use proxmox_section_config::typed::{convert_to_typed_array, lookup}; use crate::Config; use crate::api::{http_bail, http_err}; -use crate::api_types::{ - DeleteableSendmailProperty, SENDMAIL_TYPENAME, SendmailConfig, SendmailConfigUpdater, -}; +use crate::api_types::{DeleteableSendmailProperty, SendmailConfig, SendmailConfigUpdater}; +use crate::config::ConfigEntity; /// Get a list of all sendmail endpoints. /// @@ -13,10 +13,12 @@ use crate::api_types::{ /// Returns a list of all sendmail endpoints or a `HttpError` if the config is /// erroneous (`500 Internal server error`). pub fn get_endpoints(config: &Config) -> Result, HttpError> { - config - .config - .convert_to_typed_array(SENDMAIL_TYPENAME) - .map_err(|e| http_err!(NOT_FOUND, "Could not fetch endpoints: {e}")) + Ok( + convert_to_typed_array!(config.config, ConfigEntity::Sendmail) + .into_iter() + .cloned() + .collect(), + ) } /// Get sendmail endpoint with given `name`. @@ -24,10 +26,9 @@ pub fn get_endpoints(config: &Config) -> Result, HttpError> /// The caller is responsible for any needed permission checks. /// Returns the endpoint or a `HttpError` if the endpoint was not found (`404 Not found`). pub fn get_endpoint(config: &Config, name: &str) -> Result { - config - .config - .lookup(SENDMAIL_TYPENAME, name) - .map_err(|_| http_err!(NOT_FOUND, "endpoint '{name}' not found")) + lookup!(config.config, name, ConfigEntity::Sendmail) + .cloned() + .ok_or_else(|| http_err!(NOT_FOUND, "endpoint '{name}' not found")) } /// Add a new sendmail endpoint. @@ -50,14 +51,9 @@ pub fn add_endpoint(config: &mut Config, endpoint: SendmailConfig) -> Result<(), config .config - .set_data(&endpoint.name, SENDMAIL_TYPENAME, &endpoint) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{}': {e}", - endpoint.name - ) - }) + .insert(endpoint.name.clone(), ConfigEntity::Sendmail(endpoint)); + + Ok(()) } /// Update existing sendmail endpoint @@ -122,16 +118,9 @@ pub fn update_endpoint( ); } - config - .config - .set_data(name, SENDMAIL_TYPENAME, &endpoint) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{}': {e}", - endpoint.name - ) - }) + config.config.insert(name, ConfigEntity::Sendmail(endpoint)); + + Ok(()) } /// Delete existing sendmail endpoint @@ -147,7 +136,7 @@ pub fn delete_endpoint(config: &mut Config, name: &str) -> Result<(), HttpError> let _ = get_endpoint(config, name)?; super::ensure_safe_to_delete(config, name)?; - config.config.sections.remove(name); + config.config.remove(name); Ok(()) } diff --git a/proxmox-notify/src/api/smtp.rs b/proxmox-notify/src/api/smtp.rs index ceae77df3..30df66d21 100644 --- a/proxmox-notify/src/api/smtp.rs +++ b/proxmox-notify/src/api/smtp.rs @@ -1,12 +1,14 @@ use proxmox_config_digest::ConfigDigest; use proxmox_http_error::HttpError; +use proxmox_section_config::typed::{convert_to_typed_array, lookup}; use crate::Config; use crate::api::{http_bail, http_err}; use crate::api_types::{ - DeleteableSmtpProperty, SMTP_TYPENAME, SmtpConfig, SmtpConfigUpdater, SmtpPrivateConfig, + DeleteableSmtpProperty, SmtpConfig, SmtpConfigUpdater, SmtpPrivateConfig, SmtpPrivateConfigUpdater, }; +use crate::config::{ConfigEntity, PrivateConfigEntity}; /// Get a list of all smtp endpoints. /// @@ -14,10 +16,10 @@ use crate::api_types::{ /// Returns a list of all smtp endpoints or a `HttpError` if the config is /// erroneous (`500 Internal server error`). pub fn get_endpoints(config: &Config) -> Result, HttpError> { - config - .config - .convert_to_typed_array(SMTP_TYPENAME) - .map_err(|e| http_err!(NOT_FOUND, "Could not fetch endpoints: {e}")) + Ok(convert_to_typed_array!(config.config, ConfigEntity::Smtp) + .into_iter() + .cloned() + .collect()) } /// Get smtp endpoint with given `name`. @@ -25,10 +27,9 @@ pub fn get_endpoints(config: &Config) -> Result, HttpError> { /// The caller is responsible for any needed permission checks. /// Returns the endpoint or a `HttpError` if the endpoint was not found (`404 Not found`). pub fn get_endpoint(config: &Config, name: &str) -> Result { - config - .config - .lookup(SMTP_TYPENAME, name) - .map_err(|_| http_err!(NOT_FOUND, "endpoint '{name}' not found")) + lookup!(config.config, name, ConfigEntity::Smtp) + .cloned() + .ok_or_else(|| http_err!(NOT_FOUND, "endpoint '{name}' not found")) } /// Add a new smtp endpoint. @@ -58,23 +59,17 @@ pub fn add_endpoint( ); } - super::set_private_config_entry( - config, - private_endpoint_config, - SMTP_TYPENAME, - &endpoint_config.name, - )?; + config.private_config.insert( + private_endpoint_config.name.clone(), + PrivateConfigEntity::Smtp(private_endpoint_config), + ); - config - .config - .set_data(&endpoint_config.name, SMTP_TYPENAME, &endpoint_config) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{}': {e}", - endpoint_config.name - ) - }) + config.config.insert( + endpoint_config.name.clone(), + ConfigEntity::Smtp(endpoint_config), + ); + + Ok(()) } /// Update existing smtp endpoint @@ -104,15 +99,15 @@ pub fn update_endpoint( DeleteableSmtpProperty::Disable => endpoint.disable = None, DeleteableSmtpProperty::Mailto => endpoint.mailto.clear(), DeleteableSmtpProperty::MailtoUser => endpoint.mailto_user.clear(), - DeleteableSmtpProperty::Password => super::set_private_config_entry( - config, - SmtpPrivateConfig { - name: name.to_string(), - password: None, - }, - SMTP_TYPENAME, - name, - )?, + DeleteableSmtpProperty::Password => { + config.private_config.insert( + name, + PrivateConfigEntity::Smtp(SmtpPrivateConfig { + name: name.into(), + password: None, + }), + ); + } DeleteableSmtpProperty::Port => endpoint.port = None, DeleteableSmtpProperty::Username => endpoint.username = None, } @@ -141,15 +136,13 @@ pub fn update_endpoint( endpoint.mode = Some(mode); } if let Some(password) = private_endpoint_config_updater.password { - super::set_private_config_entry( - config, - SmtpPrivateConfig { + config.private_config.insert( + name, + PrivateConfigEntity::Smtp(SmtpPrivateConfig { name: name.into(), password: Some(password), - }, - SMTP_TYPENAME, - name, - )?; + }), + ); } if let Some(author) = updater.author { @@ -171,16 +164,9 @@ pub fn update_endpoint( ); } - config - .config - .set_data(name, SMTP_TYPENAME, &endpoint) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{}': {e}", - endpoint.name - ) - }) + config.config.insert(name, ConfigEntity::Smtp(endpoint)); + + Ok(()) } /// Delete existing smtp endpoint @@ -195,8 +181,9 @@ pub fn delete_endpoint(config: &mut Config, name: &str) -> Result<(), HttpError> let _ = get_endpoint(config, name)?; super::ensure_safe_to_delete(config, name)?; - super::remove_private_config_entry(config, name)?; - config.config.sections.remove(name); + config.private_config.remove(name); + + config.config.remove(name); Ok(()) } diff --git a/proxmox-notify/src/api/webhook.rs b/proxmox-notify/src/api/webhook.rs index 7266faca6..beaa26f15 100644 --- a/proxmox-notify/src/api/webhook.rs +++ b/proxmox-notify/src/api/webhook.rs @@ -5,37 +5,38 @@ use proxmox_config_digest::ConfigDigest; use proxmox_http_error::HttpError; use proxmox_schema::property_string::PropertyString; +use proxmox_section_config::typed::{convert_to_typed_array, lookup}; use crate::api::http_err; use crate::api_types::{ - DeleteableWebhookProperty, KeyAndBase64Val, WEBHOOK_TYPENAME, WebhookConfig, - WebhookConfigUpdater, WebhookPrivateConfig, + DeleteableWebhookProperty, KeyAndBase64Val, WebhookConfig, WebhookConfigUpdater, + WebhookPrivateConfig, }; +use crate::config::{ConfigEntity, PrivateConfigEntity}; use crate::{Config, http_bail}; -use super::remove_private_config_entry; -use super::set_private_config_entry; - /// Get a list of all webhook endpoints. /// /// The caller is responsible for any needed permission checks. /// Returns a list of all webhook endpoints or a [`HttpError`] if the config is /// erroneous (`500 Internal server error`). pub fn get_endpoints(config: &Config) -> Result, HttpError> { - let mut endpoints: Vec = config - .config - .convert_to_typed_array(WEBHOOK_TYPENAME) - .map_err(|e| http_err!(NOT_FOUND, "Could not fetch endpoints: {e}"))?; + let mut endpoints: Vec = + convert_to_typed_array!(config.config, ConfigEntity::Webhook) + .into_iter() + .cloned() + .collect(); for endpoint in &mut endpoints { - let priv_config: WebhookPrivateConfig = config - .private_config - .lookup(WEBHOOK_TYPENAME, &endpoint.name) - .unwrap_or_default(); + let priv_config = lookup!( + config.private_config, + &endpoint.name, + PrivateConfigEntity::Webhook + ); let mut secret_names = Vec::new(); // We only return *which* secrets we have stored, but not their values. - for secret in priv_config.secret { + for secret in priv_config.into_iter().flat_map(|c| &c.secret) { secret_names.push( KeyAndBase64Val { name: secret.name.clone(), @@ -56,15 +57,15 @@ pub fn get_endpoints(config: &Config) -> Result, HttpError> { /// The caller is responsible for any needed permission checks. /// Returns the endpoint or a [`HttpError`] if the endpoint was not found (`404 Not found`). pub fn get_endpoint(config: &Config, name: &str) -> Result { - let mut endpoint: WebhookConfig = config - .config - .lookup(WEBHOOK_TYPENAME, name) - .map_err(|_| http_err!(NOT_FOUND, "endpoint '{name}' not found"))?; + let mut endpoint = lookup!(config.config, name, ConfigEntity::Webhook) + .cloned() + .ok_or_else(|| http_err!(NOT_FOUND, "endpoint '{name}' not found"))?; - let priv_config: Option = config - .private_config - .lookup(WEBHOOK_TYPENAME, &endpoint.name) - .ok(); + let priv_config = lookup!( + config.private_config, + &endpoint.name, + PrivateConfigEntity::Webhook + ); let mut secret_names = Vec::new(); if let Some(priv_config) = priv_config { @@ -100,26 +101,20 @@ pub fn add_endpoint( let secrets = std::mem::take(&mut endpoint_config.secret); - set_private_config_entry( - config, - &WebhookPrivateConfig { + config.private_config.insert( + endpoint_config.name.clone(), + PrivateConfigEntity::Webhook(WebhookPrivateConfig { name: endpoint_config.name.clone(), secret: secrets, - }, - WEBHOOK_TYPENAME, - &endpoint_config.name, - )?; + }), + ); - config - .config - .set_data(&endpoint_config.name, WEBHOOK_TYPENAME, &endpoint_config) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{}': {e}", - endpoint_config.name - ) - }) + config.config.insert( + endpoint_config.name.clone(), + ConfigEntity::Webhook(endpoint_config), + ); + + Ok(()) } /// Update existing webhook endpoint. @@ -144,11 +139,10 @@ pub fn update_endpoint( let mut endpoint = get_endpoint(config, name)?; endpoint.secret.clear(); - let old_secrets = config - .private_config - .lookup::(WEBHOOK_TYPENAME, name) - .map_err(|err| http_err!(INTERNAL_SERVER_ERROR, "could not read secret config: {err}"))? - .secret; + let old_secrets = lookup!(config.private_config, name, PrivateConfigEntity::Webhook) + .ok_or_else(|| http_err!(INTERNAL_SERVER_ERROR, "could not read secret config"))? + .secret + .clone(); if let Some(delete) = delete { for deleteable_property in delete { @@ -158,15 +152,13 @@ pub fn update_endpoint( DeleteableWebhookProperty::Header => endpoint.header = Vec::new(), DeleteableWebhookProperty::Body => endpoint.body = None, DeleteableWebhookProperty::Secret => { - set_private_config_entry( - config, - &WebhookPrivateConfig { + config.private_config.insert( + name, + PrivateConfigEntity::Webhook(WebhookPrivateConfig { name: name.into(), secret: Vec::new(), - }, - WEBHOOK_TYPENAME, - name, - )?; + }), + ); } } } @@ -250,26 +242,18 @@ pub fn update_endpoint( new_secrets.push(sec); } - set_private_config_entry( - config, - &WebhookPrivateConfig { + config.private_config.insert( + name, + PrivateConfigEntity::Webhook(WebhookPrivateConfig { name: name.into(), secret: new_secrets, - }, - WEBHOOK_TYPENAME, - name, - )?; + }), + ); } - config - .config - .set_data(name, WEBHOOK_TYPENAME, &endpoint) - .map_err(|e| { - http_err!( - INTERNAL_SERVER_ERROR, - "could not save endpoint '{name}': {e}" - ) - }) + config.config.insert(name, ConfigEntity::Webhook(endpoint)); + + Ok(()) } /// Delete existing webhook endpoint. @@ -284,8 +268,9 @@ pub fn delete_endpoint(config: &mut Config, name: &str) -> Result<(), HttpError> let _ = get_endpoint(config, name)?; super::ensure_safe_to_delete(config, name)?; - remove_private_config_entry(config, name)?; - config.config.sections.remove(name); + config.private_config.remove(name); + + config.config.remove(name); Ok(()) } @@ -381,11 +366,13 @@ mod tests { assert_eq!(endpoint.comment, Some("newcomment".to_string())); assert!(matches!(endpoint.method, HttpMethod::Put)); - let secrets = config - .private_config - .lookup::(WEBHOOK_TYPENAME, "webhook-endpoint") - .unwrap() - .secret; + let secrets = &lookup!( + config.private_config, + "webhook-endpoint", + PrivateConfigEntity::Webhook + ) + .unwrap() + .secret; assert_eq!(secrets[1].name, "token".to_string()); assert_eq!(secrets[1].value, Some(proxmox_base64::encode("secret"))); @@ -407,11 +394,13 @@ mod tests { let endpoint = get_endpoint(&config, "webhook-endpoint")?; assert_eq!(endpoint.comment, None); - let secrets = config - .private_config - .lookup::(WEBHOOK_TYPENAME, "webhook-endpoint") - .unwrap() - .secret; + let secrets = &lookup!( + config.private_config, + "webhook-endpoint", + PrivateConfigEntity::Webhook + ) + .unwrap() + .secret; assert!(secrets.is_empty()); diff --git a/proxmox-notify/src/config.rs b/proxmox-notify/src/config.rs index f59da9bdd..406d3cb53 100644 --- a/proxmox-notify/src/config.rs +++ b/proxmox-notify/src/config.rs @@ -1,138 +1,43 @@ use std::sync::OnceLock; use proxmox_config_digest::ConfigDigest; -use proxmox_schema::{ApiType, ObjectSchema}; -use proxmox_section_config::{SectionConfig, SectionConfigData, SectionConfigPlugin}; -use serde_json::Value; -use tracing::error; +use proxmox_schema::{ApiType, api}; +use proxmox_section_config::typed::{ApiSectionDataEntry, SectionConfigData}; +use proxmox_section_config::{SectionConfig, SectionConfigPlugin}; +use serde::{Deserialize, Serialize}; use crate::Error; use crate::api_types::{ BACKEND_NAME_SCHEMA, GOTIFY_TYPENAME, GotifyConfig, GotifyPrivateConfig, MATCHER_TYPENAME, - MatcherConfig, SENDMAIL_TYPENAME, SMTP_TYPENAME, SendmailConfig, SmtpConfig, SmtpPrivateConfig, - WEBHOOK_TYPENAME, WebhookConfig, WebhookPrivateConfig, + MatcherConfig, Origin, SENDMAIL_TYPENAME, SMTP_TYPENAME, SendmailConfig, SmtpConfig, + SmtpPrivateConfig, WEBHOOK_TYPENAME, WebhookConfig, WebhookPrivateConfig, }; -/// Section config schema for the public config file. -pub fn config_parser() -> &'static SectionConfig { - static CONFIG: OnceLock = OnceLock::new(); - CONFIG.get_or_init(config_init) -} - -/// Section config schema for the private config file. -pub fn private_config_parser() -> &'static SectionConfig { - static CONFIG: OnceLock = OnceLock::new(); - CONFIG.get_or_init(private_config_init) -} - -fn config_init() -> SectionConfig { - let mut config = SectionConfig::new(&BACKEND_NAME_SCHEMA); - - { - const SENDMAIL_SCHEMA: &ObjectSchema = SendmailConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - SENDMAIL_TYPENAME.to_string(), - Some(String::from("name")), - SENDMAIL_SCHEMA, - )); - } - { - const SMTP_SCHEMA: &ObjectSchema = SmtpConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - SMTP_TYPENAME.to_string(), - Some(String::from("name")), - SMTP_SCHEMA, - )); - } - { - const GOTIFY_SCHEMA: &ObjectSchema = GotifyConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - GOTIFY_TYPENAME.to_string(), - Some(String::from("name")), - GOTIFY_SCHEMA, - )); - } - { - const WEBHOOK_SCHEMA: &ObjectSchema = WebhookConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - WEBHOOK_TYPENAME.to_string(), - Some(String::from("name")), - WEBHOOK_SCHEMA, - )); - } - - const MATCHER_SCHEMA: &ObjectSchema = MatcherConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - MATCHER_TYPENAME.to_string(), - Some(String::from("name")), - MATCHER_SCHEMA, - )); - - config -} - -fn private_config_init() -> SectionConfig { - let mut config = SectionConfig::new(&BACKEND_NAME_SCHEMA); - - const GOTIFY_SCHEMA: &ObjectSchema = GotifyPrivateConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - GOTIFY_TYPENAME.to_string(), - Some(String::from("name")), - GOTIFY_SCHEMA, - )); - - const SMTP_SCHEMA: &ObjectSchema = SmtpPrivateConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - SMTP_TYPENAME.to_string(), - Some(String::from("name")), - SMTP_SCHEMA, - )); - - const WEBHOOK_SCHEMA: &ObjectSchema = WebhookPrivateConfig::API_SCHEMA.unwrap_object_schema(); - config.register_plugin(SectionConfigPlugin::new( - WEBHOOK_TYPENAME.to_string(), - Some(String::from("name")), - WEBHOOK_SCHEMA, - )); - - config -} - -fn parse_config(raw_config: &str) -> Result<(SectionConfigData, ConfigDigest), Error> { +fn parse_config( + raw_config: &str, +) -> Result<(SectionConfigData, ConfigDigest), Error> { let digest = ConfigDigest::from_slice(raw_config.as_bytes()); - let data = config_parser() - .parse("notifications.cfg", raw_config) + let data = ConfigEntity::parse_section_config("notifications.cfg", raw_config) .map_err(Error::config_deserialization)?; Ok((data, digest)) } -fn parse_private_config(raw_config: &str) -> Result<(SectionConfigData, ConfigDigest), Error> { +fn parse_private_config( + raw_config: &str, +) -> Result<(SectionConfigData, ConfigDigest), Error> { let digest = ConfigDigest::from_slice(raw_config.as_bytes()); - let data = private_config_parser() - .parse("priv/notifications.cfg", raw_config) + let data = PrivateConfigEntity::parse_section_config("priv/notifications.cfg", raw_config) .map_err(Error::config_deserialization)?; Ok((data, digest)) } -fn write(config: &SectionConfigData) -> Result { - config_parser() - .write("notifications.cfg", config) - .map_err(Error::config_serialization) -} - -fn write_private(config: &SectionConfigData) -> Result { - private_config_parser() - .write("priv/notifications.cfg", config) - .map_err(Error::config_serialization) -} - /// Notification configuration -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct Config { - pub(crate) config: SectionConfigData, - pub(crate) private_config: SectionConfigData, + pub(crate) config: SectionConfigData, + pub(crate) private_config: SectionConfigData, digest: ConfigDigest, } @@ -141,53 +46,38 @@ impl Config { pub fn parse_section_config( raw_config: &str, raw_private_config: &str, - builtin_config: Option<&SectionConfigData>, + builtin_config: Option<&SectionConfigData>, ) -> Result { let (mut config, digest) = parse_config(raw_config)?; let (private_config, _) = parse_private_config(raw_private_config)?; if let Some(builtin_config) = builtin_config { - for (key, (builtin_typename, builtin_value)) in &builtin_config.sections { - if let Some((typename, value)) = config.sections.get_mut(key) { - if builtin_typename == typename && value == builtin_value { + for (key, builtin_value) in builtin_config { + if let Some(value) = config.get_mut(key) { + if value == builtin_value { // Entry is built-in and the config entry section in notifications.cfg // is exactly the same. - if let Some(obj) = value.as_object_mut() { - obj.insert("origin".to_string(), Value::String("builtin".into())); - } else { - error!("section config entry is not an object. This should not happen"); - } + value.set_origin(Some(Origin::Builtin)); } else { // Entry is built-in, but it has been modified by the user. - if let Some(obj) = value.as_object_mut() { - obj.insert( - "origin".to_string(), - Value::String("modified-builtin".into()), - ); - } else { - error!("section config entry is not an object. This should not happen"); - } + value.set_origin(Some(Origin::ModifiedBuiltin)); } } else { - let mut val = builtin_value.clone(); - - if let Some(obj) = val.as_object_mut() { - obj.insert("origin".to_string(), Value::String("builtin".into())); - } else { - error!("section config entry is not an object. This should not happen"); - } - config - .set_data(key, builtin_typename, val) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; + // If it doesn't exist, we insert the builtin + let mut value = builtin_value.clone(); + value.set_origin(Some(Origin::Builtin)); + config.insert(key.to_string(), value); } } } - for (_, (_, value)) in config.sections.iter_mut() { - if let Some(obj) = value.as_object_mut() { - if obj.get("origin").is_none() { - obj.insert("origin".to_string(), Value::String("user-created".into())); - } + let keys: Vec = config.keys().cloned().collect(); + + for key in keys { + if let Some(value) = config.get_mut(&key) + && value.origin().is_none() + { + value.set_origin(Some(Origin::UserCreated)); } } @@ -200,20 +90,48 @@ impl Config { /// Serialize config pub fn to_section_config(&self) -> Result<(String, String), Error> { - let mut c = self.config.clone(); - for (_, (_, value)) in c.sections.iter_mut() { - // Remove 'origin' parameter, we do not want it in our - // config fields - // TODO: Check if there is a better way for this, maybe a - // separate type for API responses? - if let Some(obj) = value.as_object_mut() { - obj.remove("origin"); - } else { - error!("section config entry is not an object. This should not happen"); + let mut configs_without_origin = SectionConfigData::default(); + + for (name, section) in &self.config { + match section { + ConfigEntity::Sendmail(config) => { + let mut config = config.clone(); + config.origin = None; + configs_without_origin.insert(name, ConfigEntity::Sendmail(config)); + } + ConfigEntity::Smtp(config) => { + let mut config = config.clone(); + config.origin = None; + configs_without_origin.insert(name, ConfigEntity::Smtp(config)); + } + ConfigEntity::Gotify(config) => { + let mut config = config.clone(); + config.origin = None; + configs_without_origin.insert(name, ConfigEntity::Gotify(config)); + } + ConfigEntity::Webhook(config) => { + let mut config = config.clone(); + config.origin = None; + configs_without_origin.insert(name, ConfigEntity::Webhook(config)); + } + ConfigEntity::Matcher(config) => { + let mut config = config.clone(); + config.origin = None; + configs_without_origin.insert(name, ConfigEntity::Matcher(config)); + } } } - Ok((write(&c)?, write_private(&self.private_config)?)) + let config_str = + ConfigEntity::write_section_config("notifications.cfg", &configs_without_origin) + .map_err(Error::config_serialization)?; + let private_config_str = PrivateConfigEntity::write_section_config( + "priv/notifications.cfg", + &self.private_config, + ) + .map_err(Error::config_serialization)?; + + Ok((config_str, private_config_str)) } /// Returns the SHA256 digest of the configuration. @@ -222,3 +140,168 @@ impl Config { &self.digest } } + +#[api] +/// Config entity in the notification config file. +#[derive(Clone, Deserialize, Serialize, PartialEq)] +#[serde(rename_all = "kebab-case", tag = "type")] +pub enum ConfigEntity { + /// Sendmail endpoint. + Sendmail(SendmailConfig), + /// Gotify endpoint. + Gotify(GotifyConfig), + /// SMTP endpoint. + Smtp(SmtpConfig), + /// Webhook endpoint. + Webhook(WebhookConfig), + /// Matcher configuration. + Matcher(MatcherConfig), +} + +impl ApiSectionDataEntry for ConfigEntity { + const INTERNALLY_TAGGED: Option<&'static str> = Some("type"); + + /// Get the `SectionConfig` configuration for this enum. + fn section_config() -> &'static SectionConfig { + static CONFIG: OnceLock = OnceLock::new(); + + CONFIG.get_or_init(|| { + let mut this = SectionConfig::new(&BACKEND_NAME_SCHEMA).with_type_key("type"); + this.register_plugin(SectionConfigPlugin::new( + SENDMAIL_TYPENAME.into(), + Some("name".to_string()), + SendmailConfig::API_SCHEMA.unwrap_object_schema(), + )); + this.register_plugin(SectionConfigPlugin::new( + MATCHER_TYPENAME.into(), + Some("name".to_string()), + MatcherConfig::API_SCHEMA.unwrap_object_schema(), + )); + this.register_plugin(SectionConfigPlugin::new( + SMTP_TYPENAME.into(), + Some("name".to_string()), + SmtpConfig::API_SCHEMA.unwrap_object_schema(), + )); + this.register_plugin(SectionConfigPlugin::new( + GOTIFY_TYPENAME.into(), + Some("name".to_string()), + GotifyConfig::API_SCHEMA.unwrap_object_schema(), + )); + this.register_plugin(SectionConfigPlugin::new( + WEBHOOK_TYPENAME.into(), + Some("name".to_string()), + WebhookConfig::API_SCHEMA.unwrap_object_schema(), + )); + this + }) + } + + /// Maps an enum value to its type name. + fn section_type(&self) -> &'static str { + match self { + ConfigEntity::Sendmail(_) => "sendmail", + ConfigEntity::Gotify(_) => "gotify", + ConfigEntity::Smtp(_) => "smtp", + ConfigEntity::Webhook(_) => "webhook", + ConfigEntity::Matcher(_) => "matcher", + } + } +} + +impl ConfigEntity { + pub(crate) fn set_origin(&mut self, origin: Option) { + match self { + ConfigEntity::Sendmail(config) => config.origin = origin, + ConfigEntity::Gotify(config) => config.origin = origin, + ConfigEntity::Smtp(config) => config.origin = origin, + ConfigEntity::Webhook(config) => config.origin = origin, + ConfigEntity::Matcher(config) => config.origin = origin, + } + } + + pub(crate) fn origin(&self) -> Option { + match self { + ConfigEntity::Sendmail(config) => config.origin, + ConfigEntity::Gotify(config) => config.origin, + ConfigEntity::Smtp(config) => config.origin, + ConfigEntity::Webhook(config) => config.origin, + ConfigEntity::Matcher(config) => config.origin, + } + } +} + +#[api] +/// Config entity in the private notification config file. +#[derive(Clone, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case", tag = "type")] +pub enum PrivateConfigEntity { + /// Private config for a gotify endpoint. + Gotify(GotifyPrivateConfig), + /// Private config for an SMTP endpoint. + Smtp(SmtpPrivateConfig), + /// Private config for a webhook endpoint. + Webhook(WebhookPrivateConfig), +} + +impl ApiSectionDataEntry for PrivateConfigEntity { + const INTERNALLY_TAGGED: Option<&'static str> = Some("type"); + + /// Get the `SectionConfig` configuration for this enum. + fn section_config() -> &'static SectionConfig { + static CONFIG: OnceLock = OnceLock::new(); + + CONFIG.get_or_init(|| { + let mut this = SectionConfig::new(&BACKEND_NAME_SCHEMA).with_type_key("type"); + this.register_plugin(SectionConfigPlugin::new( + SMTP_TYPENAME.into(), + Some("name".to_string()), + SmtpPrivateConfig::API_SCHEMA.unwrap_object_schema(), + )); + this.register_plugin(SectionConfigPlugin::new( + GOTIFY_TYPENAME.into(), + Some("name".to_string()), + GotifyPrivateConfig::API_SCHEMA.unwrap_object_schema(), + )); + this.register_plugin(SectionConfigPlugin::new( + WEBHOOK_TYPENAME.into(), + Some("name".to_string()), + WebhookPrivateConfig::API_SCHEMA.unwrap_object_schema(), + )); + this + }) + } + + /// Maps an enum value to its type name. + fn section_type(&self) -> &'static str { + match self { + PrivateConfigEntity::Gotify(_) => "gotify", + PrivateConfigEntity::Smtp(_) => "smtp", + PrivateConfigEntity::Webhook(_) => "webhook", + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const CONFIG_REF: &str = include_str!("../testdata/notifications.cfg.ref"); + const PRIV_CONFIG_REF: &str = include_str!("../testdata/notifications-priv.cfg.ref"); + + use pretty_assertions::assert_eq; + + #[test] + fn section_config_roundtrip() { + let config = Config::parse_section_config(CONFIG_REF, PRIV_CONFIG_REF, None).unwrap(); + + assert_eq!( + config.digest().to_string(), + "53554a97ca1747b69582f7cde5d4493f68b77c0d5946ce593a59547c9638d504" + ); + + let (public_config, private_config) = config.to_section_config().unwrap(); + + assert_eq!(public_config, CONFIG_REF); + assert_eq!(private_config, PRIV_CONFIG_REF); + } +} diff --git a/proxmox-notify/src/send.rs b/proxmox-notify/src/send.rs index a96b838df..210a42599 100644 --- a/proxmox-notify/src/send.rs +++ b/proxmox-notify/src/send.rs @@ -1,20 +1,18 @@ use std::collections::{HashMap, HashSet}; +use proxmox_section_config::typed::{convert_to_typed_array, lookup}; use proxmox_uuid::Uuid; -use serde::Deserialize; use serde_json::json; use tracing::{error, info}; -use crate::api_types::{GOTIFY_TYPENAME, GotifyConfig, GotifyPrivateConfig}; -use crate::api_types::{MATCHER_TYPENAME, MatcherConfig}; -use crate::api_types::{SENDMAIL_TYPENAME, SendmailConfig}; -use crate::api_types::{SMTP_TYPENAME, SmtpConfig, SmtpPrivateConfig}; -use crate::api_types::{WEBHOOK_TYPENAME, WebhookConfig, WebhookPrivateConfig}; +use crate::api_types::MatcherConfig; +use crate::config::{ConfigEntity, PrivateConfigEntity}; +use crate::endpoints::Endpoint; use crate::endpoints::gotify::GotifyEndpoint; use crate::endpoints::sendmail::SendmailEndpoint; use crate::endpoints::smtp::SmtpEndpoint; use crate::endpoints::webhook::WebhookEndpoint; -use crate::{Config, Content, Context, Endpoint, Error, Metadata, Notification, Severity}; +use crate::{Config, Content, Context, Error, Metadata, Notification, Severity}; /// Send a notification to a given target. /// @@ -47,64 +45,8 @@ struct Bus { matchers: Vec, } -macro_rules! parse_endpoints_with_private_config { - ($config:ident, $public_config:ty, $private_config:ty, $endpoint_type:ident, $type_name:expr) => { - (|| -> Result>, Error> { - let mut endpoints = Vec::>::new(); - - let configs: Vec<$public_config> = $config - .config - .convert_to_typed_array($type_name) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; - - for config in configs { - match $config.private_config.sections.get(&config.name) { - Some((section_type_name, private_config)) => { - if $type_name != section_type_name { - error!( - "Could not instantiate endpoint '{name}': \ - private config has wrong type", - name = config.name - ); - } - let private_config = <$private_config>::deserialize(private_config) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; - - endpoints.push(Box::new($endpoint_type { - config, - private_config: private_config.clone(), - })); - } - None => error!( - "Could not instantiate endpoint '{name}': \ - private config does not exist", - name = config.name - ), - } - } - - Ok(endpoints) - })() - }; -} - -macro_rules! parse_endpoints_without_private_config { - ($config:ident, $public_config:ty, $endpoint_type:ident, $type_name:expr) => { - (|| -> Result>, Error> { - let mut endpoints = Vec::>::new(); - - let configs: Vec<$public_config> = $config - .config - .convert_to_typed_array($type_name) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; - - for config in configs { - endpoints.push(Box::new($endpoint_type { config })); - } - - Ok(endpoints) - })() - }; +fn log_missing_private_config(endpoint_name: &str) { + error!("Could not instantiate endpoint '{endpoint_name}': private config does not exist"); } impl Bus { @@ -112,58 +54,73 @@ impl Bus { pub fn from_config(config: &Config) -> Result { let mut endpoints = HashMap::new(); - // Instantiate endpoints - endpoints.extend( - parse_endpoints_without_private_config!( - config, - SendmailConfig, - SendmailEndpoint, - SENDMAIL_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); + for endpoint_config in convert_to_typed_array!(config.config, ConfigEntity::Sendmail) { + endpoints.insert( + endpoint_config.name.clone(), + Box::new(SendmailEndpoint { + config: endpoint_config.clone(), + }) as Box, + ); + } - endpoints.extend( - parse_endpoints_with_private_config!( - config, - GotifyConfig, - GotifyPrivateConfig, - GotifyEndpoint, - GOTIFY_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); + for endpoint_config in convert_to_typed_array!(config.config, ConfigEntity::Gotify) { + if let Some(private_config) = lookup!( + config.private_config, + &endpoint_config.name, + PrivateConfigEntity::Gotify + ) { + endpoints.insert( + endpoint_config.name.clone(), + Box::new(GotifyEndpoint { + config: endpoint_config.clone(), + private_config: private_config.clone(), + }) as Box, + ); + } else { + log_missing_private_config(&endpoint_config.name); + } + } - endpoints.extend( - parse_endpoints_with_private_config!( - config, - SmtpConfig, - SmtpPrivateConfig, - SmtpEndpoint, - SMTP_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); + for endpoint_config in convert_to_typed_array!(config.config, ConfigEntity::Webhook) { + if let Some(private_config) = lookup!( + config.private_config, + &endpoint_config.name, + PrivateConfigEntity::Webhook + ) { + endpoints.insert( + endpoint_config.name.clone(), + Box::new(WebhookEndpoint { + config: endpoint_config.clone(), + private_config: private_config.clone(), + }) as Box, + ); + } else { + log_missing_private_config(&endpoint_config.name); + } + } - endpoints.extend( - parse_endpoints_with_private_config!( - config, - WebhookConfig, - WebhookPrivateConfig, - WebhookEndpoint, - WEBHOOK_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); + for endpoint_config in convert_to_typed_array!(config.config, ConfigEntity::Smtp) { + if let Some(private_config) = lookup!( + config.private_config, + &endpoint_config.name, + PrivateConfigEntity::Smtp + ) { + endpoints.insert( + endpoint_config.name.clone(), + Box::new(SmtpEndpoint { + config: endpoint_config.clone(), + private_config: private_config.clone(), + }) as Box, + ); + } else { + log_missing_private_config(&endpoint_config.name); + } + } - let matchers = config - .config - .convert_to_typed_array(MATCHER_TYPENAME) - .map_err(|err| Error::ConfigDeserialization(err.into()))?; + let matchers = convert_to_typed_array!(config.config, ConfigEntity::Matcher) + .into_iter() + .cloned() + .collect(); Ok(Bus { endpoints, diff --git a/proxmox-notify/testdata/notifications-priv.cfg.ref b/proxmox-notify/testdata/notifications-priv.cfg.ref new file mode 100644 index 000000000..fcf4d0dbe --- /dev/null +++ b/proxmox-notify/testdata/notifications-priv.cfg.ref @@ -0,0 +1,8 @@ +gotify: test-gotify + token test + +smtp: test-smtp + password password + +webhook: test-webhook + secret name=key,value=c2VjcmV0 diff --git a/proxmox-notify/testdata/notifications.cfg.ref b/proxmox-notify/testdata/notifications.cfg.ref new file mode 100644 index 000000000..53040973f --- /dev/null +++ b/proxmox-notify/testdata/notifications.cfg.ref @@ -0,0 +1,29 @@ +sendmail: mail-to-root + comment Send mails to root@pam's email address + mailto-user root@pam + +matcher: default-matcher + comment Route all notifications to mail-to-root + expression {"constant":true} + target mail-to-root + +gotify: test-gotify + comment some comment + server https://localhost:8000 + +smtp: test-smtp + author Proxmox VE (test) + comment some comment + from-address test@example.com + mailto test@example.com + mailto-user root@pam + mode tls + server mail.example.com + username testuser + +webhook: test-webhook + body c29tZXRoaW5n + comment some comment + header name=Content-Type,value=YXBwbGljYXRpb24vanNvbg== + method post + url https://localhost:8001 -- 2.47.3