public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Arthur Bied-Charreton <a.bied-charreton@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH proxmox v6 02/27] notify: smtp: introduce xoauth2 module
Date: Tue,  2 Jun 2026 10:53:54 +0200	[thread overview]
Message-ID: <20260602085419.271767-3-a.bied-charreton@proxmox.com> (raw)
In-Reply-To: <20260602085419.271767-1-a.bied-charreton@proxmox.com>

The xoauth2 module handles some of the implementation details related to
supporting XOAUTH2 for SMTP notification targets.

The get_{google,microsoft}_token functions handle provider-specific
token exchange. A newtype wrapper over proxmox_http's Client
implementing the SyncHttpClient trait is added to allow using
proxmox-http as a backend for oauth2 and respecting the proxy configs.

Signed-off-by: Arthur Bied-Charreton <a.bied-charreton@proxmox.com>
---
 proxmox-notify/Cargo.toml                    |   3 +-
 proxmox-notify/src/endpoints/smtp.rs         |   2 +
 proxmox-notify/src/endpoints/smtp/xoauth2.rs | 133 +++++++++++++++++++
 3 files changed, 137 insertions(+), 1 deletion(-)
 create mode 100644 proxmox-notify/src/endpoints/smtp/xoauth2.rs

diff --git a/proxmox-notify/Cargo.toml b/proxmox-notify/Cargo.toml
index bc63e19d..6a3a3794 100644
--- a/proxmox-notify/Cargo.toml
+++ b/proxmox-notify/Cargo.toml
@@ -20,6 +20,7 @@ lettre = { workspace = true, optional = true }
 tracing.workspace = true
 mail-parser = { workspace = true, optional = true }
 openssl.workspace = true
+oauth2 = { workspace = true, optional = true }
 percent-encoding = { workspace = true, optional = true }
 regex.workspace = true
 serde = { workspace = true, features = ["derive"] }
@@ -44,5 +45,5 @@ sendmail = ["dep:proxmox-sys", "dep:proxmox-sendmail"]
 gotify = ["dep:proxmox-http", "dep:http"]
 pve-context = ["dep:proxmox-sys"]
 pbs-context = ["dep:proxmox-sys"]
-smtp = ["dep:lettre"]
+smtp = ["dep:lettre", "dep:oauth2", "dep:proxmox-http", "dep:http"]
 webhook = ["dep:http", "dep:percent-encoding", "dep:proxmox-base64", "dep:proxmox-http"]
diff --git a/proxmox-notify/src/endpoints/smtp.rs b/proxmox-notify/src/endpoints/smtp.rs
index 85988aa7..636828b6 100644
--- a/proxmox-notify/src/endpoints/smtp.rs
+++ b/proxmox-notify/src/endpoints/smtp.rs
@@ -23,6 +23,8 @@ const SMTP_SUBMISSION_STARTTLS_PORT: u16 = 587;
 const SMTP_SUBMISSION_TLS_PORT: u16 = 465;
 const SMTP_TIMEOUT: u16 = 5;
 
+mod xoauth2;
+
 #[api]
 #[derive(Debug, Serialize, Deserialize, Default, Clone, Copy)]
 #[serde(rename_all = "kebab-case")]
diff --git a/proxmox-notify/src/endpoints/smtp/xoauth2.rs b/proxmox-notify/src/endpoints/smtp/xoauth2.rs
new file mode 100644
index 00000000..4b99b3f5
--- /dev/null
+++ b/proxmox-notify/src/endpoints/smtp/xoauth2.rs
@@ -0,0 +1,133 @@
+use oauth2::{
+    AccessToken, AuthUrl, ClientId, ClientSecret, RefreshToken, TokenResponse, TokenUrl,
+    basic::BasicClient,
+};
+use proxmox_http::{HttpOptions, ProxyConfig};
+
+use crate::{Error, context::context};
+
+/// Implements `oauth2`'s `SyncHttpClient` trait.
+///
+/// This allows `oauth2` to use `proxmox-http` as a backend for OAuth2 requests.
+struct SyncHttpClient(proxmox_http::client::sync::Client);
+
+impl SyncHttpClient {
+    fn new() -> Result<Self, Error> {
+        let proxy_config = context()
+            .http_proxy_config()
+            .map(|p| ProxyConfig::parse_proxy_url(&p))
+            .transpose()
+            .map_err(|e| Error::Generic(format!("invalid HTTP proxy config: {e}")))?;
+
+        let client = proxmox_http::client::sync::Client::new(HttpOptions {
+            proxy_config,
+            ..Default::default()
+        });
+
+        Ok(Self(client))
+    }
+}
+
+impl oauth2::SyncHttpClient for SyncHttpClient {
+    type Error = oauth2::HttpClientError<Error>;
+
+    fn call(&self, request: oauth2::HttpRequest) -> Result<oauth2::HttpResponse, Self::Error> {
+        let (parts, body) = request.into_parts();
+        let request = http::Request::from_parts(parts, body.as_slice());
+
+        proxmox_http::HttpClient::<&[u8], Vec<u8>>::request(&self.0, request)
+            .map_err(|e| oauth2::HttpClientError::Other(e.to_string()))
+    }
+}
+
+/// The result yielded by an OAuth2 token exchange.
+///
+/// A successful OAuth2 token exchange will always return an access token to be
+/// used for authentication.
+///
+/// Some providers additionally yield a new refresh token that should replace the
+/// old one.
+pub(crate) struct TokenExchangeResult {
+    pub access_token: AccessToken,
+    pub refresh_token: Option<RefreshToken>,
+}
+
+/// Perform a Microsoft OAuth2 token exchange.
+///
+/// Microsoft Identity Platform refresh tokens have static lifetimes of 90 days, with each
+/// token exchange yielding a new refresh token. The new refresh token is assigned a new
+/// static lifetime, starting from the moment the token exchange was performed.
+///
+/// The old refresh token is not invalidated, rather it keeps the static lifetime it was
+/// assigned at generation time. This means that at any given point in time, there can be
+/// many different refresh tokens that are *all* valid.
+///
+/// Therefore, while the saved token should be rotated eventually, in practice it is safe
+/// to persist the new refresh token only once every 24 hours for example.
+///
+/// https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens#token-lifetime
+pub(crate) fn get_microsoft_token(
+    client_id: ClientId,
+    client_secret: ClientSecret,
+    tenant_id: &str,
+    refresh_token: RefreshToken,
+) -> Result<TokenExchangeResult, Error> {
+    let client = BasicClient::new(client_id)
+        .set_client_secret(client_secret)
+        .set_auth_uri(
+            AuthUrl::new(format!(
+                "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize"
+            ))
+            .map_err(|e| Error::Generic(format!("invalid auth URL: {e}")))?,
+        )
+        .set_token_uri(
+            TokenUrl::new(format!(
+                "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
+            ))
+            .map_err(|e| Error::Generic(format!("invalid token URL: {e}")))?,
+        );
+
+    let token_result = client
+        .exchange_refresh_token(&refresh_token)
+        .request(&SyncHttpClient::new()?)
+        .map_err(|e| Error::Generic(format!("could not get access token: {e}")))?;
+
+    Ok(TokenExchangeResult {
+        access_token: token_result.access_token().clone(),
+        refresh_token: token_result.refresh_token().cloned(),
+    })
+}
+
+/// Perform a Google OAuth2 token exchange.
+///
+/// Google refresh tokens' TTL is extended at every use. As long as
+/// a token has been used at least once in the past 6 months, and no
+/// other expiration reason applies, the same token can be kept.
+///
+/// https://developers.google.com/identity/protocols/oauth2#expiration
+pub(crate) fn get_google_token(
+    client_id: ClientId,
+    client_secret: ClientSecret,
+    refresh_token: RefreshToken,
+) -> Result<TokenExchangeResult, Error> {
+    let client = BasicClient::new(client_id)
+        .set_client_secret(client_secret)
+        .set_auth_uri(
+            AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".into())
+                .map_err(|e| Error::Generic(format!("invalid auth URL: {e}")))?,
+        )
+        .set_token_uri(
+            TokenUrl::new("https://oauth2.googleapis.com/token".into())
+                .map_err(|e| Error::Generic(format!("invalid token URL: {e}")))?,
+        );
+
+    let token_result = client
+        .exchange_refresh_token(&refresh_token)
+        .request(&SyncHttpClient::new()?)
+        .map_err(|e| Error::Generic(format!("could not get access token: {e}")))?;
+
+    Ok(TokenExchangeResult {
+        access_token: token_result.access_token().clone(),
+        refresh_token: token_result.refresh_token().cloned(),
+    })
+}
-- 
2.47.3




  parent reply	other threads:[~2026-06-02  8:56 UTC|newest]

Thread overview: 28+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-06-02  8:53 [PATCH docs/manager/proxmox{,-perl-rs,-widget-toolkit,-backup} v6 00/27] fix #7238: Add XOAUTH2 authentication support for SMTP notification targets Arthur Bied-Charreton
2026-06-02  8:53 ` [PATCH proxmox v6 01/27] add oauth2 and ureq to workspace dependencies Arthur Bied-Charreton
2026-06-02  8:53 ` Arthur Bied-Charreton [this message]
2026-06-02  8:53 ` [PATCH proxmox v6 03/27] notify: smpt: add state management utilities Arthur Bied-Charreton
2026-06-02  8:53 ` [PATCH proxmox v6 04/27] notify: smtp: factor out transport building logic Arthur Bied-Charreton
2026-06-02  8:53 ` [PATCH proxmox v6 05/27] notify: smtp: update API with OAuth2 parameters Arthur Bied-Charreton
2026-06-02  8:53 ` [PATCH proxmox v6 06/27] notify: smtp: add API to exchange authorization code for refresh token Arthur Bied-Charreton
2026-06-02  8:53 ` [PATCH proxmox v6 07/27] notify: smtp: infer auth method for backwards compatibility Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox v6 08/27] notify: smtp: add state handling logic Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox v6 09/27] notify: smtp: add XOAUTH2 authentication support Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-perl-rs v6 10/27] pve-rs: notify: smtp: add OAuth2 parameters to bindings Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-perl-rs v6 11/27] pve-rs: notify: add binding for triggering state refresh Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-perl-rs v6 12/27] pve-rs: notify: add binding for initial OAuth2 refresh token exchange Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-widget-toolkit v6 13/27] utils: add OAuth2 flow handlers Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-widget-toolkit v6 14/27] utils: oauth2: add callback handler Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-widget-toolkit v6 15/27] notifications: add opt-in OAuth2 support for SMTP targets Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH pve-manager v6 16/27] notifications: smtp: api: add XOAUTH2 parameters Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH pve-manager v6 17/27] notifications: add endpoint for initial OAuth2 refresh token exchange Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH pve-manager v6 18/27] pveupdate: refresh notification targets' OAuth2 state Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH pve-manager v6 19/27] login: handle OAuth2 callback Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH pve-manager v6 20/27] fix #7238: notifications: smtp: add XOAUTH2 support Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-backup v6 21/27] notifications: add XOAUTH2 parameters to endpoints Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-backup v6 22/27] notifications: add endpoint for initial OAuth2 refresh token exchange Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-backup v6 23/27] login: handle OAuth2 callback Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-backup v6 24/27] fix #7238: notifications: smtp: add XOAUTH2 support Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-backup v6 25/27] daily-update: refresh OAuth2 state for SMTP notification endpoints Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH proxmox-backup v6 26/27] notifications: add OAuth2 section to SMTP targets docs Arthur Bied-Charreton
2026-06-02  8:54 ` [PATCH pve-docs v6 27/27] " Arthur Bied-Charreton

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=20260602085419.271767-3-a.bied-charreton@proxmox.com \
    --to=a.bied-charreton@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
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal