all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH container v2 23/36] restore: refuse overwriting a container with another guest's backup
Date: Tue, 17 Nov 2026 23:34:33 +0100	[thread overview]
Message-ID: <20261117223945.862914-24-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261117223945.862914-1-t.lamprecht@proxmox.com>

Restoring the backup of another guest over an existing container
results in the data of the backup under the identity of the target.
Tools that follow that identity would take the result for the original
guest.

Refuse a restore if the uids differ, unless 'allow-identity-mismatch'
is set through the create API or 'pct restore'. The existing 'force'
option permits overwriting a container but does not override this
check. With the override, a container that already had an identity
keeps it.

A container that has the uid of the backup as pending uid was left
behind by an unfinished restore of that backup, so a retry may proceed.
Without 'unique', the retry takes that uid over if no other guest uses
it.

For standard input, the config of the backup is only known after the
old volumes were destroyed and the archive got extracted. So require
the override whenever the target already has an identity. A target
without identity can still be overwritten without it.

Compare the uids before the restore destroys anything. Apply the
network options only after that as well: applying them can allocate
addresses in the IPAM of SDN, and the cleanup after a failure can
remove mappings for MAC addresses that the existing container still
uses. Validate and queue those options before the worker starts,
without changing the IPAM state.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
---

changes v1 -> v2:
* use the shared check of pve-guest-common
* 'Allow overwriting' instead of 'Allow to overwrite' and a default for
  'allow-identity-mismatch' (Dominik)

 src/PVE/API2/LXC.pm         |  53 +++++++++++++-
 src/test/lifecycle_tests.pl | 141 ++++++++++++++++++++++++++++++++++++
 2 files changed, 193 insertions(+), 1 deletion(-)

diff --git a/src/PVE/API2/LXC.pm b/src/PVE/API2/LXC.pm
index 5fea82f..67a38af 100644
--- a/src/PVE/API2/LXC.pm
+++ b/src/PVE/API2/LXC.pm
@@ -214,6 +214,17 @@ __PACKAGE__->register_method({
                     . " the guest uid of the backup.",
                 requires => 'restore',
             },
+            'allow-identity-mismatch' => {
+                optional => 1,
+                type => 'boolean',
+                default => 0,
+                description => "Allow overwriting an existing container with a backup of"
+                    . " another guest, as detected by a different 'uid' in 'meta'. A restore from"
+                    . " standard input over a container that has a uid always needs this option,"
+                    . " as the backup cannot be checked beforehand. Unless the container is left"
+                    . " over from an unfinished restore of the same backup, it keeps its own uid.",
+                requires => 'restore',
+            },
             pool => {
                 optional => 1,
                 type => 'string',
@@ -276,6 +287,7 @@ __PACKAGE__->register_method({
         my $unprivileged = extract_param($param, 'unprivileged');
         my $restore = extract_param($param, 'restore');
         my $unique = extract_param($param, 'unique');
+        my $allow_identity_mismatch = extract_param($param, 'allow-identity-mismatch');
 
         $param->{cpuunits} = PVE::CGroup::clamp_cpu_shares($param->{cpuunits})
             if defined($param->{cpuunits}); # clamp value depending on cgroup version
@@ -437,7 +449,13 @@ __PACKAGE__->register_method({
         # check/activate default storage
         &$check_and_activate_storage($storage) if !defined($mp_param->{rootfs});
 
-        PVE::LXC::Config->update_pct_config($vmid, $conf, 0, $no_disk_param);
+        if ($restore) {
+            # applying network options can allocate addresses in the IPAM of SDN, so only check and
+            # queue the options here, and apply them once the restore may overwrite the container
+            PVE::LXC::Config->queue_pct_config_changes($vmid, $conf, $no_disk_param, [], []);
+        } else {
+            PVE::LXC::Config->update_pct_config($vmid, $conf, 0, $no_disk_param);
+        }
 
         $conf->{unprivileged} = 1 if $unprivileged;
         $conf->{meta} = PVE::LXC::Config->new_meta_info_string() if !$restore;
@@ -449,6 +467,32 @@ __PACKAGE__->register_method({
 
         my $destroy_config_on_error = !$same_container_exists;
 
+        # Restoring over an existing container must not turn it into another guest. The identity of
+        # a backup from STDIN is only known once the container got overwritten. A container with the
+        # uid of the backup as pending uid is a leftover of an earlier restore of it.
+        my $assert_identity_matches = sub {
+            my ($backup_identity, $from_stdin) = @_;
+
+            my $target = $reservation->{previous} or return;
+
+            if ($from_stdin) {
+                if (!$allow_identity_mismatch) {
+                    die "cannot verify the guest identity of a backup from standard input"
+                        . " before overwriting CT $vmid (uid '$target->{uid}') - use"
+                        . " 'allow-identity-mismatch' to overwrite the CT anyway\n";
+                }
+                return;
+            }
+
+            PVE::GuestIdentity::assert_backup_matches_target(
+                'PVE::LXC::Config',
+                $vmid,
+                $reservation,
+                $backup_identity ? $backup_identity->{uid} : undef,
+                $allow_identity_mismatch,
+            );
+        };
+
         my $code = sub {
             my $old_conf = PVE::LXC::Config->load_config($vmid);
             my $was_template;
@@ -465,6 +509,7 @@ __PACKAGE__->register_method({
                         ($orig_conf, $orig_mp_param) =
                             PVE::LXC::Create::recover_config($storage_cfg, $archive, $vmid);
                         $backup_identity = PVE::LXC::Config->get_identity($orig_conf);
+                        $assert_identity_matches->($backup_identity);
                         $pending_uid = restore_pending_uid($reservation, $backup_identity);
                         PVE::LXC::Config->record_pending_uid($vmid, $pending_uid)
                             if defined($pending_uid);
@@ -500,7 +545,11 @@ __PACKAGE__->register_method({
                         ) {
                             $rpcenv->check($authuser, '/', ['Sys.Modify']);
                         }
+                    } else {
+                        $assert_identity_matches->(undef, 1);
                     }
+
+                    PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storage_cfg);
                 }
                 if ($storage_only_mode) {
                     if ($restore) {
@@ -617,6 +666,8 @@ __PACKAGE__->register_method({
                         # the API parameters cannot carry 'meta', so it comes from the backup
                         if ($archive eq '-') {
                             $backup_identity = PVE::LXC::Config->get_identity($conf);
+                            # only logs a mismatch, which needed the override already
+                            $assert_identity_matches->($backup_identity);
                             $pending_uid = restore_pending_uid($reservation, $backup_identity);
                         }
                         PVE::LXC::create_ifaces_ipams_ips($conf, $vmid) if $unique;
diff --git a/src/test/lifecycle_tests.pl b/src/test/lifecycle_tests.pl
index eb5b308..235169f 100755
--- a/src/test/lifecycle_tests.pl
+++ b/src/test/lifecycle_tests.pl
@@ -31,6 +31,7 @@ use PVE::Tools qw(file_get_contents file_set_contents);
 
 use PVE::API2::LXC;
 use PVE::API2::LXC::Config;
+use PVE::CLI::pct;
 use PVE::LXC;
 use PVE::LXC::Config;
 use PVE::LXC::Create;
@@ -293,6 +294,7 @@ my sub run_task($code) {
 
 my $backup_raw_config;
 my $backup_read_error;
+my $volumes_touched = 0;
 
 my $storage_module = Test::MockModule->new('PVE::Storage');
 $storage_module->mock(
@@ -320,6 +322,7 @@ $lxc_module->mock(
     check_running => sub { return 0 },
     create_disks => sub {
         my ($storecfg, $vmid, $settings, $conf) = @_;
+        $volumes_touched++;
         my $vollist = [];
         for my $ms (sort keys %$settings) {
             my $volid = "local:$vmid/vm-$vmid-disk-$ms.raw";
@@ -331,6 +334,7 @@ $lxc_module->mock(
     destroy_disks => sub { },
     destroy_lxc_container => sub {
         my ($storecfg, $vmid, $conf, $replacement_conf) = @_;
+        $volumes_touched++;
         if (defined($replacement_conf)) {
             PVE::LXC::Config->write_config($vmid, $replacement_conf);
         } else {
@@ -1300,6 +1304,44 @@ subtest 'using the container left behind drops its pending uid' => sub {
         . " restore - a retry now needs 'allow-identity-mismatch'";
     like($task_log, qr/^WARN: \Q$dropped\E$/m, 'dropped');
     is(pending_uid_of(200), undef, 'pending uid is gone');
+
+    $backup_raw_config =~ s/^arch: amd64$/arch: amd64\nunprivileged: 1/m;
+    $err = restore_ct(200, { force => 1 });
+    like($err, qr/backup belongs to another guest/, 'container stays a guest of its own');
+};
+
+subtest 'retry over the container left behind by a restore of another backup' => sub {
+    failed_restore_in_place();
+
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=anotheranotheranothe');
+    my $err = restore_ct(200, { force => 1 });
+    like(
+        $err,
+        qr/backup belongs to another guest: its uid .anotheranotheranothe. differs/,
+        'refused',
+    );
+    is(pending_uid_of(200), 'backupbackupbackupba', 'pending uid is unchanged');
+};
+
+subtest 'restore from STDIN over the container left behind' => sub {
+    failed_restore_in_place();
+    my $leftover = identity_of(200)->{uid};
+
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba');
+    my $param = { force => 1, ostemplate => '-', rootfs => 'local:4' };
+    my $err = restore_ct(200, $param);
+    like($err, qr/cannot verify the guest identity of a backup from standard input/, 'refused');
+
+    $err = restore_ct(200, { $param->%*, 'allow-identity-mismatch' => 1 });
+    is($err, '', 'restore with override succeeds') or diag($task_log);
+    is(
+        identity_of(200)->{uid},
+        'backupbackupbackupba',
+        'pending uid matches the backup: taken over',
+    );
+    is(pending_uid_of(200), undef, 'pending uid is removed');
 };
 
 subtest 'restore with unique keeps a pending uid, but never takes it over' => sub {
@@ -1417,6 +1459,105 @@ subtest 'every write of a restore keeps the pending uid' => sub {
     $storage_module->unmock('volume_has_feature');
 };
 
+subtest 'restore over a container of another guest needs an override' => sub {
+    my $existing_meta = 'ctime=1500000000,rtime=1500000000000,uid=existingexistingexis';
+    my $existing_raw = existing_config($existing_meta);
+    my $existing_conf = PVE::LXC::Config::parse_pct_config('/lxc/200.conf', $existing_raw);
+    delete $existing_conf->{digest};
+    $backup_raw_config =
+        backup_config('ctime=1400000000,rtime=1400000000000,uid=backupbackupbackupba');
+
+    # network options can change the IPAM of SDN, with the same MAC address as the existing one
+    my $net = 'name=eth0,bridge=vnet0,hwaddr=BC:24:11:00:00:01,ip=dhcp';
+    my @sdn_calls;
+    my $vnets_module = Test::MockModule->new('PVE::Network::SDN::Vnets');
+    $vnets_module->mock(
+        add_next_free_cidr => sub { push @sdn_calls, 'add_next_free_cidr' },
+        del_ips_from_mac => sub { push @sdn_calls, 'del_ips_from_mac' },
+    );
+    $lxc_module->unmock('delete_ifaces_ipams_ips');
+
+    my $refused = sub {
+        my ($name, $param, $expected_err) = @_;
+
+        reset_configs();
+        write_raw_config(200, $existing_raw);
+        $volumes_touched = 0;
+        @sdn_calls = ();
+        my $err = restore_ct(200, { force => 1, $param->%* });
+        like($err, $expected_err, "$name: restore is refused");
+        is($volumes_touched, 0, "$name: volumes are not touched");
+        is_deeply(\@sdn_calls, [], "$name: IPAM is not touched");
+        my $conf = PVE::LXC::Config->load_config(200);
+        delete $conf->{digest};
+        is_deeply($conf, $existing_conf, "$name: config is unchanged");
+    };
+
+    my $mismatch_err =
+        "unable to restore CT 200 - backup belongs to another guest: its uid 'backupbackupbackupba'"
+        . " differs from uid 'existingexistingexis' of the existing CT 200 - use"
+        . " 'allow-identity-mismatch' to overwrite the CT anyway";
+    my $stdin_err =
+        "unable to restore CT 200 - cannot verify the guest identity of a backup from standard"
+        . " input before overwriting CT 200 (uid 'existingexistingexis') - use"
+        . " 'allow-identity-mismatch' to overwrite the CT anyway";
+    my $ignored = "guest identity: ignoring backup uid backupbackupbackupba, CT 200 keeps uid"
+        . " existingexistingexis";
+    my $stdin = { ostemplate => '-', rootfs => 'local:4' };
+    $refused->('different uid', {}, qr/^\Q$mismatch_err\E$/);
+    $refused->('different uid, unique', { unique => 1 }, qr/^\Q$mismatch_err\E$/);
+    $refused->('different uid, network option', { net0 => $net }, qr/^\Q$mismatch_err\E$/);
+    $refused->('from STDIN', $stdin, qr/^\Q$stdin_err\E$/);
+    $refused->('from STDIN, network option', { $stdin->%*, net0 => $net },
+        qr/^\Q$stdin_err\E$/);
+
+    for my $param ({}, $stdin) {
+        my $name = $param->{ostemplate} ? 'from STDIN' : 'from file';
+        reset_configs();
+        write_raw_config(200, $existing_raw);
+        @sdn_calls = ();
+        my $err = restore_ct(
+            200,
+            { force => 1, 'allow-identity-mismatch' => 1, net0 => $net, $param->%* },
+        );
+        is($err, '', "$name: restore with override succeeds") or diag($task_log);
+        is_deeply(\@sdn_calls, ['add_next_free_cidr'], "$name: network option is applied");
+        is(
+            PVE::LXC::Config->load_config(200)->{hostname},
+            'backup',
+            "$name: backup is restored",
+        );
+        is_deeply(
+            identity_of(200),
+            { uid => 'existingexistingexis', rtime => 1500000000000 },
+            "$name: identity of the target is kept",
+        );
+        like(
+            $task_log, qr/^\Q$ignored\E$/m, "$name: override is logged",
+        );
+        like(
+            $task_log,
+            qr/^guest identity: kept uid existingexistingexis$/m,
+            "$name: result is logged",
+        );
+    }
+
+    reset_configs();
+    write_raw_config(200, existing_config('ctime=1500000000'));
+    my $err = restore_ct(200, { force => 1, ostemplate => '-', rootfs => 'local:4' });
+    is($err, '', 'restore from STDIN over a container without identity succeeds');
+    is(identity_of(200)->{uid}, 'backupbackupbackupba', 'uid of the backup is taken over');
+
+    $err = create_ct(201, { 'allow-identity-mismatch' => 1 });
+    like($err, qr/allow-identity-mismatch/, 'override is only allowed for restores');
+
+    my ($class, $method, undef, $fixed) = $PVE::CLI::pct::cmddef->{restore}->@*;
+    is("$class->$method", 'PVE::API2::LXC->create_vm', 'pct restore uses the create API call');
+    ok($fixed->{restore}, 'pct restore sets restore, so it accepts the override');
+
+    $lxc_module->mock(delete_ifaces_ipams_ips => sub { });
+};
+
 remove_tree($WORKDIR);
 
 done_testing();
-- 
2.47.3





  parent reply	other threads:[~2026-11-17 22:43 UTC|newest]

Thread overview: 38+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-17 22:34 [PATCH cluster/guest-common/qemu-server/container/manager/docs v2 00/36] fix #7846: guest identity (uid) and cluster ID Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 01/36] pmxcfs: reject changes to the cluster ID file from user space Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 02/36] pmxcfs: generate a cluster ID on standalone nodes Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 03/36] pmxcfs: dfsm: add a callback that runs once all members are in sync Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 04/36] pmxcfs: quorum: pass the corosync membership to an optional listener Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 05/36] pmxcfs: dcdb: generate the cluster ID once the cluster is in sync Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 06/36] cluster: add helper to read the cluster ID Thomas Lamprecht
2026-11-17 22:34 ` [PATCH cluster v2 07/36] pmxcfs: allow removing the cluster ID file in forced local mode Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 08/36] guest identity: add helpers for the guest uid and registration time Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 09/36] abstract config: assign a guest identity and keep it on config writes Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 10/36] abstract config: let the VMID reservation return the previous state Thomas Lamprecht
2026-11-17 22:34 ` [PATCH guest-common v2 11/36] guest identity: allow taking over a uid that is unused in the cluster Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 12/36] api: restore: release the VMID if a restore to an unused VMID fails Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 13/36] api: migrate, clone: refuse targets that would drop the guest identity Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 14/36] fix #7846: config: add a guest identity to the 'meta' property Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 15/36] restore: take over the guest uid from the backup where possible Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 16/36] api: remote migration: take over the guest uid from the source Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 17/36] api: status: return the guest uid Thomas Lamprecht
2026-11-17 22:34 ` [PATCH qemu-server v2 18/36] tests: remote migration: check a failed command and an early tunnel end Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 19/36] config: add read-only meta property with the creation time Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 20/36] fix #7846: config: add a guest identity to the 'meta' property Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 21/36] api: migrate, clone: refuse targets that would drop the guest identity Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 22/36] restore: take over the guest uid from the backup where possible Thomas Lamprecht
2026-11-17 22:34 ` Thomas Lamprecht [this message]
2026-11-17 22:34 ` [PATCH container v2 24/36] test: remote migration: check the cleanup of the target after failures Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 25/36] api: remote migration: take over the guest uid from the source Thomas Lamprecht
2026-11-17 22:34 ` [PATCH container v2 26/36] api: status: return the guest uid Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 27/36] api: cluster resources: add guest uid and registration time Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 28/36] api: cluster status: add cluster ID Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 29/36] ui: restore: allow overwriting a guest with a backup of another guest Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 30/36] ui: migrate: refuse target nodes that would drop the guest identity Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 31/36] ui: guest summary: show " Thomas Lamprecht
2026-11-17 22:34 ` [PATCH manager v2 32/36] api: migrate all: refuse targets that would drop " Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 33/36] vzdump: describe the guest identity of VMs and containers Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 34/36] pvecm: document the cluster ID and how to get a new one Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 35/36] qm: configuration: describe the read-only meta property Thomas Lamprecht
2026-11-17 22:34 ` [PATCH docs v2 36/36] pct: " Thomas Lamprecht
2026-11-18  5:57 ` superseded: [PATCH cluster/guest-common/qemu-server/container/manager/docs v2 00/36] fix #7846: guest identity (uid) and cluster ID Thomas Lamprecht

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=20261117223945.862914-24-t.lamprecht@proxmox.com \
    --to=t.lamprecht@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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal