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 5AD981FF0B7 for ; Fri, 13 Nov 2026 16:18:32 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 953D321DE6; Fri, 13 Nov 2026 16:10:24 +0100 (CET) From: Lukas Wagner To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox 07/55] notify: introduce 'send-impl', 'api-impl' and 'api-types' features Date: Fri, 13 Nov 2026 16:07:40 +0100 Message-ID: <20261113150828.756836-8-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: 1794582523837 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.151 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) PROLO_LEO1 0.1 Meta Catches all Leo drug variations so far 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: 3O3M3H7KBER5BNV347THFYGUYS5GPXVJ X-Message-ID-Hash: 3O3M3H7KBER5BNV347THFYGUYS5GPXVJ 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: The old per-endpoint-type features turned out to be not super useful (all products support all endpoints), so they were merged into a single 'send-impl' feature. In anticipation of a Rust-based UI for changing notification configuration, a new 'api-types' feature was introduced and the config types for endpoints and matchers moved to a new 'api_types' module. Furthermore, the existing API method implementation is now gated behind the 'api-impl' feature. This change only moves existing code and modifies feature gates. It is inherently a breaking change, but does not change functionality. Signed-off-by: Lukas Wagner --- proxmox-notify/Cargo.toml | 51 +++-- proxmox-notify/src/api/gotify.rs | 2 +- proxmox-notify/src/api/matcher.rs | 8 +- proxmox-notify/src/api/mod.rs | 45 +--- proxmox-notify/src/api/sendmail.rs | 2 +- proxmox-notify/src/api/smtp.rs | 5 +- proxmox-notify/src/api/webhook.rs | 4 +- proxmox-notify/src/api_types/gotify.rs | 68 ++++++ .../src/{ => api_types}/matcher/calendar.rs | 4 +- .../src/{ => api_types}/matcher/expression.rs | 2 +- .../src/{ => api_types}/matcher/field.rs | 2 +- .../src/{ => api_types}/matcher/mod.rs | 4 +- .../src/{ => api_types}/matcher/severity.rs | 2 +- proxmox-notify/src/api_types/mod.rs | 21 ++ proxmox-notify/src/api_types/sendmail.rs | 96 ++++++++ proxmox-notify/src/api_types/smtp.rs | 136 +++++++++++ proxmox-notify/src/api_types/webhook.rs | 208 +++++++++++++++++ proxmox-notify/src/config.rs | 70 ++---- proxmox-notify/src/context/pbs.rs | 3 +- proxmox-notify/src/context/pve.rs | 3 +- proxmox-notify/src/endpoints/common/mod.rs | 1 - proxmox-notify/src/endpoints/gotify.rs | 72 +----- proxmox-notify/src/endpoints/mod.rs | 4 - proxmox-notify/src/endpoints/sendmail.rs | 96 +------- proxmox-notify/src/endpoints/smtp.rs | 138 +----------- proxmox-notify/src/endpoints/webhook.rs | 213 +----------------- proxmox-notify/src/lib.rs | 139 ++++++------ 27 files changed, 694 insertions(+), 705 deletions(-) create mode 100644 proxmox-notify/src/api_types/gotify.rs rename proxmox-notify/src/{ => api_types}/matcher/calendar.rs (96%) rename proxmox-notify/src/{ => api_types}/matcher/expression.rs (98%) rename proxmox-notify/src/{ => api_types}/matcher/field.rs (99%) rename proxmox-notify/src/{ => api_types}/matcher/mod.rs (99%) rename proxmox-notify/src/{ => api_types}/matcher/severity.rs (97%) create mode 100644 proxmox-notify/src/api_types/mod.rs create mode 100644 proxmox-notify/src/api_types/sendmail.rs create mode 100644 proxmox-notify/src/api_types/smtp.rs create mode 100644 proxmox-notify/src/api_types/webhook.rs diff --git a/proxmox-notify/Cargo.toml b/proxmox-notify/Cargo.toml index 2c085ae68..6bb4871f7 100644 --- a/proxmox-notify/Cargo.toml +++ b/proxmox-notify/Cargo.toml @@ -13,27 +13,27 @@ rust-version.workspace = true [dependencies] const_format.workspace = true -handlebars = { workspace = true } +handlebars = { workspace = true, optional = true } http = { workspace = true, optional = true } lettre = { workspace = true, optional = true } tracing.workspace = true mail-parser = { workspace = true, optional = true } percent-encoding = { workspace = true, optional = true } -regex.workspace = true +regex = { workspace = true, optional = true } serde = { workspace = true, features = ["derive"] } serde_json.workspace = true -serde_regex.workspace = true +serde_regex = { workspace = true, optional = true } thiserror.workspace = true -proxmox-api-macro.workspace = true +proxmox-api-macro = { workspace = true, optional = true } proxmox-base64 = { workspace = true, optional = true } -proxmox-config-digest = { workspace = true, features = ["openssl"] } +proxmox-config-digest = { workspace = true, features = ["openssl"], optional = true } proxmox-http = { workspace = true, features = ["client-sync"], optional = true } -proxmox-http-error.workspace = true -proxmox-human-byte.workspace = true -proxmox-match-expression.workspace = true +proxmox-http-error = { workspace = true, optional = true } +proxmox-human-byte = { workspace = true, optional = true } +proxmox-match-expression = { workspace = true, optional = true } proxmox-schema = { workspace = true, features = ["api-macro", "api-types"] } -proxmox-section-config = { workspace = true } +proxmox-section-config = { workspace = true, optional = true } proxmox-serde.workspace = true proxmox-sendmail = { workspace = true, optional = true } proxmox-sys = { workspace = true, optional = true } @@ -41,12 +41,35 @@ proxmox-time.workspace = true proxmox-uuid = { workspace = true, features = ["serde"] } [features] -default = ["sendmail", "gotify", "smtp", "webhook"] +default = ["send-impl", "api-types"] +api-impl = [ + "api-types", + "dep:proxmox-config-digest", + "dep:proxmox-http-error", + "dep:proxmox-section-config", +] +api-types = [ + "dep:proxmox-api-macro", + "dep:proxmox-base64", + "dep:proxmox-match-expression", + "dep:regex", + "dep:serde_regex", +] +send-impl = [ + "api-types", + "dep:http", + "dep:lettre", + "dep:handlebars", + "dep:proxmox-config-digest", + "dep:percent-encoding", + "dep:proxmox-base64", + "dep:proxmox-http", + "dep:proxmox-human-byte", + "dep:proxmox-section-config", + "dep:proxmox-sendmail", + "dep:proxmox-sys", +] mail-forwarder = ["dep:mail-parser", "dep:proxmox-sys", "proxmox-sendmail/mail-forwarder"] -sendmail = ["dep:proxmox-sys", "dep:proxmox-sendmail"] -gotify = ["dep:proxmox-http", "dep:http"] pve-context = ["dep:proxmox-sys", "legacy-matchers"] pbs-context = ["dep:proxmox-sys", "legacy-matchers"] -smtp = ["dep:lettre"] -webhook = ["dep:http", "dep:percent-encoding", "dep:proxmox-base64", "dep:proxmox-http"] legacy-matchers = [] diff --git a/proxmox-notify/src/api/gotify.rs b/proxmox-notify/src/api/gotify.rs index c3149c152..fc56d250b 100644 --- a/proxmox-notify/src/api/gotify.rs +++ b/proxmox-notify/src/api/gotify.rs @@ -3,7 +3,7 @@ use proxmox_http_error::HttpError; use crate::Config; use crate::api::http_err; -use crate::endpoints::gotify::{ +use crate::api_types::{ DeleteableGotifyProperty, GOTIFY_TYPENAME, GotifyConfig, GotifyConfigUpdater, GotifyPrivateConfig, GotifyPrivateConfigUpdater, }; diff --git a/proxmox-notify/src/api/matcher.rs b/proxmox-notify/src/api/matcher.rs index 4600063e2..1994cb65c 100644 --- a/proxmox-notify/src/api/matcher.rs +++ b/proxmox-notify/src/api/matcher.rs @@ -3,7 +3,7 @@ use proxmox_http_error::HttpError; use crate::Config; use crate::api::http_err; -use crate::matcher::{ +use crate::api_types::{ DeleteableMatcherProperty, MATCHER_TYPENAME, MatcherConfig, MatcherConfigUpdater, }; @@ -204,13 +204,13 @@ pub fn delete_matcher(config: &mut Config, name: &str) -> Result<(), HttpError> Ok(()) } -#[cfg(all(test, feature = "sendmail"))] +#[cfg(all(test, feature = "send-impl"))] mod tests { use proxmox_match_expression::Expression; use super::*; - use crate::{context::test::test_context, matcher::expression::NotificationMatcher}; + use crate::{api_types::expression::NotificationMatcher, context::test::test_context}; fn empty_config() -> Config { let context = test_context(); @@ -266,7 +266,7 @@ matcher: matcher2 #[test] #[cfg(feature = "legacy-matchers")] fn test_matcher_update() -> Result<(), HttpError> { - use crate::matcher::MatchModeOperator; + use crate::api_types::MatchModeOperator; let mut config = config_with_two_matchers(); diff --git a/proxmox-notify/src/api/mod.rs b/proxmox-notify/src/api/mod.rs index 0ae71acfe..0dbb15b91 100644 --- a/proxmox-notify/src/api/mod.rs +++ b/proxmox-notify/src/api/mod.rs @@ -9,14 +9,10 @@ use proxmox_schema::api; use crate::{Config, Origin}; pub mod common; -#[cfg(feature = "gotify")] pub mod gotify; pub mod matcher; -#[cfg(feature = "sendmail")] pub mod sendmail; -#[cfg(feature = "smtp")] pub mod smtp; -#[cfg(feature = "webhook")] pub mod webhook; // We have our own, local versions of http_err and http_bail, because @@ -49,16 +45,12 @@ pub use http_err; /// Type of the endpoint. pub enum EndpointType { /// Sendmail endpoint - #[cfg(feature = "sendmail")] Sendmail, /// SMTP endpoint - #[cfg(feature = "smtp")] Smtp, /// Gotify endpoint - #[cfg(feature = "gotify")] Gotify, /// Webhook endpoint - #[cfg(feature = "webhook")] Webhook, } @@ -86,7 +78,6 @@ pub struct Target { pub fn get_targets(config: &Config) -> Result, HttpError> { let mut targets = Vec::new(); - #[cfg(feature = "gotify")] for endpoint in gotify::get_endpoints(config)? { targets.push(Target { name: endpoint.name, @@ -97,7 +88,6 @@ pub fn get_targets(config: &Config) -> Result, HttpError> { }) } - #[cfg(feature = "sendmail")] for endpoint in sendmail::get_endpoints(config)? { targets.push(Target { name: endpoint.name, @@ -108,7 +98,6 @@ pub fn get_targets(config: &Config) -> Result, HttpError> { }) } - #[cfg(feature = "smtp")] for endpoint in smtp::get_endpoints(config)? { targets.push(Target { name: endpoint.name, @@ -119,7 +108,6 @@ pub fn get_targets(config: &Config) -> Result, HttpError> { }) } - #[cfg(feature = "webhook")] for endpoint in webhook::get_endpoints(config)? { targets.push(Target { name: endpoint.name, @@ -146,26 +134,11 @@ fn verify_digest(config: &Config, digest: Option) -> Result<(), Ht Ok(()) } -fn ensure_endpoint_exists(#[allow(unused)] config: &Config, name: &str) -> Result<(), HttpError> { - #[allow(unused_mut)] - let mut exists = false; - - #[cfg(feature = "sendmail")] - { - exists = exists || sendmail::get_endpoint(config, name).is_ok(); - } - #[cfg(feature = "gotify")] - { - exists = exists || gotify::get_endpoint(config, name).is_ok(); - } - #[cfg(feature = "smtp")] - { - exists = exists || smtp::get_endpoint(config, name).is_ok(); - } - #[cfg(feature = "webhook")] - { - exists = exists || webhook::get_endpoint(config, name).is_ok(); - } +fn ensure_endpoint_exists(config: &Config, name: &str) -> Result<(), HttpError> { + let mut exists = sendmail::get_endpoint(config, name).is_ok(); + exists = exists || gotify::get_endpoint(config, name).is_ok(); + exists = exists || smtp::get_endpoint(config, name).is_ok(); + exists = exists || webhook::get_endpoint(config, name).is_ok(); if !exists { http_bail!(NOT_FOUND, "endpoint '{name}' does not exist") @@ -264,7 +237,6 @@ fn get_referenced_entities(config: &Config, entity: &str) -> HashSet { expanded } -#[allow(unused)] fn set_private_config_entry( config: &mut Config, private_config: T, @@ -283,7 +255,6 @@ fn set_private_config_entry( }) } -#[allow(unused)] fn remove_private_config_entry(config: &mut Config, name: &str) -> Result<(), HttpError> { config.private_config.sections.remove(name); Ok(()) @@ -300,12 +271,10 @@ mod test_helpers { } } -#[cfg(all(test, feature = "gotify", feature = "sendmail"))] +#[cfg(test)] mod tests { use super::*; - use crate::endpoints::gotify::{GotifyConfig, GotifyPrivateConfig}; - use crate::endpoints::sendmail::SendmailConfig; - use crate::matcher::MatcherConfig; + use crate::api_types::{GotifyConfig, GotifyPrivateConfig, MatcherConfig, SendmailConfig}; fn prepare_config() -> Result { let mut config = test_helpers::empty_config(); diff --git a/proxmox-notify/src/api/sendmail.rs b/proxmox-notify/src/api/sendmail.rs index 2d54608cd..aecc69b38 100644 --- a/proxmox-notify/src/api/sendmail.rs +++ b/proxmox-notify/src/api/sendmail.rs @@ -3,7 +3,7 @@ use proxmox_http_error::HttpError; use crate::Config; use crate::api::{http_bail, http_err}; -use crate::endpoints::sendmail::{ +use crate::api_types::{ DeleteableSendmailProperty, SENDMAIL_TYPENAME, SendmailConfig, SendmailConfigUpdater, }; diff --git a/proxmox-notify/src/api/smtp.rs b/proxmox-notify/src/api/smtp.rs index 456cbc31e..f36a51e8c 100644 --- a/proxmox-notify/src/api/smtp.rs +++ b/proxmox-notify/src/api/smtp.rs @@ -3,7 +3,7 @@ use proxmox_http_error::HttpError; use crate::Config; use crate::api::{http_bail, http_err}; -use crate::endpoints::smtp::{ +use crate::api_types::{ DeleteableSmtpProperty, SMTP_TYPENAME, SmtpConfig, SmtpConfigUpdater, SmtpPrivateConfig, SmtpPrivateConfigUpdater, }; @@ -204,8 +204,7 @@ pub fn delete_endpoint(config: &mut Config, name: &str) -> Result<(), HttpError> #[cfg(test)] pub mod tests { use super::*; - use crate::api::test_helpers::*; - use crate::endpoints::smtp::SmtpMode; + use crate::{api::test_helpers::*, api_types::SmtpMode}; pub fn add_smtp_endpoint_for_test(config: &mut Config, name: &str) -> Result<(), HttpError> { add_endpoint( diff --git a/proxmox-notify/src/api/webhook.rs b/proxmox-notify/src/api/webhook.rs index e79eeb7e9..8755eb291 100644 --- a/proxmox-notify/src/api/webhook.rs +++ b/proxmox-notify/src/api/webhook.rs @@ -7,7 +7,7 @@ use proxmox_http_error::HttpError; use proxmox_schema::property_string::PropertyString; use crate::api::http_err; -use crate::endpoints::webhook::{ +use crate::api_types::{ DeleteableWebhookProperty, KeyAndBase64Val, WEBHOOK_TYPENAME, WebhookConfig, WebhookConfigUpdater, WebhookPrivateConfig, }; @@ -293,7 +293,7 @@ pub fn delete_endpoint(config: &mut Config, name: &str) -> Result<(), HttpError> #[cfg(test)] mod tests { use super::*; - use crate::{api::test_helpers::empty_config, endpoints::webhook::HttpMethod}; + use crate::{api::test_helpers::empty_config, api_types::HttpMethod}; pub fn add_default_webhook_endpoint(config: &mut Config) -> Result<(), HttpError> { add_endpoint( diff --git a/proxmox-notify/src/api_types/gotify.rs b/proxmox-notify/src/api_types/gotify.rs new file mode 100644 index 000000000..48193ff3c --- /dev/null +++ b/proxmox-notify/src/api_types/gotify.rs @@ -0,0 +1,68 @@ +use serde::{Deserialize, Serialize}; + +use proxmox_schema::{Updater, api, api_types::COMMENT_SCHEMA}; + +use crate::{Origin, schema::ENTITY_NAME_SCHEMA}; + +pub const GOTIFY_TYPENAME: &str = "gotify"; + +#[api( + properties: { + name: { + schema: ENTITY_NAME_SCHEMA, + }, + comment: { + optional: true, + schema: COMMENT_SCHEMA, + }, + } +)] +#[derive(Serialize, Deserialize, Updater, Default)] +#[serde(rename_all = "kebab-case")] +/// Config for Gotify notification endpoints +pub struct GotifyConfig { + /// Name of the endpoint. + #[updater(skip)] + pub name: String, + /// Gotify Server URL. + pub server: String, + /// Comment. + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + /// Deprecated. + #[serde(skip_serializing)] + #[updater(skip)] + pub filter: Option, + /// Disable this target. + #[serde(skip_serializing_if = "Option::is_none")] + pub disable: Option, + /// Origin of this config entry. + #[serde(skip_serializing_if = "Option::is_none")] + #[updater(skip)] + pub origin: Option, +} + +#[api] +#[derive(Serialize, Deserialize, Clone, Updater)] +#[serde(rename_all = "kebab-case")] +/// Private configuration for Gotify notification endpoints. +/// This config will be saved to a separate configuration file with stricter +/// permissions (root:root 0600) +pub struct GotifyPrivateConfig { + /// Name of the endpoint + #[updater(skip)] + pub name: String, + /// Authentication token + pub token: String, +} + +#[api] +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +/// The set of properties that can be deleted from a gotify endpoint configuration. +pub enum DeleteableGotifyProperty { + /// Delete `comment` + Comment, + /// Delete `disable` + Disable, +} diff --git a/proxmox-notify/src/matcher/calendar.rs b/proxmox-notify/src/api_types/matcher/calendar.rs similarity index 96% rename from proxmox-notify/src/matcher/calendar.rs rename to proxmox-notify/src/api_types/matcher/calendar.rs index 72af94102..0a8d31e7a 100644 --- a/proxmox-notify/src/matcher/calendar.rs +++ b/proxmox-notify/src/api_types/matcher/calendar.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use proxmox_time::DailyDuration; -use crate::{Error, Notification, matcher::expression::NotificationMatcher}; +use crate::{Error, Notification, api_types::expression::NotificationMatcher}; use super::MatchDirective; @@ -127,7 +127,7 @@ pub use inline::*; mod test { use serde_json::Value; - use crate::{Notification, Severity, matcher::MatchDirective as _}; + use crate::{Notification, Severity}; use super::*; diff --git a/proxmox-notify/src/matcher/expression.rs b/proxmox-notify/src/api_types/matcher/expression.rs similarity index 98% rename from proxmox-notify/src/matcher/expression.rs rename to proxmox-notify/src/api_types/matcher/expression.rs index df9fe439d..4c062caeb 100644 --- a/proxmox-notify/src/matcher/expression.rs +++ b/proxmox-notify/src/api_types/matcher/expression.rs @@ -35,7 +35,7 @@ impl MatchExpression for NotificationMatcher { impl NotificationMatcher { /// Validate any additional constraints that cannot be expressed in the type system. pub(crate) fn validate(&self) -> Result<(), Error> { - use crate::matcher::MatchDirective; + use crate::api_types::matcher::MatchDirective; match self { NotificationMatcher::Field(field_matcher) => field_matcher.validate(), diff --git a/proxmox-notify/src/matcher/field.rs b/proxmox-notify/src/api_types/matcher/field.rs similarity index 99% rename from proxmox-notify/src/matcher/field.rs rename to proxmox-notify/src/api_types/matcher/field.rs index f609421ce..b1ea25302 100644 --- a/proxmox-notify/src/matcher/field.rs +++ b/proxmox-notify/src/api_types/matcher/field.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use proxmox_match_expression::Expression; use proxmox_schema::api_types::SAFE_ID_REGEX; -use crate::{Error, Notification, matcher::expression::NotificationMatcher}; +use crate::{Error, Notification, api_types::expression::NotificationMatcher}; use super::MatchDirective; diff --git a/proxmox-notify/src/matcher/mod.rs b/proxmox-notify/src/api_types/matcher/mod.rs similarity index 99% rename from proxmox-notify/src/matcher/mod.rs rename to proxmox-notify/src/api_types/matcher/mod.rs index 59baeae4e..8f0bc7405 100644 --- a/proxmox-notify/src/matcher/mod.rs +++ b/proxmox-notify/src/api_types/matcher/mod.rs @@ -9,7 +9,6 @@ use proxmox_api_macro::api; use proxmox_schema::Updater; use proxmox_schema::api_types::COMMENT_SCHEMA; -use crate::matcher::expression::NotificationMatcher; use crate::schema::ENTITY_NAME_SCHEMA; use crate::{Error, Notification, Origin}; @@ -18,9 +17,12 @@ pub mod expression; pub mod field; pub mod severity; +use expression::NotificationMatcher; + pub const MATCHER_TYPENAME: &str = "matcher"; #[api] +#[cfg(feature = "legacy-matchers")] #[derive(Debug, Serialize, Deserialize, Default, Clone, Copy)] #[serde(rename_all = "kebab-case")] /// The mode in which the results of matches are combined. diff --git a/proxmox-notify/src/matcher/severity.rs b/proxmox-notify/src/api_types/matcher/severity.rs similarity index 97% rename from proxmox-notify/src/matcher/severity.rs rename to proxmox-notify/src/api_types/matcher/severity.rs index 6818e5c22..2d68a46bb 100644 --- a/proxmox-notify/src/matcher/severity.rs +++ b/proxmox-notify/src/api_types/matcher/severity.rs @@ -1,7 +1,7 @@ use proxmox_match_expression::Expression; use serde::{Deserialize, Serialize}; -use crate::{Error, Notification, Severity, matcher::expression::NotificationMatcher}; +use crate::{Error, Notification, Severity, api_types::expression::NotificationMatcher}; use super::MatchDirective; diff --git a/proxmox-notify/src/api_types/mod.rs b/proxmox-notify/src/api_types/mod.rs new file mode 100644 index 000000000..443dea336 --- /dev/null +++ b/proxmox-notify/src/api_types/mod.rs @@ -0,0 +1,21 @@ +//! API types for the notification system. +//! +//! Contains the schema-annotated types used for +//! - endpoint and matcher configuration +//! - the generic target listing +//! - send receipts. + +mod gotify; +pub use gotify::*; + +mod sendmail; +pub use sendmail::*; + +mod webhook; +pub use webhook::*; + +mod smtp; +pub use smtp::*; + +mod matcher; +pub use matcher::*; diff --git a/proxmox-notify/src/api_types/sendmail.rs b/proxmox-notify/src/api_types/sendmail.rs new file mode 100644 index 000000000..921970265 --- /dev/null +++ b/proxmox-notify/src/api_types/sendmail.rs @@ -0,0 +1,96 @@ +use serde::{Deserialize, Serialize}; + +use proxmox_schema::{Updater, api, api_types::COMMENT_SCHEMA}; + +use crate::{ + Origin, + schema::{EMAIL_SCHEMA, ENTITY_NAME_SCHEMA, USER_SCHEMA}, +}; + +pub const SENDMAIL_TYPENAME: &str = "sendmail"; + +#[api( + properties: { + name: { + schema: ENTITY_NAME_SCHEMA, + }, + mailto: { + type: Array, + items: { + schema: EMAIL_SCHEMA, + }, + optional: true, + }, + "mailto-user": { + type: Array, + items: { + schema: USER_SCHEMA, + }, + optional: true, + }, + comment: { + optional: true, + schema: COMMENT_SCHEMA, + }, + }, +)] +#[derive(Debug, Serialize, Deserialize, Updater, Default)] +#[serde(rename_all = "kebab-case")] +/// Config for Sendmail notification endpoints +pub struct SendmailConfig { + /// Name of the endpoint + #[updater(skip)] + pub name: String, + /// Mail address to send a mail to. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + pub mailto: Vec, + /// Users to send a mail to. The email address of the user + /// will be looked up in users.cfg. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + pub mailto_user: Vec, + /// `From` address for sent E-Mails. + /// If the parameter is not set, the plugin will fall back to the + /// email-from setting from node.cfg (PBS). + /// If that is also not set, the plugin will default to root@$hostname, + /// where $hostname is the hostname of the node. + #[serde(skip_serializing_if = "Option::is_none")] + pub from_address: Option, + /// Author of the mail. Defaults to 'Proxmox Backup Server ($hostname)' + #[serde(skip_serializing_if = "Option::is_none")] + pub author: Option, + /// Comment. + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + /// Deprecated. + #[serde(skip_serializing)] + #[updater(skip)] + pub filter: Option, + /// Disable this target. + #[serde(skip_serializing_if = "Option::is_none")] + pub disable: Option, + /// Origin of this config entry. + #[serde(skip_serializing_if = "Option::is_none")] + #[updater(skip)] + pub origin: Option, +} + +#[api] +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +/// The set of properties that can be deleted from a sendmail endpoint configuration. +pub enum DeleteableSendmailProperty { + /// Delete `author` + Author, + /// Delete `comment` + Comment, + /// Delete `disable` + Disable, + /// Delete `from-address` + FromAddress, + /// Delete `mailto` + Mailto, + /// Delete `mailto-user` + MailtoUser, +} diff --git a/proxmox-notify/src/api_types/smtp.rs b/proxmox-notify/src/api_types/smtp.rs new file mode 100644 index 000000000..d30f1dfee --- /dev/null +++ b/proxmox-notify/src/api_types/smtp.rs @@ -0,0 +1,136 @@ +use serde::{Deserialize, Serialize}; + +use proxmox_schema::{Updater, api, api_types::COMMENT_SCHEMA}; + +use crate::Origin; +use crate::schema::{EMAIL_SCHEMA, ENTITY_NAME_SCHEMA, USER_SCHEMA}; + +pub const SMTP_TYPENAME: &str = "smtp"; + +#[api] +#[derive(Debug, Serialize, Deserialize, Default, Clone, Copy)] +#[serde(rename_all = "kebab-case")] +/// Connection security +pub enum SmtpMode { + /// No encryption (insecure), plain SMTP + Insecure, + /// Upgrade to TLS after connecting + #[serde(rename = "starttls")] + StartTls, + /// Use TLS-secured connection + #[default] + Tls, +} + +#[api( + properties: { + name: { + schema: ENTITY_NAME_SCHEMA, + }, + mailto: { + type: Array, + items: { + schema: EMAIL_SCHEMA, + }, + optional: true, + }, + "mailto-user": { + type: Array, + items: { + schema: USER_SCHEMA, + }, + optional: true, + }, + comment: { + optional: true, + schema: COMMENT_SCHEMA, + }, + }, +)] +#[derive(Debug, Serialize, Deserialize, Updater, Default)] +#[serde(rename_all = "kebab-case")] +/// Config for Sendmail notification endpoints +pub struct SmtpConfig { + /// Name of the endpoint. + #[updater(skip)] + pub name: String, + /// Host name or IP of the SMTP relay. + pub server: String, + /// The port to connect to. + /// If not set, the used port defaults to 25 (insecure), 465 (tls) + /// or 587 (starttls), depending on the value of mode + #[serde(skip_serializing_if = "Option::is_none")] + pub port: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// Username to use during authentication. + /// If no username is set, no authentication will be performed. + /// The PLAIN and LOGIN authentication methods are supported + #[serde(skip_serializing_if = "Option::is_none")] + pub username: Option, + /// Mail address to send a mail to. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + pub mailto: Vec, + /// Users to send a mail to. The email address of the user + /// will be looked up in users.cfg. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + pub mailto_user: Vec, + /// `From` address for the mail. + /// SMTP relays might require that this address is owned by the user + /// in order to avoid spoofing. The `From` header in the email will be + /// set to `$author <$from-address>`. + pub from_address: String, + /// Author of the mail. Defaults to 'Proxmox Backup Server ($hostname)' + #[serde(skip_serializing_if = "Option::is_none")] + pub author: Option, + /// Comment. + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + /// Disable this target. + #[serde(skip_serializing_if = "Option::is_none")] + pub disable: Option, + /// Origin of this config entry. + #[serde(skip_serializing_if = "Option::is_none")] + #[updater(skip)] + pub origin: Option, +} + +#[api] +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +/// The set of properties that can be deleted from a smtp endpoint configuration. +pub enum DeleteableSmtpProperty { + /// Delete `author` + Author, + /// Delete `comment` + Comment, + /// Delete `disable` + Disable, + /// Delete `mailto` + Mailto, + /// Delete `mailto-user` + MailtoUser, + /// Delete `password` + Password, + /// Delete `port` + Port, + /// Delete `username` + Username, +} + +#[api] +#[derive(Serialize, Deserialize, Clone, Updater, Debug)] +#[serde(rename_all = "kebab-case")] +/// Private configuration for SMTP notification endpoints. +/// This config will be saved to a separate configuration file with stricter +/// permissions (root:root 0600) +pub struct SmtpPrivateConfig { + /// Name of the endpoint + #[updater(skip)] + pub name: String, + /// The password to use during authentication. + #[serde(skip_serializing_if = "Option::is_none")] + pub password: Option, +} diff --git a/proxmox-notify/src/api_types/webhook.rs b/proxmox-notify/src/api_types/webhook.rs new file mode 100644 index 000000000..ad65f617e --- /dev/null +++ b/proxmox-notify/src/api_types/webhook.rs @@ -0,0 +1,208 @@ +use proxmox_schema::{ + ApiStringFormat, ApiType, PropertyString, Schema, StringSchema, Updater, api, + api_types::{COMMENT_SCHEMA, HTTP_URL_SCHEMA}, +}; +use serde::{Deserialize, Serialize}; + +use crate::{Error, Origin, schema::ENTITY_NAME_SCHEMA}; + +/// This will be used as a section type in the public/private configuration file. +pub const WEBHOOK_TYPENAME: &str = "webhook"; + +pub const KEY_AND_BASE64_VALUE_SCHEMA: Schema = + StringSchema::new("String schema for pairs of keys and base64 encoded values") + .format(&ApiStringFormat::PropertyString( + &KeyAndBase64Val::API_SCHEMA, + )) + .schema(); + +#[api] +#[derive(Serialize, Deserialize, Clone, Copy, Default, PartialEq)] +#[serde(rename_all = "kebab-case")] +/// HTTP Method to use. +pub enum HttpMethod { + /// HTTP POST + #[default] + Post, + /// HTTP PUT + Put, + /// HTTP GET + Get, +} + +// We only ever need a &str, so we rather implement this +// instead of Display. +impl From for &str { + fn from(value: HttpMethod) -> Self { + match value { + HttpMethod::Post => "POST", + HttpMethod::Put => "PUT", + HttpMethod::Get => "GET", + } + } +} + +#[api( + properties: { + name: { + schema: ENTITY_NAME_SCHEMA, + }, + url: { + schema: HTTP_URL_SCHEMA, + }, + comment: { + optional: true, + schema: COMMENT_SCHEMA, + }, + header: { + type: Array, + items: { + schema: KEY_AND_BASE64_VALUE_SCHEMA, + }, + optional: true, + }, + secret: { + type: Array, + items: { + schema: KEY_AND_BASE64_VALUE_SCHEMA, + }, + optional: true, + }, + } +)] +#[derive(Serialize, Deserialize, Updater, Default, Clone)] +#[serde(rename_all = "kebab-case")] +/// Config for Webhook notification endpoints +pub struct WebhookConfig { + /// Name of the endpoint. + #[updater(skip)] + pub name: String, + + pub method: HttpMethod, + + /// Webhook URL. Supports templating. + pub url: String, + /// Array of HTTP headers. Each entry is a property string with a name and a value. + /// The value property contains the header in base64 encoding. Supports templating. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + pub header: Vec>, + /// The HTTP body to send. Supports templating. + #[serde(skip_serializing_if = "Option::is_none")] + pub body: Option, + + /// Comment. + #[serde(skip_serializing_if = "Option::is_none")] + pub comment: Option, + /// Disable this target. + #[serde(skip_serializing_if = "Option::is_none")] + pub disable: Option, + /// Origin of this config entry. + #[serde(skip_serializing_if = "Option::is_none")] + #[updater(skip)] + pub origin: Option, + /// Array of secrets. Each entry is a property string with a name and an optional value. + /// The value property contains the secret in base64 encoding. + /// For any API endpoints returning the endpoint config, + /// only the secret name but not the value will be returned. + /// When updating the config, also send all secrets that you want + /// to keep, setting only the name but not the value. Can be accessed from templates. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + pub secret: Vec>, +} + +#[api( + properties: { + name: { + schema: ENTITY_NAME_SCHEMA, + }, + secret: { + type: Array, + items: { + schema: KEY_AND_BASE64_VALUE_SCHEMA, + }, + optional: true, + }, + } +)] +#[derive(Serialize, Deserialize, Clone, Updater, Default)] +#[serde(rename_all = "kebab-case")] +/// Private configuration for Webhook notification endpoints. +/// This config will be saved to a separate configuration file with stricter +/// permissions (root:root 0600). +pub struct WebhookPrivateConfig { + /// Name of the endpoint + #[updater(skip)] + pub name: String, + + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[updater(serde(skip_serializing_if = "Option::is_none"))] + /// Array of secrets. Each entry is a property string with a name, + /// and a value property. The value property contains the secret + /// in base64 encoding. Can be accessed from templates. + pub secret: Vec>, +} + +#[api] +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +/// Webhook configuration properties that can be deleted. +pub enum DeleteableWebhookProperty { + /// Delete `comment`. + Comment, + /// Delete `disable`. + Disable, + /// Delete `header`. + Header, + /// Delete `body`. + Body, + /// Delete `secret`. + Secret, +} + +#[api] +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +/// Datatype used to represent key-value pairs, the value +/// being encoded in base64. +pub struct KeyAndBase64Val { + /// Name + pub name: String, + /// Base64 encoded value + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +impl KeyAndBase64Val { + #[cfg(test)] + pub fn new_with_plain_value(name: &str, value: &str) -> Self { + let value = proxmox_base64::encode(value); + + Self { + name: name.into(), + value: Some(value), + } + } + + /// Decode the contained value, returning the plaintext value + /// + /// Returns an error if the contained value is not valid base64-encoded + /// text. + pub fn decode_value(&self) -> Result { + let value = self.value.as_deref().unwrap_or_default(); + let bytes = proxmox_base64::decode(value).map_err(|_| { + Error::invalid_config(format!( + "could not decode base64 value with key '{}'", + self.name + )) + })?; + let value = String::from_utf8(bytes).map_err(|_| { + Error::invalid_config(format!( + "could not decode UTF8 string from base64, key '{}'", + self.name + )) + })?; + + Ok(value) + } +} diff --git a/proxmox-notify/src/config.rs b/proxmox-notify/src/config.rs index 176bc46b7..bf1469160 100644 --- a/proxmox-notify/src/config.rs +++ b/proxmox-notify/src/config.rs @@ -5,7 +5,11 @@ use proxmox_schema::{ApiType, ObjectSchema}; use proxmox_section_config::{SectionConfig, SectionConfigData, SectionConfigPlugin}; use crate::Error; -use crate::matcher::{MATCHER_TYPENAME, MatcherConfig}; +use crate::api_types::{ + GOTIFY_TYPENAME, GotifyConfig, GotifyPrivateConfig, MATCHER_TYPENAME, MatcherConfig, + SENDMAIL_TYPENAME, SMTP_TYPENAME, SendmailConfig, SmtpConfig, SmtpPrivateConfig, + WEBHOOK_TYPENAME, WebhookConfig, WebhookPrivateConfig, +}; use crate::schema::BACKEND_NAME_SCHEMA; /// Section config schema for the public config file. @@ -23,10 +27,7 @@ pub fn private_config_parser() -> &'static SectionConfig { fn config_init() -> SectionConfig { let mut config = SectionConfig::new(&BACKEND_NAME_SCHEMA); - #[cfg(feature = "sendmail")] { - use crate::endpoints::sendmail::{SENDMAIL_TYPENAME, SendmailConfig}; - const SENDMAIL_SCHEMA: &ObjectSchema = SendmailConfig::API_SCHEMA.unwrap_object_schema(); config.register_plugin(SectionConfigPlugin::new( SENDMAIL_TYPENAME.to_string(), @@ -34,10 +35,7 @@ fn config_init() -> SectionConfig { SENDMAIL_SCHEMA, )); } - #[cfg(feature = "smtp")] { - use crate::endpoints::smtp::{SMTP_TYPENAME, SmtpConfig}; - const SMTP_SCHEMA: &ObjectSchema = SmtpConfig::API_SCHEMA.unwrap_object_schema(); config.register_plugin(SectionConfigPlugin::new( SMTP_TYPENAME.to_string(), @@ -45,10 +43,7 @@ fn config_init() -> SectionConfig { SMTP_SCHEMA, )); } - #[cfg(feature = "gotify")] { - use crate::endpoints::gotify::{GOTIFY_TYPENAME, GotifyConfig}; - const GOTIFY_SCHEMA: &ObjectSchema = GotifyConfig::API_SCHEMA.unwrap_object_schema(); config.register_plugin(SectionConfigPlugin::new( GOTIFY_TYPENAME.to_string(), @@ -56,10 +51,7 @@ fn config_init() -> SectionConfig { GOTIFY_SCHEMA, )); } - #[cfg(feature = "webhook")] { - use crate::endpoints::webhook::{WEBHOOK_TYPENAME, WebhookConfig}; - const WEBHOOK_SCHEMA: &ObjectSchema = WebhookConfig::API_SCHEMA.unwrap_object_schema(); config.register_plugin(SectionConfigPlugin::new( WEBHOOK_TYPENAME.to_string(), @@ -79,45 +71,29 @@ fn config_init() -> SectionConfig { } fn private_config_init() -> SectionConfig { - #[allow(unused_mut)] let mut config = SectionConfig::new(&BACKEND_NAME_SCHEMA); - #[cfg(feature = "gotify")] - { - use crate::endpoints::gotify::{GOTIFY_TYPENAME, GotifyPrivateConfig}; + 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 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, + )); - #[cfg(feature = "smtp")] - { - use crate::endpoints::smtp::{SMTP_TYPENAME, SmtpPrivateConfig}; + 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, + )); - 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, - )); - } - - #[cfg(feature = "webhook")] - { - use crate::endpoints::webhook::{WEBHOOK_TYPENAME, WebhookPrivateConfig}; - - 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 } diff --git a/proxmox-notify/src/context/pbs.rs b/proxmox-notify/src/context/pbs.rs index a979f25d6..f16e9ebdd 100644 --- a/proxmox-notify/src/context/pbs.rs +++ b/proxmox-notify/src/context/pbs.rs @@ -6,9 +6,8 @@ use tracing::error; use proxmox_schema::{ObjectSchema, Schema, StringSchema}; use proxmox_section_config::{SectionConfig, SectionConfigPlugin}; -use crate::context::{ContextImpl, common}; +use crate::context::{ContextImpl, TemplateSource, common}; use crate::error::BoxedError; -use crate::renderer::TemplateSource; const PBS_USER_CFG_FILENAME: &str = "/etc/proxmox-backup/user.cfg"; const PBS_NODE_CFG_FILENAME: &str = "/etc/proxmox-backup/node.cfg"; diff --git a/proxmox-notify/src/context/pve.rs b/proxmox-notify/src/context/pve.rs index b2d08acc2..bcfa0edff 100644 --- a/proxmox-notify/src/context/pve.rs +++ b/proxmox-notify/src/context/pve.rs @@ -1,8 +1,7 @@ use std::path::Path; -use crate::context::{ContextImpl, common}; +use crate::context::{ContextImpl, TemplateSource, common}; use crate::error::BoxedError; -use crate::renderer::TemplateSource; fn lookup_mail_address(content: &str, user: &str) -> Option { common::normalize_for_return(content.lines().find_map(|line| { diff --git a/proxmox-notify/src/endpoints/common/mod.rs b/proxmox-notify/src/endpoints/common/mod.rs index 60e07619b..c2d0a8b7f 100644 --- a/proxmox-notify/src/endpoints/common/mod.rs +++ b/proxmox-notify/src/endpoints/common/mod.rs @@ -1,2 +1 @@ -#[cfg(any(feature = "sendmail", feature = "smtp"))] pub(crate) mod mail; diff --git a/proxmox-notify/src/endpoints/gotify.rs b/proxmox-notify/src/endpoints/gotify.rs index 7fe74f862..5341f822f 100644 --- a/proxmox-notify/src/endpoints/gotify.rs +++ b/proxmox-notify/src/endpoints/gotify.rs @@ -1,17 +1,14 @@ use std::collections::HashMap; use std::time::Duration; -use serde::{Deserialize, Serialize}; use serde_json::json; use proxmox_http::client::sync::Client; use proxmox_http::{HttpClient, HttpOptions, ProxyConfig}; -use proxmox_schema::api_types::COMMENT_SCHEMA; -use proxmox_schema::{Updater, api}; +use crate::api_types::{GotifyConfig, GotifyPrivateConfig}; use crate::renderer::TemplateType; -use crate::schema::ENTITY_NAME_SCHEMA; -use crate::{Content, Context, Error, Notification, Origin, Severity, renderer}; +use crate::{Content, Context, Error, Notification, Severity, renderer}; use super::Endpoint; @@ -27,75 +24,12 @@ fn severity_to_priority(level: Severity) -> u32 { } } -pub(crate) const GOTIFY_TYPENAME: &str = "gotify"; - -#[api( - properties: { - name: { - schema: ENTITY_NAME_SCHEMA, - }, - comment: { - optional: true, - schema: COMMENT_SCHEMA, - }, - } -)] -#[derive(Serialize, Deserialize, Updater, Default)] -#[serde(rename_all = "kebab-case")] -/// Config for Gotify notification endpoints -pub struct GotifyConfig { - /// Name of the endpoint. - #[updater(skip)] - pub name: String, - /// Gotify Server URL. - pub server: String, - /// Comment. - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - /// Deprecated. - #[serde(skip_serializing)] - #[updater(skip)] - pub filter: Option, - /// Disable this target. - #[serde(skip_serializing_if = "Option::is_none")] - pub disable: Option, - /// Origin of this config entry. - #[serde(skip_serializing_if = "Option::is_none")] - #[updater(skip)] - pub origin: Option, -} - -#[api()] -#[derive(Serialize, Deserialize, Clone, Updater)] -#[serde(rename_all = "kebab-case")] -/// Private configuration for Gotify notification endpoints. -/// This config will be saved to a separate configuration file with stricter -/// permissions (root:root 0600) -pub struct GotifyPrivateConfig { - /// Name of the endpoint - #[updater(skip)] - pub name: String, - /// Authentication token - pub token: String, -} - /// A Gotify notification endpoint. -pub struct GotifyEndpoint { +pub(crate) struct GotifyEndpoint { pub config: GotifyConfig, pub private_config: GotifyPrivateConfig, } -#[api] -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -/// The set of properties that can be deleted from a gotify endpoint configuration. -pub enum DeleteableGotifyProperty { - /// Delete `comment` - Comment, - /// Delete `disable` - Disable, -} - impl Endpoint for GotifyEndpoint { fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> { let (title, message) = match ¬ification.content { diff --git a/proxmox-notify/src/endpoints/mod.rs b/proxmox-notify/src/endpoints/mod.rs index ea77d4243..0bf7f9f60 100644 --- a/proxmox-notify/src/endpoints/mod.rs +++ b/proxmox-notify/src/endpoints/mod.rs @@ -2,13 +2,9 @@ use crate::Context; use crate::Error; use crate::Notification; -#[cfg(feature = "gotify")] pub mod gotify; -#[cfg(feature = "sendmail")] pub mod sendmail; -#[cfg(feature = "smtp")] pub mod smtp; -#[cfg(feature = "webhook")] pub mod webhook; mod common; diff --git a/proxmox-notify/src/endpoints/sendmail.rs b/proxmox-notify/src/endpoints/sendmail.rs index 0d60308d2..6ddee5161 100644 --- a/proxmox-notify/src/endpoints/sendmail.rs +++ b/proxmox-notify/src/endpoints/sendmail.rs @@ -1,104 +1,12 @@ use proxmox_sendmail::Mail; -use serde::{Deserialize, Serialize}; - -use proxmox_schema::api_types::COMMENT_SCHEMA; -use proxmox_schema::{Updater, api}; +use crate::api_types::SendmailConfig; use crate::endpoints::common::mail; use crate::renderer::TemplateType; -use crate::schema::{EMAIL_SCHEMA, ENTITY_NAME_SCHEMA, USER_SCHEMA}; -use crate::{Content, Context, Error, Notification, Origin, renderer}; +use crate::{Content, Context, Error, Notification, renderer}; use super::Endpoint; -pub(crate) const SENDMAIL_TYPENAME: &str = "sendmail"; - -#[api( - properties: { - name: { - schema: ENTITY_NAME_SCHEMA, - }, - mailto: { - type: Array, - items: { - schema: EMAIL_SCHEMA, - }, - optional: true, - }, - "mailto-user": { - type: Array, - items: { - schema: USER_SCHEMA, - }, - optional: true, - }, - comment: { - optional: true, - schema: COMMENT_SCHEMA, - }, - }, -)] -#[derive(Debug, Serialize, Deserialize, Updater, Default)] -#[serde(rename_all = "kebab-case")] -/// Config for Sendmail notification endpoints -pub struct SendmailConfig { - /// Name of the endpoint - #[updater(skip)] - pub name: String, - /// Mail address to send a mail to. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - pub mailto: Vec, - /// Users to send a mail to. The email address of the user - /// will be looked up in users.cfg. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - pub mailto_user: Vec, - /// `From` address for sent E-Mails. - /// If the parameter is not set, the plugin will fall back to the - /// email-from setting from node.cfg (PBS). - /// If that is also not set, the plugin will default to root@$hostname, - /// where $hostname is the hostname of the node. - #[serde(skip_serializing_if = "Option::is_none")] - pub from_address: Option, - /// Author of the mail. Defaults to 'Proxmox Backup Server ($hostname)' - #[serde(skip_serializing_if = "Option::is_none")] - pub author: Option, - /// Comment. - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - /// Deprecated. - #[serde(skip_serializing)] - #[updater(skip)] - pub filter: Option, - /// Disable this target. - #[serde(skip_serializing_if = "Option::is_none")] - pub disable: Option, - /// Origin of this config entry. - #[serde(skip_serializing_if = "Option::is_none")] - #[updater(skip)] - pub origin: Option, -} - -#[api] -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -/// The set of properties that can be deleted from a sendmail endpoint configuration. -pub enum DeleteableSendmailProperty { - /// Delete `author` - Author, - /// Delete `comment` - Comment, - /// Delete `disable` - Disable, - /// Delete `from-address` - FromAddress, - /// Delete `mailto` - Mailto, - /// Delete `mailto-user` - MailtoUser, -} - /// A sendmail notification endpoint. pub struct SendmailEndpoint { pub config: SendmailConfig, diff --git a/proxmox-notify/src/endpoints/smtp.rs b/proxmox-notify/src/endpoints/smtp.rs index b64bb5596..ccade1c8e 100644 --- a/proxmox-notify/src/endpoints/smtp.rs +++ b/proxmox-notify/src/endpoints/smtp.rs @@ -5,153 +5,19 @@ use lettre::message::header::{HeaderName, HeaderValue}; use lettre::message::{Mailbox, MultiPart, SinglePart}; use lettre::transport::smtp::client::{Tls, TlsParameters}; use lettre::{Message, SmtpTransport, Transport, message::header::ContentType}; -use serde::{Deserialize, Serialize}; - -use proxmox_schema::api_types::COMMENT_SCHEMA; -use proxmox_schema::{Updater, api}; +use crate::api_types::{SmtpConfig, SmtpMode, SmtpPrivateConfig}; use crate::endpoints::common::mail; use crate::renderer::TemplateType; -use crate::schema::{EMAIL_SCHEMA, ENTITY_NAME_SCHEMA, USER_SCHEMA}; -use crate::{Content, Context, Error, Notification, Origin, renderer}; +use crate::{Content, Context, Error, Notification, renderer}; use super::Endpoint; -pub(crate) const SMTP_TYPENAME: &str = "smtp"; - const SMTP_PORT: u16 = 25; const SMTP_SUBMISSION_STARTTLS_PORT: u16 = 587; const SMTP_SUBMISSION_TLS_PORT: u16 = 465; const SMTP_TIMEOUT: u16 = 5; -#[api] -#[derive(Debug, Serialize, Deserialize, Default, Clone, Copy)] -#[serde(rename_all = "kebab-case")] -/// Connection security -pub enum SmtpMode { - /// No encryption (insecure), plain SMTP - Insecure, - /// Upgrade to TLS after connecting - #[serde(rename = "starttls")] - StartTls, - /// Use TLS-secured connection - #[default] - Tls, -} - -#[api( - properties: { - name: { - schema: ENTITY_NAME_SCHEMA, - }, - mailto: { - type: Array, - items: { - schema: EMAIL_SCHEMA, - }, - optional: true, - }, - "mailto-user": { - type: Array, - items: { - schema: USER_SCHEMA, - }, - optional: true, - }, - comment: { - optional: true, - schema: COMMENT_SCHEMA, - }, - }, -)] -#[derive(Debug, Serialize, Deserialize, Updater, Default)] -#[serde(rename_all = "kebab-case")] -/// Config for Sendmail notification endpoints -pub struct SmtpConfig { - /// Name of the endpoint. - #[updater(skip)] - pub name: String, - /// Host name or IP of the SMTP relay. - pub server: String, - /// The port to connect to. - /// If not set, the used port defaults to 25 (insecure), 465 (tls) - /// or 587 (starttls), depending on the value of mode - #[serde(skip_serializing_if = "Option::is_none")] - pub port: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, - /// Username to use during authentication. - /// If no username is set, no authentication will be performed. - /// The PLAIN and LOGIN authentication methods are supported - #[serde(skip_serializing_if = "Option::is_none")] - pub username: Option, - /// Mail address to send a mail to. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - pub mailto: Vec, - /// Users to send a mail to. The email address of the user - /// will be looked up in users.cfg. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - pub mailto_user: Vec, - /// `From` address for the mail. - /// SMTP relays might require that this address is owned by the user - /// in order to avoid spoofing. The `From` header in the email will be - /// set to `$author <$from-address>`. - pub from_address: String, - /// Author of the mail. Defaults to 'Proxmox Backup Server ($hostname)' - #[serde(skip_serializing_if = "Option::is_none")] - pub author: Option, - /// Comment. - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - /// Disable this target. - #[serde(skip_serializing_if = "Option::is_none")] - pub disable: Option, - /// Origin of this config entry. - #[serde(skip_serializing_if = "Option::is_none")] - #[updater(skip)] - pub origin: Option, -} - -#[api] -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -/// The set of properties that can be deleted from a smtp endpoint configuration. -pub enum DeleteableSmtpProperty { - /// Delete `author` - Author, - /// Delete `comment` - Comment, - /// Delete `disable` - Disable, - /// Delete `mailto` - Mailto, - /// Delete `mailto-user` - MailtoUser, - /// Delete `password` - Password, - /// Delete `port` - Port, - /// Delete `username` - Username, -} - -#[api] -#[derive(Serialize, Deserialize, Clone, Updater, Debug)] -#[serde(rename_all = "kebab-case")] -/// Private configuration for SMTP notification endpoints. -/// This config will be saved to a separate configuration file with stricter -/// permissions (root:root 0600) -pub struct SmtpPrivateConfig { - /// Name of the endpoint - #[updater(skip)] - pub name: String, - /// The password to use during authentication. - #[serde(skip_serializing_if = "Option::is_none")] - pub password: Option, -} - /// A sendmail notification endpoint. pub struct SmtpEndpoint { pub config: SmtpConfig, diff --git a/proxmox-notify/src/endpoints/webhook.rs b/proxmox-notify/src/endpoints/webhook.rs index e3ec9e5ef..49ea29c1e 100644 --- a/proxmox-notify/src/endpoints/webhook.rs +++ b/proxmox-notify/src/endpoints/webhook.rs @@ -15,230 +15,25 @@ use handlebars::{ }; use http::Request; use percent_encoding::AsciiSet; -use proxmox_schema::property_string::PropertyString; -use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use proxmox_http::client::sync::Client; use proxmox_http::{HttpClient, HttpOptions, ProxyConfig}; -use proxmox_schema::api_types::{COMMENT_SCHEMA, HTTP_URL_SCHEMA}; -use proxmox_schema::{ApiStringFormat, ApiType, Schema, StringSchema, Updater, api}; +use crate::api_types::{HttpMethod, WebhookConfig, WebhookPrivateConfig}; use crate::renderer::TemplateType; -use crate::schema::ENTITY_NAME_SCHEMA; -use crate::{Content, Context, Error, Notification, Origin, renderer}; +use crate::{Content, Context, Error, Notification, renderer}; use super::Endpoint; -/// This will be used as a section type in the public/private configuration file. -pub(crate) const WEBHOOK_TYPENAME: &str = "webhook"; - const HTTP_TIMEOUT: Duration = Duration::from_secs(10); -#[api] -#[derive(Serialize, Deserialize, Clone, Copy, Default, PartialEq)] -#[serde(rename_all = "kebab-case")] -/// HTTP Method to use. -pub enum HttpMethod { - /// HTTP POST - #[default] - Post, - /// HTTP PUT - Put, - /// HTTP GET - Get, -} - -// We only ever need a &str, so we rather implement this -// instead of Display. -impl From for &str { - fn from(value: HttpMethod) -> Self { - match value { - HttpMethod::Post => "POST", - HttpMethod::Put => "PUT", - HttpMethod::Get => "GET", - } - } -} - -#[api( - properties: { - name: { - schema: ENTITY_NAME_SCHEMA, - }, - url: { - schema: HTTP_URL_SCHEMA, - }, - comment: { - optional: true, - schema: COMMENT_SCHEMA, - }, - header: { - type: Array, - items: { - schema: KEY_AND_BASE64_VALUE_SCHEMA, - }, - optional: true, - }, - secret: { - type: Array, - items: { - schema: KEY_AND_BASE64_VALUE_SCHEMA, - }, - optional: true, - }, - } -)] -#[derive(Serialize, Deserialize, Updater, Default, Clone)] -#[serde(rename_all = "kebab-case")] -/// Config for Webhook notification endpoints -pub struct WebhookConfig { - /// Name of the endpoint. - #[updater(skip)] - pub name: String, - - pub method: HttpMethod, - - /// Webhook URL. Supports templating. - pub url: String, - /// Array of HTTP headers. Each entry is a property string with a name and a value. - /// The value property contains the header in base64 encoding. Supports templating. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - pub header: Vec>, - /// The HTTP body to send. Supports templating. - #[serde(skip_serializing_if = "Option::is_none")] - pub body: Option, - - /// Comment. - #[serde(skip_serializing_if = "Option::is_none")] - pub comment: Option, - /// Disable this target. - #[serde(skip_serializing_if = "Option::is_none")] - pub disable: Option, - /// Origin of this config entry. - #[serde(skip_serializing_if = "Option::is_none")] - #[updater(skip)] - pub origin: Option, - /// Array of secrets. Each entry is a property string with a name and an optional value. - /// The value property contains the secret in base64 encoding. - /// For any API endpoints returning the endpoint config, - /// only the secret name but not the value will be returned. - /// When updating the config, also send all secrets that you want - /// to keep, setting only the name but not the value. Can be accessed from templates. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - pub secret: Vec>, -} - -#[api( - properties: { - name: { - schema: ENTITY_NAME_SCHEMA, - }, - secret: { - type: Array, - items: { - schema: KEY_AND_BASE64_VALUE_SCHEMA, - }, - optional: true, - }, - } -)] -#[derive(Serialize, Deserialize, Clone, Updater, Default)] -#[serde(rename_all = "kebab-case")] -/// Private configuration for Webhook notification endpoints. -/// This config will be saved to a separate configuration file with stricter -/// permissions (root:root 0600). -pub struct WebhookPrivateConfig { - /// Name of the endpoint - #[updater(skip)] - pub name: String, - - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[updater(serde(skip_serializing_if = "Option::is_none"))] - /// Array of secrets. Each entry is a property string with a name, - /// and a value property. The value property contains the secret - /// in base64 encoding. Can be accessed from templates. - pub secret: Vec>, -} - /// A Webhook notification endpoint. -pub struct WebhookEndpoint { +pub(crate) struct WebhookEndpoint { pub config: WebhookConfig, pub private_config: WebhookPrivateConfig, } -#[api] -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -/// Webhook configuration properties that can be deleted. -pub enum DeleteableWebhookProperty { - /// Delete `comment`. - Comment, - /// Delete `disable`. - Disable, - /// Delete `header`. - Header, - /// Delete `body`. - Body, - /// Delete `secret`. - Secret, -} - -#[api] -#[derive(Serialize, Deserialize, Debug, Default, Clone)] -/// Datatype used to represent key-value pairs, the value -/// being encoded in base64. -pub struct KeyAndBase64Val { - /// Name - pub name: String, - /// Base64 encoded value - #[serde(skip_serializing_if = "Option::is_none")] - pub value: Option, -} - -impl KeyAndBase64Val { - #[cfg(test)] - pub fn new_with_plain_value(name: &str, value: &str) -> Self { - let value = proxmox_base64::encode(value); - - Self { - name: name.into(), - value: Some(value), - } - } - - /// Decode the contained value, returning the plaintext value - /// - /// Returns an error if the contained value is not valid base64-encoded - /// text. - pub fn decode_value(&self) -> Result { - let value = self.value.as_deref().unwrap_or_default(); - let bytes = proxmox_base64::decode(value).map_err(|_| { - Error::invalid_config(format!( - "could not decode base64 value with key '{}'", - self.name - )) - })?; - let value = String::from_utf8(bytes).map_err(|_| { - Error::invalid_config(format!( - "could not decode UTF8 string from base64, key '{}'", - self.name - )) - })?; - - Ok(value) - } -} - -pub const KEY_AND_BASE64_VALUE_SCHEMA: Schema = - StringSchema::new("String schema for pairs of keys and base64 encoded values") - .format(&ApiStringFormat::PropertyString( - &KeyAndBase64Val::API_SCHEMA, - )) - .schema(); - impl Endpoint for WebhookEndpoint { /// Send a notification to a webhook endpoint. fn send(&self, context: &Context, notification: &Notification) -> Result<(), Error> { @@ -518,7 +313,7 @@ mod tests { use std::collections::HashMap; use super::*; - use crate::{Severity, context::test}; + use crate::{Severity, api_types::KeyAndBase64Val, context::test}; #[test] fn test_build_request() { diff --git a/proxmox-notify/src/lib.rs b/proxmox-notify/src/lib.rs index 6675a9f76..c74e7e1a9 100644 --- a/proxmox-notify/src/lib.rs +++ b/proxmox-notify/src/lib.rs @@ -15,16 +15,18 @@ use proxmox_schema::api; use proxmox_section_config::SectionConfigData; use proxmox_uuid::Uuid; -pub mod matcher; -use matcher::{MATCHER_TYPENAME, MatcherConfig}; - +#[cfg(feature = "api-impl")] pub mod api; + pub mod config; pub mod context; pub mod endpoints; pub mod renderer; pub mod schema; +#[cfg(feature = "api-types")] +pub mod api_types; + mod error; pub use error::Error; @@ -33,6 +35,9 @@ pub use context::ContextImpl; use endpoints::Endpoint; +use crate::api_types::MATCHER_TYPENAME; +use crate::api_types::MatcherConfig; + #[api()] #[derive(Clone, Debug, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd)] #[serde(rename_all = "kebab-case")] @@ -312,7 +317,6 @@ pub struct Bus { matchers: Vec, } -#[allow(unused_macros)] macro_rules! parse_endpoints_with_private_config { ($config:ident, $public_config:ty, $private_config:ty, $endpoint_type:ident, $type_name:expr) => { (|| -> Result>, Error> { @@ -354,7 +358,6 @@ macro_rules! parse_endpoints_with_private_config { }; } -#[allow(unused_macros)] macro_rules! parse_endpoints_without_private_config { ($config:ident, $public_config:ty, $endpoint_type:ident, $type_name:expr) => { (|| -> Result>, Error> { @@ -377,75 +380,65 @@ macro_rules! parse_endpoints_without_private_config { impl Bus { /// Instantiate notification bus from a given configuration. pub fn from_config(config: &Config) -> Result { - #[allow(unused_mut)] let mut endpoints = HashMap::new(); // Instantiate endpoints - #[cfg(feature = "sendmail")] - { - use endpoints::sendmail::SENDMAIL_TYPENAME; - use endpoints::sendmail::{SendmailConfig, SendmailEndpoint}; - endpoints.extend( - parse_endpoints_without_private_config!( - config, - SendmailConfig, - SendmailEndpoint, - SENDMAIL_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); - } + use crate::api_types::{SENDMAIL_TYPENAME, SendmailConfig}; + use endpoints::sendmail::SendmailEndpoint; + endpoints.extend( + parse_endpoints_without_private_config!( + config, + SendmailConfig, + SendmailEndpoint, + SENDMAIL_TYPENAME + )? + .into_iter() + .map(|e| (e.name().into(), e)), + ); - #[cfg(feature = "gotify")] - { - use endpoints::gotify::GOTIFY_TYPENAME; - use endpoints::gotify::{GotifyConfig, GotifyEndpoint, GotifyPrivateConfig}; - endpoints.extend( - parse_endpoints_with_private_config!( - config, - GotifyConfig, - GotifyPrivateConfig, - GotifyEndpoint, - GOTIFY_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); - } - #[cfg(feature = "smtp")] - { - use endpoints::smtp::SMTP_TYPENAME; - use endpoints::smtp::{SmtpConfig, SmtpEndpoint, SmtpPrivateConfig}; - endpoints.extend( - parse_endpoints_with_private_config!( - config, - SmtpConfig, - SmtpPrivateConfig, - SmtpEndpoint, - SMTP_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); - } + use crate::api_types::{GOTIFY_TYPENAME, GotifyConfig, GotifyPrivateConfig}; + use crate::endpoints::gotify::GotifyEndpoint; - #[cfg(feature = "webhook")] - { - use endpoints::webhook::WEBHOOK_TYPENAME; - use endpoints::webhook::{WebhookConfig, WebhookEndpoint, WebhookPrivateConfig}; - endpoints.extend( - parse_endpoints_with_private_config!( - config, - WebhookConfig, - WebhookPrivateConfig, - WebhookEndpoint, - WEBHOOK_TYPENAME - )? - .into_iter() - .map(|e| (e.name().into(), e)), - ); - } + endpoints.extend( + parse_endpoints_with_private_config!( + config, + GotifyConfig, + GotifyPrivateConfig, + GotifyEndpoint, + GOTIFY_TYPENAME + )? + .into_iter() + .map(|e| (e.name().into(), e)), + ); + + use crate::api_types::{SMTP_TYPENAME, SmtpConfig, SmtpPrivateConfig}; + use endpoints::smtp::SmtpEndpoint; + + endpoints.extend( + parse_endpoints_with_private_config!( + config, + SmtpConfig, + SmtpPrivateConfig, + SmtpEndpoint, + SMTP_TYPENAME + )? + .into_iter() + .map(|e| (e.name().into(), e)), + ); + + use crate::api_types::{WEBHOOK_TYPENAME, WebhookConfig, WebhookPrivateConfig}; + use endpoints::webhook::WebhookEndpoint; + endpoints.extend( + parse_endpoints_with_private_config!( + config, + WebhookConfig, + WebhookPrivateConfig, + WebhookEndpoint, + WEBHOOK_TYPENAME + )? + .into_iter() + .map(|e| (e.name().into(), e)), + ); let matchers = config .config @@ -473,7 +466,7 @@ impl Bus { /// /// Any errors will not be returned but only logged. pub fn send(&self, context: &Context, notification: &Notification) { - let targets = matcher::check_matches(self.matchers.as_slice(), notification); + let targets = api_types::check_matches(self.matchers.as_slice(), notification); for target in targets { if let Some(endpoint) = self.endpoints.get(target) { @@ -535,8 +528,10 @@ mod tests { use proxmox_match_expression::Expression; - use crate::context::test; - use crate::matcher::{expression::NotificationMatcher, severity::SeverityMatcher}; + use crate::{ + api_types::{expression::NotificationMatcher, severity::SeverityMatcher}, + context::{Context, test}, + }; use super::*; -- 2.47.3