From: Christian Ebner <c.ebner@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH v2 proxmox-backup 5/9] server: pull: decouple decryption key gathering from logging
Date: Thu, 3 Dec 2026 16:04:44 +0100 [thread overview]
Message-ID: <20261203150448.412515-6-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com>
optionally_use_decryption_key() decides which decryption key to use
(if any), checking for matching fingerprint and signature and checks
if the snapshot can be resynced or not if already existing on the
target.
In an effort to make the key gathering and chosen pull variant more
transparent/readable and decouple it from the logging, make the
helper a method of PullParameters so decryption key configs need not
be passed as parameter, introduce intrinsically more descriptive enum
variants as return values instead of plain types, and pull the logging
completely out of the helper.
No functional changes apart from not logging decryption key match
in case of no resync since no data changes, which is in preparation
for state checking under shared lock.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 360 ++++++++++++++++++++++++---------------------
1 file changed, 196 insertions(+), 164 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 308ac752b..52be2edda 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -168,6 +168,159 @@ impl PullParameters {
crypt_configs,
})
}
+
+ /// Decide whether a configured decryption key should be used to decrypt the snapshot during
+ /// pull based on the source manifest and an optional pre-existing target manifest.
+ fn optionally_use_decryption_key(
+ &self,
+ manifest: &BackupManifest,
+ existing_target_manifest: Option<&BackupManifest>,
+ prefix: &str,
+ ) -> Result<PullVariant, Error> {
+ let Some(key_fp) = manifest.fingerprint().with_context(|| prefix.to_owned())? else {
+ if let Some(existing_manifest) = existing_target_manifest {
+ if existing_manifest.fingerprint()?.is_some() {
+ bail!("refusing to overwrite local encrypted snapshot from unencrypted source");
+ } else {
+ // Use a zero key to produce a deterministic content hash over the canonical,
+ // signature- and unprotected-stripped manifest. Equal output means equal
+ // protected content (files, csums, backup-time, ...).
+ let dummy = CryptConfig::new([0u8; 32])?;
+ if existing_manifest.signature(&dummy)? != manifest.signature(&dummy)? {
+ // neither source nor target encrypted, but manifests differ
+ bail!("refusing to overwrite local snapshot: content differs from source");
+ }
+ }
+ }
+
+ return Ok(PullVariant::Plain);
+ };
+
+ // check if source is encrypted or contents signed
+ let encrypted = manifest
+ .files()
+ .iter()
+ .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
+
+ if let Some(existing_manifest) = existing_target_manifest {
+ if let Some(existing_fingerprint) = existing_manifest.fingerprint()? {
+ if existing_fingerprint == key_fp {
+ let target_encrypted = existing_manifest
+ .files()
+ .iter()
+ .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
+ if encrypted == target_encrypted {
+ // both sides are signed or encrypted with the same key, just resync
+ return Ok(PullVariant::Plain);
+ }
+ } else {
+ // pre-existing local manifest for encrypted snapshot with key mismatch
+ bail!(
+ "Local encrypted or signed snapshot with different key detected, \
+ refuse to sync"
+ );
+ }
+ }
+ };
+
+ // source got key fingerprint, expect contents to be signed or encrypted
+ let Some((key_id, config)) = self
+ .crypt_configs
+ .iter()
+ .find(|(_id, crypt_conf)| crypt_conf.fingerprint() == *key_fp.bytes())
+ else {
+ // all the other cases are handled above
+ if encrypted && existing_target_manifest.is_some() {
+ bail!("No matching key found, refusing sync");
+ }
+
+ return Ok(if !self.crypt_configs.is_empty() {
+ PullVariant::NoMatchingKey
+ } else {
+ PullVariant::Plain
+ });
+ };
+
+ // check if source is encrypted or contents signed
+ if !encrypted {
+ return Ok(PullVariant::NotFullyEncrypted {
+ key_id: key_id.clone(),
+ key_fp,
+ });
+ }
+
+ manifest
+ .check_signature(config, false)
+ .context("failed to check source manifest signature")
+ .with_context(|| prefix.to_owned())?;
+
+ let mut skip_resync = false;
+
+ // avoid overwriting pre-existing target manifest
+ if let Some(existing_manifest) = existing_target_manifest {
+ let source_fp = manifest
+ .get_sync_source_signature()
+ .context("failed to parse sync-source-signature of source manifest")
+ .with_context(|| prefix.to_owned())?;
+ let stored_source_fp = existing_manifest
+ .get_sync_source_signature()
+ .context("failed to parse sync-source-signature of existing target manifest")
+ .with_context(|| prefix.to_owned())?;
+
+ if source_fp.is_none() && stored_source_fp.is_none() {
+ bail!("No sync-source-signature found, refuse to continue!");
+ }
+
+ if let Some(source_fp) = source_fp {
+ // Stored fp is HMAC over the unencrypted source's protected fields; recompute
+ // over the locally decrypted manifest, not the fresh encrypted remote one.
+ let target_fp = existing_manifest
+ .signature(config)
+ .with_context(|| prefix.to_owned())?;
+ skip_resync = skip_resync || target_fp == *source_fp.bytes();
+ }
+
+ if let Some(stored_source_fp) = stored_source_fp {
+ // Stored sync-source-signature is the source's prior signature on decrypt-pull
+ // (the flow this fallback handles); values set by encrypt-push hold a different
+ // HMAC input and fall through to the mismatch bail.
+ let Some(current) = &manifest.signature else {
+ bail!("No signature on source manifest.");
+ };
+ let current: Fingerprint = current.parse().with_context(|| prefix.to_owned())?;
+ skip_resync = skip_resync || current == stored_source_fp;
+ }
+
+ if !skip_resync {
+ bail!("sync-source-signature mismatch, refuse to continue!");
+ }
+ }
+
+ Ok(PullVariant::Decrypt {
+ key_id: key_id.clone(),
+ key_fp,
+ crypt_config: Arc::clone(config),
+ skip_resync,
+ })
+ }
+}
+
+/// Variant of pull sync specifying whether and how to decrypt a snapshot during pull.
+enum PullVariant {
+ /// Pull without decryption
+ Plain,
+ /// Pull as-is, since configured decryption keys did not match the source snapshot's key
+ /// fingerprint.
+ NoMatchingKey,
+ /// Pull as-is, a matching key exists, but the snapshot is not fully encrypted.
+ NotFullyEncrypted { key_id: String, key_fp: Fingerprint },
+ /// Decrypt archives on pull with the matching key or skip resync if target is already synced.
+ Decrypt {
+ key_id: String,
+ key_fp: Fingerprint,
+ crypt_config: Arc<CryptConfig>,
+ skip_resync: bool,
+ },
}
async fn pull_index_chunks<I: IndexFile>(
@@ -744,24 +897,54 @@ async fn pull_snapshot<'a>(
return Ok(None);
}
- let (crypt_config, new_manifest) = match optionally_use_decryption_key(
- Arc::clone(¶ms),
+ let (crypt_config, new_manifest) = match params.optionally_use_decryption_key(
&manifest,
existing_target_manifest.as_ref(),
- prefix.clone(),
- Arc::clone(&log_sender),
- )
- .await?
- {
- (None, false) => (None, None), // regular pull without decryption
- (Some(crypt_config), false) => {
- // decrypt while pull
+ &prefix,
+ )? {
+ PullVariant::Plain => (None, None),
+ PullVariant::NoMatchingKey => {
+ log_sender
+ .log(
+ Level::INFO,
+ format!("{prefix}: No matching key found, sync without decryption"),
+ )
+ .await?;
+ (None, None)
+ }
+ PullVariant::NotFullyEncrypted { key_id, key_fp } => {
+ log_sender.log(
+ Level::WARN,
+ format!(
+ "Snapshot not fully encrypted, sync as is despite matching key '{key_id}' with \
+ fingerprint {key_fp}"
+ ),
+ ).await?;
+ (None, None)
+ }
+ PullVariant::Decrypt {
+ crypt_config,
+ key_id,
+ key_fp,
+ skip_resync: false,
+ } => {
+ log_sender
+ .log(
+ Level::INFO,
+ format!(
+ "Found matching key '{key_id}' with fingerprint {key_fp}, decrypt on pull"
+ ),
+ )
+ .await?;
let new_manifest = Arc::new(Mutex::new(BackupManifest::new(snapshot.into())));
(Some(crypt_config), Some(new_manifest))
}
- (crypt_config, true) => {
- // nothing changed
- fetch_log(crypt_config).await?;
+ PullVariant::Decrypt {
+ crypt_config,
+ skip_resync: true,
+ ..
+ } => {
+ fetch_log(Some(crypt_config)).await?;
log_sender
.log(Level::INFO, format!("{prefix}: no data changes"))
.await?;
@@ -933,157 +1116,6 @@ async fn pull_snapshot<'a>(
Ok(Some(sync_stats))
}
-/// Check if the decryption key should be used to decrypt the snapshot during
-/// pull based on given pull parameter, source and optionally already present
-/// target manifest.
-///
-/// The boolean flag in the returned tuple indicates whether the pull can be
-/// skipped altogether, since the already existing target is unchanged.
-/// If decryption should happen, the matching decryption key is returned.
-async fn optionally_use_decryption_key(
- params: Arc<PullParameters>,
- manifest: &BackupManifest,
- existing_target_manifest: Option<&BackupManifest>,
- prefix: String,
- log_sender: Arc<LogLineSender>,
-) -> Result<(Option<Arc<CryptConfig>>, bool), Error> {
- let Some(key_fp) = manifest.fingerprint().with_context(|| prefix.clone())? else {
- if let Some(existing_manifest) = existing_target_manifest {
- if existing_manifest.fingerprint()?.is_some() {
- bail!("refusing to overwrite local encrypted snapshot from unencrypted source");
- } else {
- // Use a zero key to produce a deterministic content hash over the canonical,
- // signature- and unprotected-stripped manifest. Equal output means equal
- // protected content (files, csums, backup-time, ...).
- let dummy = CryptConfig::new([0u8; 32])?;
- if existing_manifest.signature(&dummy)? != manifest.signature(&dummy)? {
- // neither source nor target encrypted, but manifests differ
- bail!("refusing to overwrite local snapshot: content differs from source");
- }
- }
- }
-
- return Ok((None, false)); // no fingerprint on source, regular pull
- };
-
- // check if source is encrypted or contents signed
- let encrypted = manifest
- .files()
- .iter()
- .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
-
- if let Some(existing_manifest) = existing_target_manifest {
- if let Some(existing_fingerprint) = existing_manifest.fingerprint()? {
- if existing_fingerprint == key_fp {
- let target_encrypted = existing_manifest
- .files()
- .iter()
- .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
- if encrypted == target_encrypted {
- // both sides are signed or encrypted with the same key, just resync
- return Ok((None, false));
- }
- } else {
- // pre-existing local manifest for encrypted snapshot with key mismatch
- bail!(
- "Local encrypted or signed snapshot with different key detected, refuse to sync"
- );
- }
- }
- };
-
- // source got key fingerprint, expect contents to be signed or encrypted
- let Some((key_id, config)) = params
- .crypt_configs
- .iter()
- .find(|(_id, crypt_conf)| crypt_conf.fingerprint() == *key_fp.bytes())
- else {
- // all the other cases are handled above
- if encrypted && existing_target_manifest.is_some() {
- bail!("No matching key found, refusing sync");
- }
-
- // regular sync
- if !params.crypt_configs.is_empty() {
- log_sender
- .log(
- Level::INFO,
- format!("{prefix}: No matching key found, sync without decryption"),
- )
- .await?;
- }
-
- return Ok((None, false));
- };
-
- // check if source is encrypted or contents signed
- if !encrypted {
- log_sender
- .log(
- Level::WARN,
- format!("Snapshot not fully encrypted, sync as is despite matching key '{key_id}' with fingerprint {key_fp}"),
- )
- .await?;
- return Ok((None, false));
- }
-
- manifest
- .check_signature(config, false)
- .context("failed to check source manifest signature")
- .with_context(|| prefix.clone())?;
-
- let mut skip_resync = false;
-
- // avoid overwriting pre-existing target manifest
- if let Some(existing_manifest) = existing_target_manifest {
- let source_fp = manifest
- .get_sync_source_signature()
- .context("failed to parse sync-source-signature of source manifest")
- .with_context(|| prefix.clone())?;
- let stored_source_fp = existing_manifest
- .get_sync_source_signature()
- .context("failed to parse sync-source-signature of existing target manifest")
- .with_context(|| prefix.clone())?;
-
- if source_fp.is_none() && stored_source_fp.is_none() {
- bail!("No sync-source-signature found, refuse to continue!");
- }
-
- if let Some(source_fp) = source_fp {
- // Stored fp is HMAC over the unencrypted source's protected fields; recompute
- // over the locally decrypted manifest, not the fresh encrypted remote one.
- let target_fp = existing_manifest
- .signature(config)
- .with_context(|| prefix.clone())?;
- skip_resync = skip_resync || target_fp == *source_fp.bytes();
- }
-
- if let Some(stored_source_fp) = stored_source_fp {
- // Stored sync-source-signature is the source's prior signature on decrypt-pull
- // (the flow this fallback handles); values set by encrypt-push hold a different
- // HMAC input and fall through to the mismatch bail.
- let Some(current) = &manifest.signature else {
- bail!("No signature on source manifest.");
- };
- let current: Fingerprint = current.parse().with_context(|| prefix.clone())?;
- skip_resync = skip_resync || current == stored_source_fp;
- }
-
- if !skip_resync {
- bail!("sync-source-signature mismatch, refuse to continue!");
- }
- }
-
- log_sender
- .log(
- Level::INFO,
- format!("Found matching key '{key_id}' with fingerprint {key_fp}, decrypt on pull"),
- )
- .await?;
-
- Ok((Some(Arc::clone(config)), skip_resync))
-}
-
/// Pulls a `snapshot`, removing newly created ones on error, but keeping existing ones in any case.
///
/// The `reader` is configured to read from the source backup directory, while the
--
2.47.3
next prev parent reply other threads:[~2026-12-03 15:05 UTC|newest]
Thread overview: 10+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 1/9] server: pull: refactor snapshot sync start logging Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 2/9] server: pull: defer sync stats instantiation until needed Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 3/9] server: pull: load source manifest into memory instead of a temp file Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 4/9] server: pull: move target manifest loading logic into reusable helper Christian Ebner
2026-12-03 15:04 ` Christian Ebner [this message]
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 6/9] pbs-datastore: add BackupDir::lock_with_timeout() Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 7/9] pbs-datastore: add create_locked_backup_dir_with_timeout() Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 8/9] server: pull: check for unchanged snapshots under a shared lock Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 9/9] server: pull: skip exclusive lock when source has no client log Christian Ebner
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=20261203150448.412515-6-c.ebner@proxmox.com \
--to=c.ebner@proxmox.com \
--cc=pbs-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