public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH container 22/34] restore: refuse overwriting a container with another guest's backup
Date: Mon, 16 Nov 2026 01:46:34 +0100	[thread overview]
Message-ID: <20261116004703.2908294-23-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261116004703.2908294-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>
---
 src/PVE/API2/LXC.pm         |  56 +++++++++++++-
 src/test/lifecycle_tests.pl | 141 ++++++++++++++++++++++++++++++++++++
 2 files changed, 196 insertions(+), 1 deletion(-)

diff --git a/src/PVE/API2/LXC.pm b/src/PVE/API2/LXC.pm
index b354e9d..06049d7 100644
--- a/src/PVE/API2/LXC.pm
+++ b/src/PVE/API2/LXC.pm
@@ -231,6 +231,16 @@ __PACKAGE__->register_method({
                 description => "Assign a unique random ethernet address.",
                 requires => 'restore',
             },
+            'allow-identity-mismatch' => {
+                optional => 1,
+                type => 'boolean',
+                description => "Allow to overwrite 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',
@@ -293,6 +303,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
@@ -454,7 +465,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;
@@ -466,6 +483,36 @@ __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->{identity} or return;
+
+            if ($from_stdin) {
+                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"
+                    if !$allow_identity_mismatch;
+                return;
+            }
+
+            return
+                if !$backup_identity
+                || PVE::GuestIdentity::uid_matches_target($reservation, $backup_identity->{uid});
+
+            my $uid = $backup_identity->{uid};
+            die "backup belongs to another guest: its uid '$uid' differs from uid"
+                . " '$target->{uid}' of the existing CT $vmid - use 'allow-identity-mismatch' to"
+                . " overwrite the CT anyway\n"
+                if !$allow_identity_mismatch;
+
+            print "guest identity: ignoring backup uid $uid, CT $vmid keeps uid"
+                . " $target->{uid}\n";
+        };
+
         my $code = sub {
             my $old_conf = PVE::LXC::Config->load_config($vmid);
             my $was_template;
@@ -482,6 +529,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);
@@ -517,7 +565,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) {
@@ -634,6 +686,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 bed9b72..d93f24e 100755
--- a/src/test/lifecycle_tests.pl
+++ b/src/test/lifecycle_tests.pl
@@ -32,6 +32,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;
@@ -300,6 +301,7 @@ my sub run_task {
 
 my $backup_raw_config;
 my $backup_read_error;
+my $volumes_touched = 0;
 
 my $storage_module = Test::MockModule->new('PVE::Storage');
 $storage_module->mock(
@@ -327,6 +329,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";
@@ -338,6 +341,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 {
@@ -1291,6 +1295,44 @@ subtest 'using the container left behind drops its pending uid' => sub {
     is($err, '', 'config change of the stopped container') or diag($task_log);
     like($task_log, qr/ignoring pending change of read-only option 'meta'/, '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 {
@@ -1408,6 +1450,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-16  0:50 UTC|newest]

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

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=20261116004703.2908294-23-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 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