From: Lukas Wagner <l.wagner@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH proxmox v2 23/63] notify: use typed SectionConfigData
Date: Wed, 18 Nov 2026 10:43:07 +0100 [thread overview]
Message-ID: <20261118094348.273646-24-l.wagner@proxmox.com> (raw)
In-Reply-To: <20261118094348.273646-1-l.wagner@proxmox.com>
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 <l.wagner@proxmox.com>
---
Notes:
Changes since v1:
- Use id-property and id-schema to simplify code.
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 | 40 +--
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 | 326 +++++++++---------
proxmox-notify/src/send.rs | 180 ++++------
.../testdata/notifications-priv.cfg.ref | 8 +
proxmox-notify/testdata/notifications.cfg.ref | 29 ++
11 files changed, 467 insertions(+), 565 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<Vec<GotifyConfig>, 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<Vec<GotifyConfig>, 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<GotifyConfig, HttpError> {
- 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::<GotifyPrivateConfig>(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<Vec<MatcherConfig>, 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<Vec<MatcherConfig>, 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<MatcherConfig, HttpError> {
- 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<MatcherConfig, HttpErr
/// Returns the endpoint or a `HttpError` if the matcher was not found (`404 Not found`).
#[cfg(feature = "legacy-matchers")]
pub fn get_matcher_as_expression(config: &Config, name: &str) -> Result<MatcherConfig, HttpError> {
- 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 43e448bc9..fb6ba9ad9 100644
--- a/proxmox-notify/src/api/mod.rs
+++ b/proxmox-notify/src/api/mod.rs
@@ -1,7 +1,5 @@
use std::collections::HashSet;
-use serde::{Deserialize, Serialize};
-
use proxmox_config_digest::ConfigDigest;
use proxmox_http_error::HttpError;
@@ -118,7 +116,7 @@ fn ensure_endpoints_exist<T: AsRef<str>>(
}
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"
@@ -141,14 +139,11 @@ fn get_referrers(config: &Config, entity: &str) -> Result<HashSet<String>, 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");
@@ -196,29 +191,6 @@ fn get_referenced_entities(config: &Config, entity: &str) -> HashSet<String> {
expanded
}
-fn set_private_config_entry<T: Serialize>(
- 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<Vec<SendmailConfig>, 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<Vec<SendmailConfig>, 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<SendmailConfig, HttpError> {
- 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<Vec<SmtpConfig>, 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<Vec<SmtpConfig>, 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<SmtpConfig, HttpError> {
- 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<Vec<WebhookConfig>, HttpError> {
- let mut endpoints: Vec<WebhookConfig> = config
- .config
- .convert_to_typed_array(WEBHOOK_TYPENAME)
- .map_err(|e| http_err!(NOT_FOUND, "Could not fetch endpoints: {e}"))?;
+ let mut endpoints: Vec<WebhookConfig> =
+ 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<Vec<WebhookConfig>, 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<WebhookConfig, HttpError> {
- 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<WebhookPrivateConfig> = 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::<WebhookPrivateConfig>(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::<WebhookPrivateConfig>(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::<WebhookPrivateConfig>(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..459e2f322 100644
--- a/proxmox-notify/src/config.rs
+++ b/proxmox-notify/src/config.rs
@@ -1,138 +1,40 @@
-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::api;
+use proxmox_schema::api_types::SAFE_ID_FORMAT;
+use proxmox_section_config::typed::{ApiSectionDataEntry, SectionConfigData};
+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,
+ GotifyConfig, GotifyPrivateConfig, MatcherConfig, Origin, SendmailConfig, SmtpConfig,
+ SmtpPrivateConfig, WebhookConfig, WebhookPrivateConfig,
};
-/// Section config schema for the public config file.
-pub fn config_parser() -> &'static SectionConfig {
- static CONFIG: OnceLock<SectionConfig> = 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<SectionConfig> = 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<ConfigEntity>, 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<PrivateConfigEntity>, 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<String, Error> {
- config_parser()
- .write("notifications.cfg", config)
- .map_err(Error::config_serialization)
-}
-
-fn write_private(config: &SectionConfigData) -> Result<String, Error> {
- 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<ConfigEntity>,
+ pub(crate) private_config: SectionConfigData<PrivateConfigEntity>,
digest: ConfigDigest,
}
@@ -141,53 +43,38 @@ impl Config {
pub fn parse_section_config(
raw_config: &str,
raw_private_config: &str,
- builtin_config: Option<&SectionConfigData>,
+ builtin_config: Option<&SectionConfigData<ConfigEntity>>,
) -> Result<Self, Error> {
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<String> = 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 +87,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 +137,98 @@ impl Config {
&self.digest
}
}
+
+#[api(
+ "id-property": "name",
+ "id-schema": {
+ type: String,
+ description: "Notification config entity name.",
+ min_length: 3,
+ max_length: 32,
+ format: &SAFE_ID_FORMAT,
+ },
+)]
+/// 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 ConfigEntity {
+ pub(crate) fn set_origin(&mut self, origin: Option<Origin>) {
+ 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<Origin> {
+ 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(
+ "id-property": "name",
+ "id-schema": {
+ type: String,
+ description: "Notification config entity name.",
+ min_length: 3,
+ max_length: 32,
+ format: &SAFE_ID_FORMAT,
+ },
+)]
+/// 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),
+}
+
+#[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 3cb9444c2..210a42599 100644
--- a/proxmox-notify/src/send.rs
+++ b/proxmox-notify/src/send.rs
@@ -1,15 +1,12 @@
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;
@@ -48,64 +45,8 @@ struct Bus {
matchers: Vec<MatcherConfig>,
}
-macro_rules! parse_endpoints_with_private_config {
- ($config:ident, $public_config:ty, $private_config:ty, $endpoint_type:ident, $type_name:expr) => {
- (|| -> Result<Vec<Box<dyn Endpoint>>, Error> {
- let mut endpoints = Vec::<Box<dyn Endpoint>>::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<Vec<Box<dyn Endpoint>>, Error> {
- let mut endpoints = Vec::<Box<dyn Endpoint>>::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 {
@@ -113,58 +54,73 @@ impl Bus {
pub fn from_config(config: &Config) -> Result<Self, Error> {
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<dyn Endpoint>,
+ );
+ }
- 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<dyn Endpoint>,
+ );
+ } 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<dyn Endpoint>,
+ );
+ } 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<dyn Endpoint>,
+ );
+ } 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
next prev parent reply other threads:[~2026-11-18 9:53 UTC|newest]
Thread overview: 66+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-11-18 9:42 [PATCH many v2 00/63] notify: maintenance, PDM preparations, queue + worker Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 01/63] notify: disallow `unsafe` code Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 02/63] notify: refactor error type Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 03/63] notify: move `Endpoint` trait to endpoint module as pub(crate) Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 04/63] notify: use ConfigDigest instead of raw byte arrays Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 05/63] notify: remove static context and pass context as parameter Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 06/63] notify: matcher: drop unused field matcher verifiers Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 07/63] notify: introduce 'send-impl', 'api-impl' and 'api-types' features Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 08/63] notify: matcher: make matcher validation methods public Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 09/63] notify: matcher: stub CalendarMatcher::matches on wasm32 Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 10/63] notify: make SendmailEndpoint and SmtpEndpoint private types Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 11/63] notify: move `send`, `test_target` and `Bus` to new `send` module Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 12/63] notify: move Origin type to api_types module Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 13/63] notify: move Target " Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 14/63] notify: move Config to config module Lukas Wagner
2026-11-18 9:42 ` [PATCH proxmox v2 15/63] notify: move Notification and sub-types to `notification` module Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 16/63] notify: move schema module to api_types Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 17/63] notify: move check_matches from api_types::matcher to send::Bus Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 18/63] notify: move TemplateSource to context module Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 19/63] notify: config: cleanup helper names and visibility Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 20/63] notify: config: rename section config parser/writer methods Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 21/63] notify: config: pass builtins explicitly when parsing section config Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 22/63] notify: implement PartialEq for all Config types Lukas Wagner
2026-11-18 9:43 ` Lukas Wagner [this message]
2026-11-18 9:43 ` [PATCH proxmox v2 24/63] notify: api: api types: rename Deleteable* -> Deletable* Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 25/63] notify: context: parse builtin config only once Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 26/63] notify: context: parse proxy config in trait impl, not at the callsite Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 27/63] notify: gate sub-modules with the appropriate feature flags Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 28/63] notify: fold mail-forwarder feature into send-impl Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 29/63] notify: forwarded mails: don't hardcode severity and metadata fields Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 30/63] notify: don't pass uid when instantiating forwarded mail notifications Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 31/63] notify: derive PartialEq for Notification type Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 32/63] notify: add getters for severity and fields on " Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 33/63] notify: add test suite for " Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 34/63] notify: serialize raw, forwarded mail content as base64 Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 35/63] notify: unify code paths for legacy-sendmail and regular notifications Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 36/63] notify: add backwards-compat note to Notification type Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 37/63] notify: remove 'test_target' API Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 38/63] notify: replace notification instantiation with builder pattern Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 39/63] notify: add send receipts Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 40/63] notify: make sure that template name matches SAFE_ID_REGEX Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 41/63] notify: implement notification queue submitter Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 42/63] notify: context: add read_config Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 43/63] notify: queue: add queue consumer Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox v2 44/63] notify: queue: add worker task Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-backup v2 45/63] notifications: don't ignore verification errors in legacy-sendmail mode Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-backup v2 46/63] notifications: adapt to proxmox-notify API changes Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-backup v2 47/63] api: notification: send test notification via proxmox_notify::send Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-backup v2 48/63] notifications: send all notifications via proxmox-notify's queue Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-perl-rs v2 49/63] pve: notify: adapt to changes in the public API of proxmox-notify Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-perl-rs v2 50/63] pve: notify: add `PVE::RS::Notify::enqueue` method Lukas Wagner
2026-11-18 9:43 ` [PATCH pve-cluster v2 51/63] notify: send notifications via notification queue Lukas Wagner
2026-11-18 9:43 ` [PATCH manager v2 52/63] vzdump: send legacy-sendmail notifications via simplified API Lukas Wagner
2026-11-18 9:43 ` [PATCH manager v2 53/63] debian: create notification queue directory via tmpfiles Lukas Wagner
2026-11-18 9:43 ` [PATCH manager v2 54/63] debian: add 'pve-notify-worker' as dependecy Lukas Wagner
2026-11-18 9:43 ` [PATCH manager v2 55/63] api: services: add 'pve-notify-worker' as known service Lukas Wagner
2026-11-18 9:43 ` [PATCH manager v2 56/63] services: request pve-notify-worker.service via Wants Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 57/63] forward mails via notification queue Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 58/63] use return code to signal permanent or temporary failure Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 59/63] limit size of mail read from stdin Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 60/63] cargo: move mail forwarder into a workspace member crate Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 61/63] add crate for code shared between the mail-forwarder and the worker Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 62/63] add pve-notify-worker crate and package Lukas Wagner
2026-11-18 9:43 ` [PATCH proxmox-mail-forward v2 63/63] debian: add versioned break for pve-manager and proxmox-backup-server Lukas Wagner
2026-11-18 21:44 ` [PATCH many v2 00/63] notify: maintenance, PDM preparations, queue + worker Thomas Lamprecht
2026-11-19 10:45 ` Lukas Wagner
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261118094348.273646-24-l.wagner@proxmox.com \
--to=l.wagner@proxmox.com \
--cc=pve-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox