public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Joaquin Varela <joaquinvarela@neatech.ar>
To: pve-devel@lists.proxmox.com
Subject: [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests
Date: Thu, 26 Nov 2026 12:09:53 -0300	[thread overview]
Message-ID: <20261126150956.310593-13-joaquinvarela@neatech.ar> (raw)
In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar>

The fault sweep fails every mutating call of every flow in each way an
SSH call can fail, and checks that identities stay unique, other
storages stay untouched and the next activation converges. The rendered
command chains also run with /bin/sh on a configfs stand-in, which
checks the quoting.

run_zfsnvme_taint_tests.pl runs under perl -T against a small model of
the target and a directory in place of sysfs. What the target answers
and what the plugin reads from files is tainted, as in the daemons,
while the commands, file names and sysfs writes are real. It covers the
activation, adding, cloning and removing a disk, rollback, templates
and the node side. It also covers a resize and a disk move that take
their size from the target, the sizes, names, snapshot names and
storage IDs that an internal caller passes, and the rows that the
methods return.

Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
 src/test/Makefile                   |   4 +
 src/test/run_zfsnvme_taint_tests.pl | 988 ++++++++++++++++++++++++++++
 src/test/zfsnvme_target_test.pm     | 766 +++++++++++++++++++++
 3 files changed, 1758 insertions(+)
 create mode 100755 src/test/run_zfsnvme_taint_tests.pl

diff --git a/src/test/Makefile b/src/test/Makefile
index eab91494..33ac5d17 100644
--- a/src/test/Makefile
+++ b/src/test/Makefile
@@ -28,8 +28,12 @@ test: \
     test_sensitive_properties \
     test_storage_create \
     test_volume_access \
+    test_zfsnvme_taint \
     test_zfspoolplugin \
 
+test_zfsnvme_taint: run_zfsnvme_taint_tests.pl
+	perl -T ./run_zfsnvme_taint_tests.pl
+
 test_zfspoolplugin: run_test_zfspoolplugin.pl
 	./run_test_zfspoolplugin.pl
 
diff --git a/src/test/run_zfsnvme_taint_tests.pl b/src/test/run_zfsnvme_taint_tests.pl
new file mode 100755
index 00000000..bdc4a0de
--- /dev/null
+++ b/src/test/run_zfsnvme_taint_tests.pl
@@ -0,0 +1,988 @@
+#!/usr/bin/perl -T
+
+# The zfsnvme plugin in taint mode, as pvedaemon, pveproxy and pvesr run it. A model of the target
+# answers the commands that the plugin sends over SSH, and the files that the plugin reads and
+# writes live in a temporary directory. What the model answers and what the plugin reads from files
+# is tainted like the read of a file or a pipe. Every command also runs for real, as true with the
+# same arguments, and the file names and sysfs writes are real, so a tainted word fails them as it
+# would in a daemon. The test checks every command with Scalar::Util::tainted as well.
+
+use v5.36;
+use lib qw(..);
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use File::Path qw(make_path);
+use File::Temp qw(tempdir);
+use MIME::Base64 qw(encode_base64);
+use Scalar::Util qw(tainted);
+use Test::MockModule;
+use Test::More;
+
+use PVE::File;
+use PVE::NVMeOF;
+use PVE::Storage;
+use PVE::Storage::ZFSNVMePlugin;
+use PVE::SysFSTools;
+use PVE::Tools qw(file_get_contents file_set_contents);
+
+my $PLUGIN = 'PVE::Storage::ZFSNVMePlugin';
+my $ROOT = '/sys/kernel/config/nvmet';
+my $NQN = 'nqn.2026-01.com.example:zfsnvme-test';
+my @HOSTS =
+    map { sprintf('nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-%012d', $_) } 1, 2;
+my %UUID = (
+    5 => '0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c',
+    6 => '0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d',
+    new => '7e57c0de-1111-4000-8000-000000000001',
+);
+my @PROPERTIES = qw(proxmox:nvme-subsys proxmox:nvme-nsid proxmox:nvme-uuid proxmox:nvme-last-nsid);
+my $RAW = join('', map { chr(($_ * 131 + 17) % 256) } 1 .. 32);
+my $KEY = 'DHHC-1:00:' . encode_base64($RAW . pack('V', crc32($RAW)), '') . ':';
+
+$ENV{PATH} = '/usr/sbin:/usr/bin:/sbin:/bin';
+delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
+
+# The parts of the file system that the plugin reads and writes live below $root.
+my $dir = tempdir('zfsnvme-taint-XXXX', DIR => '.', CLEANUP => 1);
+my $root = "$dir/root";
+
+sub fs($path) {
+    return "$root$path";
+}
+
+sub put($path, $content, $mode = undef) {
+    make_path(fs($path) =~ s{/[^/]*\z}{}r);
+    file_set_contents(fs($path), $content);
+    chmod($mode, fs($path)) if defined($mode);
+}
+
+# The lines as the read of a file or a pipe returns them.
+sub as_read(@lines) {
+    file_set_contents("$dir/read", join('', map { "$_\n" } @lines));
+    open(my $fh, '<', "$dir/read") or die "cannot read back the lines: $!\n";
+    chomp(my @read = <$fh>);
+    close($fh);
+    return @read;
+}
+
+# Every tainted value in what a method returns.
+sub tainted_values(@data) {
+    return map {
+        ref($_) eq 'ARRAY' ? tainted_values($_->@*)
+            : ref($_) eq 'HASH' ? tainted_values(values $_->%*)
+            : tainted($_) ? ($_)
+            : ()
+    } @data;
+}
+
+# The target: ZFS datasets and the nvmet configfs, with only what the plugin uses of both.
+
+my %T;
+my $seq = 0;
+
+sub new_uuid() {
+    $seq++;
+    return sprintf('%08x-dead-4000-8000-%012x', $seq, $seq);
+}
+
+sub add_volume($name, $nsid, $uuid) {
+    $T{ds}->{$name} = {
+        type => 'volume',
+        size => 1024**3,
+        origin => '-',
+        props => {
+            'proxmox:nvme-subsys' => $NQN,
+            'proxmox:nvme-nsid' => $nsid,
+            'proxmox:nvme-uuid' => $uuid,
+        },
+    };
+}
+
+# A target with two volumes of an earlier life, exported unless the target restarted since.
+sub seed($exported) {
+    %T = (
+        ds => { tank => { type => 'filesystem', props => { 'proxmox:nvme-last-nsid' => 6 } } },
+        snaps => {},
+        subsystems => {},
+        ports => {},
+        hosts => {},
+    );
+    add_volume('tank/vm-100-disk-0', 5, $UUID{5});
+    add_volume('tank/vm-100-cloudinit', 6, $UUID{6});
+    return if !$exported;
+    $T{subsystems}->{$NQN} = {
+        attr => {
+            attr_model => 'Proxmox ZFS NVMe',
+            attr_serial => PVE::Storage::ZFSNVMePlugin::_nvmet_serial($NQN),
+            attr_allow_any_host => '0',
+        },
+        acl => { map { $_ => 1 } @HOSTS },
+        ns => {
+            map {
+                my $name = $_;
+                my $props = $T{ds}->{$name}->{props};
+                (
+                    $props->{'proxmox:nvme-nsid'} => {
+                        enable => '1',
+                        device_path => "/dev/zvol/$name",
+                        device_uuid => $props->{'proxmox:nvme-uuid'},
+                        buffered_io => '0',
+                    },
+                )
+            } grep {
+                $T{ds}->{$_}->{type} eq 'volume'
+            } keys $T{ds}->%*
+        },
+    };
+    $T{hosts}->{$_} = { key => "$KEY\n" } for @HOSTS;
+    my $id = 0;
+    for my $address ('192.0.2.21', '192.0.2.22') {
+        $T{ports}->{ ++$id } = {
+            attr => {
+                addr_trtype => 'tcp',
+                addr_adrfam => 'ipv4',
+                addr_traddr => $address,
+                addr_trsvcid => '4420',
+            },
+            links => { $NQN => 1 },
+        };
+    }
+}
+
+sub parts($path) {
+    return $path =~ m{\A\Q$ROOT\E/(.+)\z} ? split(m{/}, $1) : ('');
+}
+
+sub inventory($pool) {
+    my @rows;
+    for my $name (sort grep { $_ eq $pool || m{\A\Q$pool\E/[^/]+\z} } keys $T{ds}->%*) {
+        my $ds = $T{ds}->{$name};
+        push @rows, join("\t", $name, 'type', $ds->{type}, '-');
+        for my $prop (@PROPERTIES) {
+            my $value = $ds->{props}->{$prop};
+            push @rows, join("\t", $name, $prop, defined($value) ? ($value, 'local') : ('-', '-'));
+        }
+    }
+    return @rows;
+}
+
+sub configfs($hosts) {
+    my (@dirs, @links, @attrs, @digests);
+    push @dirs, "D $ROOT", map { "D $ROOT/$_" } qw(hosts ports subsystems);
+    push @dirs, map { "D $ROOT/hosts/$_" } sort keys $T{hosts}->%*;
+    for my $id (sort { $a <=> $b } keys $T{ports}->%*) {
+        my $port = $T{ports}->{$id};
+        push @dirs, "D $ROOT/ports/$id", "D $ROOT/ports/$id/subsystems";
+        push @links, map { "L $ROOT/ports/$id/subsystems/$_" } sort keys $port->{links}->%*;
+        push @attrs, map { "$ROOT/ports/$id/$_:$port->{attr}->{$_}" } sort keys $port->{attr}->%*;
+    }
+    for my $nqn (sort keys $T{subsystems}->%*) {
+        my ($subsys, $S) = ($T{subsystems}->{$nqn}, "$ROOT/subsystems/$nqn");
+        push @dirs, "D $S", "D $S/allowed_hosts", "D $S/namespaces";
+        push @links, map { "L $S/allowed_hosts/$_" } sort keys $subsys->{acl}->%*;
+        push @attrs, map { "$S/$_:$subsys->{attr}->{$_}" } sort keys $subsys->{attr}->%*;
+        for my $id (sort { $a <=> $b } keys $subsys->{ns}->%*) {
+            my $ns = $subsys->{ns}->{$id};
+            push @dirs, "D $S/namespaces/$id";
+            push @attrs, map { "$S/namespaces/$id/$_:$ns->{$_}" } sort keys $ns->%*;
+        }
+    }
+    for my $hostnqn ($hosts->@*) {
+        push @digests,
+            sha256_hex($T{hosts}->{$hostnqn}->{key} // "\n") . "  $ROOT/hosts/$hostnqn/dhchap_key";
+    }
+    return (@dirs, @links, @attrs, @digests);
+}
+
+sub device_exists($dev) {
+    return $dev =~ m{\A/dev/zvol/(.+)\z} && $T{ds}->{$1} ? 1 : 0;
+}
+
+sub write_attr($path, $value) {
+    my @p = parts($path);
+    if ($p[0] eq 'subsystems' && @p == 3) {
+        $T{subsystems}->{ $p[1] }->{attr}->{ $p[2] } = $value;
+    } elsif ($p[0] eq 'subsystems' && @p == 5 && $p[2] eq 'namespaces') {
+        my $ns = $T{subsystems}->{ $p[1] }->{ns}->{ $p[3] } // die "no such namespace\n";
+        die "no such device\n" if $p[4] eq 'enable' && $value && !device_exists($ns->{device_path});
+        $ns->{ $p[4] } = $value if $p[4] ne 'revalidate_size';
+    } elsif ($p[0] eq 'ports' && @p == 3) {
+        $T{ports}->{ $p[1] }->{attr}->{ $p[2] } = $value;
+    } else {
+        die "write to '$path'\n";
+    }
+}
+
+sub assignments(@list) {
+    return map { /\A([^=]+)=(.*)\z/ ? ($1 => $2) : die "assignment '$_'\n" } @list;
+}
+
+sub columns(@args) {
+    return split(/,/, (map { $args[$_ + 1] } grep { $args[$_] eq '-o' } 0 .. $#args)[0]);
+}
+
+my %zfs = (
+    # the inventory, the usage of a dataset, or the owner of every dataset
+    get => sub(@args) {
+        my ($property, $name) = @args[-2, -1];
+        my @columns = columns(@args);
+        return inventory($name) if grep { $_ eq 'property' } @columns;
+        my %usage = (
+            available => 100 * 1024**3,
+            used => 3 * 1024**3,
+            volsize => $T{ds}->{$name}->{size},
+            usedbydataset => 1024**2,
+        );
+        return map { $usage{$_} // die "zfs get $_\n" } split(/,/, $property)
+            if $columns[0] eq 'value';
+        return map {
+            my $value = $T{ds}->{$_}->{props}->{$property};
+            join("\t", $_, defined($value) ? ($value, 'local') : ('-', '-'));
+        } sort grep {
+            $_ eq $name || m{\A\Q$name\E/[^/]+\z}
+        } keys $T{ds}->%*;
+    },
+    list => sub(@args) {
+        my $pool = $args[-1];
+        if (grep { $_ eq 'snapshot' } @args) {
+            my @columns = columns(@args);
+            return map {
+                my %row = (name => $_, $T{snaps}->{$_}->%{qw(guid creation)});
+                join("\t", @row{@columns});
+            } sort {
+                $T{snaps}->{$a}->{creation} <=> $T{snaps}->{$b}->{creation}
+            } grep {
+                index($_, "$pool\@") == 0
+            } keys $T{snaps}->%*;
+        }
+        return map {
+            my $ds = $T{ds}->{$_};
+            join("\t",
+                $_,
+                $ds->{type} eq 'volume' ? $ds->{size} : '-',
+                $ds->{origin} // '-',
+                $ds->{type});
+        } sort grep {
+            $_ eq $pool || m{\A\Q$pool\E/[^/]+\z}
+        } keys $T{ds}->%*;
+    },
+    create => sub(@args) {
+        my (%o, @props);
+        while (@args > 1) {
+            my $option = shift @args;
+            if ($option eq '-o') {
+                push @props, shift @args;
+            } elsif ($option eq '-V' || $option eq '-b') {
+                $o{$option} = shift @args;
+            } elsif ($option eq '-s') {
+                $o{$option} = 1;
+            } else {
+                die "zfs create option '$option'\n";
+            }
+        }
+        die "zfs create size\n" if ($o{'-V'} // '') !~ /\A([0-9]+)k\z/;
+        my $size = $1 * 1024;
+        $T{ds}->{ $args[0] } =
+            { type => 'volume', size => $size, origin => '-', props => { assignments(@props) } };
+        return ();
+    },
+    clone => sub(@args) {
+        my @props;
+        while ($args[0] eq '-o') {
+            shift @args;
+            push @props, shift @args;
+        }
+        my ($origin, $name) = @args;
+        my $snap = $T{snaps}->{$origin} // die "no snapshot '$origin'\n";
+        $T{ds}->{$name} = {
+            type => 'volume',
+            size => $snap->{size},
+            origin => $origin,
+            props => { assignments(@props) },
+        };
+        return ();
+    },
+    destroy => sub(@args) {
+        my $name = pop @args;
+        if ($name =~ /\@/) {
+            delete $T{snaps}->{$name};
+        } else {
+            die "cannot destroy '$name': dataset is busy\n" if $T{busy}->{$name};
+            delete $T{snaps}->{$_} for grep { index($_, "$name\@") == 0 } keys $T{snaps}->%*;
+            delete $T{ds}->{$name};
+        }
+        return ();
+    },
+    set => sub(@args) {
+        my $name = pop @args;
+        my $object = $name =~ /\@/ ? $T{snaps}->{$name} : $T{ds}->{$name};
+        my %set = assignments(@args);
+        for my $key (keys %set) {
+            if ($key eq 'volsize') {
+                $object->{size} = $set{$key} =~ s/k\z//r * 1024;
+            } else {
+                $object->{props}->{$key} = $set{$key};
+            }
+        }
+        return ();
+    },
+    rename => sub($old, $new) {
+        $T{ds}->{$new} = delete $T{ds}->{$old};
+        for my $snap (grep { index($_, "$old\@") == 0 } keys $T{snaps}->%*) {
+            $T{snaps}->{ $new . substr($snap, length($old)) } = delete $T{snaps}->{$snap};
+        }
+        return ();
+    },
+    snapshot => sub($snapshot) {
+        my ($name) = split /\@/, $snapshot;
+        my $ds = $T{ds}->{$name} // die "no dataset '$name'\n";
+        $seq++;
+        $T{snaps}->{$snapshot} = {
+            size => $ds->{size},
+            props => { $ds->{props}->%* },
+            guid => 4_000_000_000_000_000_000 + $seq,
+            creation => 1_700_000_000 + $seq,
+        };
+        return ();
+    },
+    # a rollback also brings back the properties of the snapshot
+    rollback => sub($snapshot) {
+        my ($name) = split /\@/, $snapshot;
+        my $snap = $T{snaps}->{$snapshot} // die "no snapshot '$snapshot'\n";
+        $T{ds}->{$name}->{props} = { $snap->{props}->%* };
+        $T{ds}->{$name}->{size} = $snap->{size};
+        return ();
+    },
+);
+
+my %command = (
+    modprobe => sub(@args) { return () },
+    chmod => sub(@args) { return () },
+    mount => sub(@args) { return () },
+    cat => sub($file) { return ('configfs /sys/kernel/config configfs rw,relatime 0 0') },
+    printf => sub($format, $text) { return ($text) },
+    test => sub($flag, $path) {
+        if ($flag eq '-b') {
+            die "not a block device\n" if !device_exists($path);
+            return ();
+        }
+        my @p = parts($path);
+        my $found =
+            $p[0] eq 'subsystems'
+            ? $T{subsystems}->{ $p[1] }->{acl}->{ $p[3] }
+            : $T{ports}->{ $p[1] }->{links}->{ $p[3] };
+        die "no such link\n" if !$found;
+        return ();
+    },
+    grep => sub($flag, $value, $path) {
+        my @p = parts($path);
+        die "other value\n" if $T{subsystems}->{ $p[1] }->{attr}->{ $p[2] } ne $value;
+        return ();
+    },
+    mkdir => sub($path) {
+        my @p = parts($path);
+        if ($p[0] eq 'subsystems' && @p == 2) {
+            $T{subsystems}->{ $p[1] } = {
+                attr => {
+                    attr_model => 'Linux',
+                    attr_serial => '0123456789abcdef',
+                    attr_allow_any_host => '1',
+                },
+                acl => {},
+                ns => {},
+            };
+        } elsif ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+            $T{subsystems}->{ $p[1] }->{ns}->{ $p[3] } = {
+                enable => '0',
+                device_path => '(null)',
+                device_uuid => new_uuid(),
+                buffered_io => '0',
+            };
+        } elsif ($p[0] eq 'ports' && @p == 2) {
+            $T{ports}->{ $p[1] } = {
+                attr => { map { ("addr_$_" => '') } qw(trtype adrfam traddr trsvcid) },
+                links => {},
+            };
+        } elsif ($p[0] eq 'hosts' && @p == 2) {
+            $T{hosts}->{ $p[1] } = {};
+        } else {
+            die "mkdir '$path'\n";
+        }
+        return ();
+    },
+    rmdir => sub($path) {
+        my @p = parts($path);
+        die "rmdir '$path'\n" if $p[0] ne 'subsystems' || @p != 4 || $p[2] ne 'namespaces';
+        delete $T{subsystems}->{ $p[1] }->{ns}->{ $p[3] } or die "no such namespace\n";
+        return ();
+    },
+    rm => sub($path) {
+        my @p = parts($path);
+        die "rm '$path'\n" if $p[0] ne 'ports' || @p != 4;
+        delete $T{ports}->{ $p[1] }->{links}->{ $p[3] };
+        return ();
+    },
+    ln => sub($flag, $target, $link) {
+        my @p = parts($link);
+        if ($p[0] eq 'ports' && @p == 4) {
+            $T{ports}->{ $p[1] }->{links}->{ $p[3] } = 1;
+        } elsif ($p[0] eq 'subsystems' && @p == 4) {
+            $T{subsystems}->{ $p[1] }->{acl}->{ $p[3] } = 1;
+        } else {
+            die "ln '$link'\n";
+        }
+        return ();
+    },
+    env => sub(@args) {
+        my @hosts = map { $args[$_ + 1] =~ m{/hosts/([^/]+)/dhchap_key\z} ? ($1) : () }
+            grep { $args[$_] eq '-path' } 0 .. $#args;
+        return configfs(\@hosts);
+    },
+    zfs => sub($verb, @args) {
+        return ($zfs{$verb} // die "zfs $verb\n")->(@args);
+    },
+);
+
+sub run_step($step, $input) {
+    if (ref($step) eq 'HASH' && exists($step->{write})) {
+        write_attr($step->{write}, $step->{value});
+        return ();
+    }
+    if (ref($step) eq 'HASH') {
+        for my $path ($step->{key}->@*) {
+            my @p = parts($path);
+            ($T{hosts}->{ $p[1] } // die "no such host\n")->{key} = $input;
+        }
+        return ();
+    }
+    my ($name, @args) = $step->@*;
+    return ($command{$name} // die "command '$name'\n")->(@args);
+}
+
+# What reaches a command or a file system call is checked here and by the real calls below.
+
+my @violations;
+my $steps_sent;
+my $now = 1_000_000;
+my @warnings;
+
+my $real = {
+    file_write => PVE::SysFSTools->can('file_write'),
+    dir_glob_foreach => PVE::File->can('dir_glob_foreach'),
+    restrict_attr => $PLUGIN->can('_restrict_attr'),
+    render => $PLUGIN->can('_nvmet_render'),
+};
+
+my $plugin = Test::MockModule->new($PLUGIN);
+$plugin->redefine(
+    # Every command is a real exec of true in taint mode, the plugin then gets the model's answer.
+    run_command => sub($cmd, %opts) {
+        push @violations, "a tainted word in the command '$cmd->[0]'"
+            if grep { tainted($_) } $cmd->@*;
+        push @violations, "tainted input for the command '$cmd->[0]'" if tainted($opts{input});
+        PVE::Tools::run_command(['/usr/bin/true', $cmd->@*], timeout => 10);
+        return 0 if $cmd->[0] ne '/usr/bin/ssh';
+
+        my @out = eval {
+            map { run_step($_, $opts{input}) } $steps_sent->@*;
+        };
+        if (my $error = $@) {
+            chomp($error);
+            $opts{errfunc}->($error);
+            die "command 'ssh' failed: exit code 1\n";
+        }
+        $opts{outfunc}->($_) for as_read(@out);
+        return 0;
+    },
+    _nvmet_render => sub($steps) {
+        $steps_sent = $steps;
+        return $real->{render}->($steps);
+    },
+    file_read_firstline => sub($path) { return PVE::File::file_read_first_line(fs($path)) },
+    file_set_contents =>
+        sub($path, @rest) { return PVE::File::file_set_contents(fs($path), @rest) },
+    make_path => sub($path, @rest) { return File::Path::make_path(fs($path), @rest) },
+    _unlink_file => sub($path) { return unlink(fs($path)) },
+    _restrict_attr => sub($path) { return $real->{restrict_attr}->(fs($path)) },
+    # a file stands in for the link, as the read of either is tainted
+    _link_target => sub($path) { return PVE::File::file_read_first_line(fs($path)) },
+    _block_device => sub($path) { return -e fs($path) },
+    _local_iface_exists => sub($iface) { return 1 },
+    _nvme_tcp_loaded => sub() { return 1 },
+    _namespace_users => sub($nqn) { return [] },
+    _now => sub() { return $now },
+    _sleep => sub($seconds) { $now += $seconds; return },
+    log_warn => sub($message) { push @warnings, $message; return },
+);
+my $file = Test::MockModule->new('PVE::File');
+$file->redefine(
+    dir_glob_foreach => sub($path, $regex, $func) {
+        return $real->{dir_glob_foreach}->(fs($path), $regex, $func);
+    },
+);
+my $sysfs = Test::MockModule->new('PVE::SysFSTools');
+$sysfs->redefine(
+    file_write => sub($path, @rest) { return $real->{file_write}->(fs($path), @rest) });
+my $nvmeof = Test::MockModule->new('PVE::NVMeOF');
+$nvmeof->redefine(with_lock => sub($code, $limit = undef) { return $code->() });
+my $cluster = Test::MockModule->new('PVE::Cluster');
+$cluster->redefine(
+    check_cfs_quorum => sub($noerr = undef) { return 1 },
+    cfs_lock_domain => sub($name, $timeout, $code, @param) {
+        my $res = eval { $code->(@param) };
+        my $error = $@;
+        $@ = $error;
+        return $error ? undef : $res;
+    },
+);
+
+# the storage as a node reads it: the text of storage.cfg is read from a file
+put('/etc/pve/storage.cfg', <<"EOF");
+zfsnvme: nvme1
+\tserver 192.0.2.10
+\tpool tank
+\tblocksize 16k
+\tsparse 1
+\tsubsysnqn $NQN
+\tnvme-portals 192.0.2.21,192.0.2.22
+\tnvme-host-ifaces ens19,ens20
+\tnvme-host-nqns @{[join(',', @HOSTS)]}
+\tnvme-keep-alive-tmo 5
+\tnvme-ctrl-loss-tmo 600
+
+EOF
+my $raw = file_get_contents(fs('/etc/pve/storage.cfg'));
+my $cfg = PVE::Storage::Plugin->parse_config('storage.cfg', $raw);
+my ($storeid) = grep { $_ eq 'nvme1' } keys $cfg->{ids}->%*;
+my $scfg = $cfg->{ids}->{$storeid};
+my $secret = "/etc/pve/priv/storage/$storeid.nvme-dhchap";
+my $storage = Test::MockModule->new('PVE::Storage');
+$storage->redefine(config => sub() { return $cfg });
+
+put('/etc/nvme/hostnqn', "$HOSTS[0]\n");
+put('/etc/nvme/hostid', "11111111-2222-4333-8444-555555555555\n");
+local $PVE::NVMeOF::HOSTNQN_FILE = fs('/etc/nvme/hostnqn');
+local $PVE::NVMeOF::HOSTID_FILE = fs('/etc/nvme/hostid');
+
+sub flow($name, $code) {
+    subtest $name => sub {
+        @violations = ();
+        @warnings = ();
+        my $res = eval { $code->() };
+        is($@, '', 'it completes in taint mode');
+        is_deeply(\@violations, [], 'nothing tainted reaches a command or a file system call');
+        is_deeply(\@warnings, [], 'without warnings');
+        return $res;
+    };
+}
+
+sub proc_uuid($uuid) {
+    put('/proc/sys/kernel/random/uuid', "$uuid\n");
+}
+
+sub ns_of($nsid) {
+    return $T{subsystems}->{$NQN}->{ns}->{$nsid};
+}
+
+sub identity($name) {
+    my $props = $T{ds}->{$name}->{props};
+    return [@{$props}{qw(proxmox:nvme-nsid proxmox:nvme-uuid)}];
+}
+
+ok(tainted(file_get_contents(fs('/etc/pve/storage.cfg'))), 'a file read is tainted');
+is(
+    scalar(grep { tainted($_) } $storeid, values $scfg->%*),
+    0,
+    'storage.cfg values and the storage ID come out of the parser untainted',
+);
+put($secret, "$KEY\n");
+proc_uuid($UUID{new});
+ok(tainted(PVE::File::file_read_first_line(fs('/proc/sys/kernel/random/uuid'))), 'so is the UUID');
+ok(tainted((as_read('a'))[0]), 'and the answer of the target');
+
+flow(
+    'a ZFS inventory that comes back in several reads' => sub {
+        seed(1);
+        for my $i (1 .. 60) {
+            add_volume(
+                "tank/vm-$i-disk-0",
+                10 + $i,
+                sprintf('%08x-aaaa-4000-8000-%012x', $i, $i),
+            );
+        }
+        # run_command passes on a last row without newline tainted, and so are the rows that
+        # span two reads of 4096 bytes
+        my $uuid_row = qr{\Atank/vm-9-disk-0\tproxmox:nvme-uuid\t};
+        my @rows = inventory('tank');
+        @rows = ((grep { $_ !~ $uuid_row } @rows), (grep { $_ =~ $uuid_row } @rows));
+        my $last = pop @rows;
+        file_set_contents("$dir/inventory", join('', map { "$_\n" } @rows) . $last);
+        my @lines;
+        PVE::Tools::run_command(
+            ['/bin/cat', "$dir/inventory"],
+            outfunc => sub($line) { push @lines, $line },
+        );
+        ok(tainted($lines[-1]), 'the row of a UUID is tainted');
+        my $text = join('', map { "$_\n" } @lines);
+        my $inv = PVE::Storage::ZFSNVMePlugin::_nvmet_parse_zfs_inventory($text, 'tank');
+        my @identity =
+            PVE::Storage::ZFSNVMePlugin::_nvmet_owned_identity($inv, $NQN, 'tank/vm-9-disk-0');
+        is_deeply(\@identity, [19, '00000009-aaaa-4000-8000-000000000009'], 'its identity');
+        is(scalar(grep { tainted($_) } @identity, $inv->{last_nsid}), 0, 'is untainted');
+    },
+);
+
+flow(
+    'add and the first activation rebuild the namespaces after a restart' => sub {
+        seed(0);
+        $PLUGIN->on_add_hook($storeid, $scfg, 'dhchap-key' => $KEY);
+        is(file_get_contents(fs($secret)), "$KEY\n", 'the key file is written');
+        my $portals = PVE::Storage::ZFSNVMePlugin::_configured_portals($scfg);
+        my $hostnqns =
+            PVE::Storage::ZFSNVMePlugin::parse_nvme_host_nqns($scfg->{'nvme-host-nqns'});
+        my $key = PVE::Storage::ZFSNVMePlugin::_validate_secret(
+            PVE::File::file_read_first_line(fs($secret)),
+        );
+        ok(!tainted($key), 'the key is untainted');
+        PVE::Storage::ZFSNVMePlugin::_nvmet_activate_target(
+            $storeid, $scfg, $portals, $hostnqns, $key,
+        );
+        is_deeply(
+            [map { [@{ ns_of($_) }{qw(enable device_uuid device_path)}] } 5, 6],
+            [
+                ['1', $UUID{5}, '/dev/zvol/tank/vm-100-disk-0'],
+                ['1', $UUID{6}, '/dev/zvol/tank/vm-100-cloudinit'],
+            ],
+            'the namespaces are rebuilt from the ZFS properties',
+        );
+        is_deeply(
+            [sort keys $T{subsystems}->{$NQN}->{acl}->%*],
+            [sort @HOSTS],
+            'the hosts are allowed',
+        );
+        is(
+            scalar(grep { $_->{links}->{$NQN} } values $T{ports}->%*),
+            2,
+            'both ports publish it',
+        );
+        is($T{hosts}->{ $HOSTS[0] }->{key}, "$KEY\n", 'the key reached the host object');
+    },
+);
+
+flow(
+    'add a disk' => sub {
+        seed(1);
+        proc_uuid($UUID{new});
+        my $name = $PLUGIN->alloc_image(
+            $storeid, $scfg, 101, 'raw', undef, 4 * 1024 * 1024,
+        );
+        is($name, 'vm-101-disk-0', 'the volume name');
+        is_deeply(
+            identity("tank/$name"),
+            [7, $UUID{new}],
+            'the identity comes from the pool and /proc',
+        );
+        is($T{ds}->{tank}->{props}->{'proxmox:nvme-last-nsid'}, 7, 'the NSID is reserved');
+        is_deeply(
+            [@{ ns_of(7) }{qw(enable device_uuid)}],
+            ['1', $UUID{new}],
+            'the namespace is exported',
+        );
+    },
+);
+
+flow(
+    'convert to a template and clone it' => sub {
+        seed(1);
+        proc_uuid($UUID{new});
+        my $base = $PLUGIN->create_base($storeid, $scfg, 'vm-100-disk-0');
+        is($base, 'base-100-disk-0', 'the template name');
+        is_deeply(identity("tank/$base"), [5, $UUID{5}], 'the template keeps its identity');
+        is(ns_of(5)->{device_path}, '/dev/zvol/tank/base-100-disk-0', 'and its namespace');
+        my $clone = $PLUGIN->clone_image($scfg, $storeid, $base, 102);
+        is($clone, 'base-100-disk-0/vm-102-disk-0', 'the clone name');
+        is_deeply(
+            identity('tank/vm-102-disk-0'),
+            [7, $UUID{new}],
+            'the clone has a new identity',
+        );
+        is(
+            $T{ds}->{'tank/vm-102-disk-0'}->{origin},
+            'tank/base-100-disk-0@__base__',
+            'and origin',
+        );
+        is(ns_of(7)->{enable}, '1', 'its namespace is exported');
+    },
+);
+
+flow(
+    'snapshot, roll back and resize' => sub {
+        seed(1);
+        $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', 'before');
+        $PLUGIN->volume_snapshot_rollback($scfg, $storeid, 'vm-100-disk-0', 'before');
+        is_deeply(identity('tank/vm-100-disk-0'), [5, $UUID{5}], 'the identity is kept');
+        is_deeply(
+            [@{ ns_of(5) }{qw(enable device_uuid)}],
+            ['1', $UUID{5}],
+            'the namespace is exported again',
+        );
+        is(
+            $PLUGIN->volume_resize($scfg, $storeid, 'vm-100-disk-0', 2 * 1024**3, 0),
+            2097152,
+            'resize',
+        );
+        is($T{ds}->{'tank/vm-100-disk-0'}->{size}, 2 * 1024**3, 'to the new size');
+    },
+);
+
+flow(
+    'resize to the size that the target reports plus a delta' => sub {
+        seed(1);
+        my $size = $PLUGIN->volume_size_info($scfg, $storeid, 'vm-100-disk-0');
+        is($size, 1024**3, 'the size');
+        is(
+            $PLUGIN->volume_resize($scfg, $storeid, 'vm-100-disk-0', $size + 1024**3, 0),
+            2097152,
+            'resize',
+        );
+        is($T{ds}->{'tank/vm-100-disk-0'}->{size}, 2 * 1024**3, 'to the new size');
+    },
+);
+
+flow(
+    'a disk move allocates the size of its source' => sub {
+        seed(1);
+        proc_uuid($UUID{new});
+        my ($size) = $PLUGIN->volume_size_info($scfg, $storeid, 'vm-100-disk-0');
+        my $name = $PLUGIN->alloc_image($storeid, $scfg, 101, 'raw', undef, $size / 1024);
+        is($T{ds}->{"tank/$name"}->{size}, 1024**3, 'the new disk has the size of the source');
+    },
+);
+
+# The daemons untaint what an API call passes, an internal caller (qemu-server, vzdump, the
+# replication) may pass values that it read from a file or a pipe.
+
+flow(
+    'an internal caller passes a size that is tainted' => sub {
+        seed(1);
+        proc_uuid(new_uuid());
+        my ($size, $bytes) = as_read(4096, 5120 * 1024);
+        ok(tainted($size) && tainted($bytes), 'the sizes are tainted');
+        my $name = $PLUGIN->alloc_image($storeid, $scfg, 101, 'raw', undef, $size);
+        is($T{ds}->{"tank/$name"}->{size}, 4096 * 1024, 'add a disk');
+        $PLUGIN->volume_resize($scfg, $storeid, $name, $bytes, 0);
+        is($T{ds}->{"tank/$name"}->{size}, 5120 * 1024, 'resize');
+    },
+);
+
+flow(
+    'an internal caller passes a VM ID and a name that are tainted' => sub {
+        seed(1);
+        my ($vmid, $name) = as_read(101, 'vm-101-disk-0');
+        ok(tainted($vmid) && tainted($name), 'they are tainted');
+        proc_uuid(new_uuid());
+        is(
+            $PLUGIN->alloc_image($storeid, $scfg, $vmid, 'raw', $name, 4096),
+            'vm-101-disk-0',
+            'add a disk with its name',
+        );
+        proc_uuid(new_uuid());
+        is(
+            $PLUGIN->alloc_image($storeid, $scfg, $vmid, 'raw', undef, 4096),
+            'vm-101-disk-1',
+            'and one with the name that the storage picks',
+        );
+        proc_uuid(new_uuid());
+        my ($base) = as_read('base-100-disk-0');
+        $PLUGIN->create_base($storeid, $scfg, 'vm-100-disk-0');
+        is(
+            $PLUGIN->clone_image($scfg, $storeid, $base, $vmid),
+            'base-100-disk-0/vm-101-disk-2',
+            'clone a template under the VM ID',
+        );
+    },
+);
+
+flow(
+    'an internal caller passes snapshot names that are tainted' => sub {
+        seed(1);
+        proc_uuid(new_uuid());
+        my ($snap, $tag, $base) = as_read('before', '__base__', 'base-100-disk-0');
+        ok(tainted($snap) && tainted($tag), 'they are tainted');
+        $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', $snap);
+        ok($T{snaps}->{'tank/vm-100-disk-0@before'}, 'snapshot');
+        ok(
+            $PLUGIN->volume_rollback_is_possible($scfg, $storeid, 'vm-100-disk-0', $snap),
+            'check',
+        );
+        $PLUGIN->volume_snapshot_rollback($scfg, $storeid, 'vm-100-disk-0', $snap);
+        $PLUGIN->volume_snapshot_delete($scfg, $storeid, 'vm-100-disk-0', $snap);
+        ok(!$T{snaps}->{'tank/vm-100-disk-0@before'}, 'delete');
+        $PLUGIN->create_base($storeid, $scfg, 'vm-100-disk-0');
+        is(
+            $PLUGIN->clone_image($scfg, $storeid, $base, 102, $tag),
+            'base-100-disk-0/vm-102-disk-0',
+            'clone a template from its snapshot',
+        );
+    },
+);
+
+flow(
+    'the rows that the methods return are untainted' => sub {
+        seed(1);
+        proc_uuid($UUID{new});
+        $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', 'before');
+        $PLUGIN->volume_snapshot($scfg, $storeid, 'vm-100-disk-0', 'later');
+        $PLUGIN->create_base($storeid, $scfg, 'vm-100-cloudinit');
+        $PLUGIN->clone_image($scfg, $storeid, 'base-100-cloudinit', 102);
+
+        my $images = $PLUGIN->list_images($storeid, $scfg);
+        is_deeply(
+            [sort map { $_->{volid} } $images->@*],
+            [
+                "$storeid:base-100-cloudinit",
+                "$storeid:base-100-cloudinit/vm-102-disk-0",
+                "$storeid:vm-100-disk-0",
+            ],
+            'the images',
+        );
+        my ($clone) = grep { $_->{name} eq 'vm-102-disk-0' } $images->@*;
+        is($clone->{parent}, 'base-100-cloudinit@__base__', 'the parent of a clone');
+        is_deeply([tainted_values($images)], [], 'list_images returns untainted rows');
+
+        my $snapshots = $PLUGIN->volume_snapshot_info($scfg, $storeid, 'vm-100-disk-0');
+        is_deeply([sort keys $snapshots->%*], ['before', 'later'], 'the snapshots');
+        is_deeply(
+            [tainted_values($snapshots)],
+            [],
+            'volume_snapshot_info returns untainted rows',
+        );
+
+        my @blockers;
+        eval {
+            $PLUGIN->volume_rollback_is_possible(
+                $scfg, $storeid, 'vm-100-disk-0', 'before', \@blockers,
+            );
+        };
+        like($@, qr/is not most recent snapshot/, 'a rollback past a snapshot is refused');
+        is_deeply(\@blockers, ['later'], 'it names the snapshot in the way');
+        is_deeply([tainted_values(\@blockers)], [], 'untainted');
+
+        my @usage = $PLUGIN->status($storeid, $scfg);
+        is_deeply(
+            \@usage,
+            [103 * 1024**3, 100 * 1024**3, 3 * 1024**3, 1],
+            'the usage of the pool',
+        );
+        is_deeply([tainted_values(\@usage)], [], 'status returns untainted values');
+
+        my @info = $PLUGIN->volume_size_info($scfg, $storeid, 'vm-100-disk-0');
+        is_deeply(\@info, [1024**3, 'raw', 1024**2, undef], 'the size info of a volume');
+        is_deeply([tainted_values(\@info)], [], 'volume_size_info returns untainted values');
+    },
+);
+
+flow(
+    'remove a disk' => sub {
+        seed(1);
+        $PLUGIN->free_image($storeid, $scfg, 'vm-100-disk-0');
+        ok(!$T{ds}->{'tank/vm-100-disk-0'}, 'the zvol is gone');
+        ok(!ns_of(5), 'and its namespace');
+        ok(ns_of(6), 'the other namespace stays');
+    },
+);
+
+flow(
+    'a busy zvol keeps its namespace' => sub {
+        seed(1);
+        $T{busy}->{'tank/vm-100-disk-0'} = 1;
+        eval { $PLUGIN->free_image($storeid, $scfg, 'vm-100-disk-0') };
+        like($@, qr/dataset is busy; namespace restored\n\z/, 'the removal is refused');
+        is_deeply(
+            [@{ ns_of(5) }{qw(enable device_uuid device_path)}],
+            ['1', $UUID{5}, '/dev/zvol/tank/vm-100-disk-0'],
+            'the namespace is exported again as it was',
+        );
+    },
+);
+
+flow(
+    'the path of a disk reaches a guest command line' => sub {
+        seed(1);
+        put("/dev/disk/by-id/nvme-uuid.$UUID{5}", "../../nvme0n1\n");
+        put('/sys/block/nvme0n1/uuid', "$UUID{5}\n");
+        put('/sys/block/nvme0n1/nsid', "5\n");
+        put('/sys/block/nvme0n1/device/subsysnqn', "$NQN\n");
+        my ($path) = $PLUGIN->path($scfg, 'vm-100-disk-0', $storeid);
+        is($path, "/dev/disk/by-id/nvme-uuid.$UUID{5}", 'the path');
+        my $options = $PLUGIN->qemu_blockdev_options($scfg, $storeid, 'vm-100-disk-0');
+        is(scalar(grep { tainted($_) } $path, $options->{filename}), 0, 'it is untainted');
+        is(
+            $PLUGIN->activate_volume($storeid, $scfg, 'vm-100-disk-0'),
+            1,
+            'the volume is active',
+        );
+    },
+);
+
+flow(
+    'the node side reads sysfs and changes controllers' => sub {
+        for my $i (0, 1) {
+            my $c = "/sys/class/nvme/nvme$i";
+            put("$c/subsysnqn", "$NQN\n");
+            put(
+                "$c/address",
+                sprintf("traddr=192.0.2.2%d,trsvcid=4420,host_iface=ens%d\n", $i + 1, 19 + $i),
+            );
+            put("$c/state", "live\n");
+            put("$c/reconnect_delay", "7\n");
+            put("$c/ctrl_loss_tmo", "70\n");
+            put("$c/fast_io_fail_tmo", "off\n");
+            put("$c/dhchap_secret", "$KEY\n", 0644);
+            put("$c/dhchap_ctrl_secret", "\n", 0644);
+        }
+        put('/sys/class/nvme-subsystem/nvme-subsys0/subsysnqn', "$NQN\n");
+        put('/sys/class/nvme-subsystem/nvme-subsys0/iopolicy', "numa\n");
+        put('/sys/module/nvme_core/parameters/multipath', "Y\n");
+        is($PLUGIN->activate_storage($storeid, $scfg, {}), 1, 'activation');
+        is(
+            file_get_contents(fs('/sys/class/nvme-subsystem/nvme-subsys0/iopolicy')),
+            "round-robin\n",
+            'policy',
+        );
+        is(file_get_contents(fs('/sys/class/nvme/nvme1/reconnect_delay')), "2\n", 'tunables');
+        is($PLUGIN->deactivate_storage($storeid, $scfg), 1, 'deactivation');
+        is(
+            join('',
+                map { file_get_contents(fs("/sys/class/nvme/nvme$_/delete_controller")) } 0,
+                1),
+            '11',
+            'both controllers are deleted',
+        );
+    },
+);
+
+flow(
+    'remove the storage' => sub {
+        $PLUGIN->on_delete_hook($storeid, $scfg);
+        ok(!-e fs($secret), 'the key file is gone');
+    },
+);
+
+flow(
+    'an internal caller names the storage with a tainted ID' => sub {
+        my ($id) = as_read($storeid);
+        ok(tainted($id), 'the ID is tainted');
+        $PLUGIN->on_add_hook($id, $scfg, 'dhchap-key' => $KEY);
+        is(file_get_contents(fs($secret)), "$KEY\n", 'the key file is written');
+        $PLUGIN->on_delete_hook($id, $scfg);
+        ok(!-e fs($secret), 'and removed');
+
+        my ($other) = as_read('../x');
+        eval { $PLUGIN->on_delete_hook($other, $scfg) };
+        is($@, "invalid storage ID\n", 'an ID that is not valid is refused');
+    },
+);
+
+done_testing();
diff --git a/src/test/zfsnvme_target_test.pm b/src/test/zfsnvme_target_test.pm
index 4ea7057b..687ba7fd 100644
--- a/src/test/zfsnvme_target_test.pm
+++ b/src/test/zfsnvme_target_test.pm
@@ -3745,4 +3745,770 @@ subtest 'target call timeouts' => sub {
     $rpcenv_mock->unmock_all();
 };
 
+# The goals of the swept flows. They only read the state: a lookup that
+# created a missing namespace would change the outcome of the next check.
+sub exported_ns($m, $nsid) {
+    my $subsys = $m->{subsystems}->{$NQN} // return undef;
+    return $subsys->{ns}->{$nsid};
+}
+
+sub template_done($m, $res) {
+    my $ds = owned_volumes($m)->{'tank/base-101-disk-0'} // return 'template missing';
+    my $ns = exported_ns($m, 2) // return 'template not exported';
+    return 'template not exported' if $ns->{device_path} ne '/dev/zvol/tank/base-101-disk-0';
+    return $m->{snaps}->{'tank/base-101-disk-0@__base__'} ? () : 'base snapshot missing';
+}
+
+sub new_volume_done($name) {
+    return sub($m, $res) {
+        my $owned = owned_volumes($m)->{"tank/$name"} // return "$name missing";
+        my $ns = exported_ns($m, $owned->[0]) // return "$name not exported";
+        return () if $ns->{enable} eq '1' && $ns->{device_uuid} eq $owned->[1];
+        return "$name not exported";
+    };
+}
+
+subtest 'fault sweep' => sub {
+    sweep(
+        'create',
+        {
+            setup => \&lifecycle_fake,
+            lost_replies => 1,
+            action => $ACT{alloc},
+            done => new_volume_done('vm-200-disk-0'),
+        },
+    );
+    sweep(
+        'clone',
+        {
+            setup => \&lifecycle_fake,
+            lost_replies => 1,
+            action => $ACT{clone},
+            done => new_volume_done('vm-201-disk-0'),
+        },
+    );
+    sweep(
+        'destroy',
+        {
+            setup => \&lifecycle_fake,
+            action => $ACT{free},
+            may_vanish => 'tank/vm-101-disk-0',
+            done => sub($m, $res) { $m->{ds}->{'tank/vm-101-disk-0'} ? 'volume left' : () },
+        },
+    );
+    sweep(
+        'rollback',
+        {
+            setup => \&lifecycle_fake,
+            action => $ACT{rollback},
+            done => sub($m, $res) {
+                my $ns = exported_ns($m, 1) // return 'not exported';
+                return $ns->{enable} eq '1' ? () : 'not exported';
+            },
+        },
+    );
+    sweep(
+        'template',
+        {
+            setup => \&lifecycle_fake,
+            action => $ACT{template},
+            renames => { 'tank/vm-101-disk-0' => 'tank/base-101-disk-0' },
+            done => \&template_done,
+        },
+    );
+    sweep(
+        'resize',
+        {
+            setup => \&lifecycle_fake,
+            action => $ACT{resize},
+            done => sub($m, $res) {
+                my $ds = $m->{ds}->{'tank/vm-100-disk-0'} // return 'volume missing';
+                return 'not resized' if $ds->{volsize} != 2 * 1024**3;
+                return $res->{fake}->{revalidated}->{"$NQN/1"} ? () : 'not revalidated';
+            },
+        },
+    );
+    sweep(
+        'activation after a configfs loss',
+        {
+            setup => sub () { lifecycle_fake()->reboot(1) },
+            action => $ACT{activate},
+            done => sub($m, $res) { () },
+        },
+    );
+};
+
+subtest 'two storages on one target' => sub {
+    my $nqn_b = 'nqn.2026-01.com.example:zfsnvme-b';
+    my $scfg_a = scfg(pool => 'tank/a');
+    my $scfg_b = scfg(pool => 'tank/b', subsysnqn => $nqn_b);
+    my $new = sub () { FakeTarget->new(pools => [qw(tank tank/a tank/b)]) };
+
+    # B, with another key, takes the lock first, between A's lockless read and A's locked read
+    my $fake = $new->();
+    my ($res, $b_res);
+    {
+        local $LOCK_HOOK = sub($name) {
+            $b_res = flow($fake, sub { activate($scfg_b, $KEY_B) });
+        };
+        $res = flow($fake, sub { activate($scfg_a, $KEY) });
+    }
+    is($b_res->{error}, '', 'B configures the target first');
+    like($res->{error}, qr/in-use DH-HMAC-CHAP key/, 'A is refused by its locked read');
+    ok(!$fake->{m}->{subsystems}->{$NQN}, 'without creating anything');
+    is_deeply(
+        [map { $fake->{m}->{hosts}->{$_}->{key} } @HOSTS],
+        [$KEY_B, $KEY_B],
+        "B's key is kept",
+    );
+
+    # (a) a target restart between the verify read and the publish
+    for my $loaded (0, 1) {
+        $fake = FakeTarget->new(pools => ['tank']);
+        my $restarted = 0;
+        my @online;
+        my $ctx =
+            { nqn => $NQN, pool => 'tank', hosts => [@HOSTS], key => $KEY, port_ids => [] };
+        $ctx->{foreign} = foreign_view($fake->{m}, [], $NQN, [@HOSTS]);
+        $fake->{before_call} = sub($f, $call) {
+            $f->reboot($loaded) if $call->{op} =~ /\Alink / && !$restarted++;
+        };
+        $fake->{after_call} = sub($f, $call) { push @online, online_violations($f, $ctx) };
+        $res = flow($fake, $ACT{activate});
+        like(
+            $res->{error},
+            qr/cannot publish NVMe subsystem '\Q$NQN\E'/,
+            'a restart before the publish fails it',
+        );
+        ok(!grep({ $_->{links}->%* } values $fake->{m}->{ports}->%*), 'nothing is linked');
+        $fake->{before_call} = undef;
+        $res = flow($fake, $ACT{activate});
+        is($res->{error}, '', 'the next activation restores the target');
+        is_deeply(\@online, [], 'never published before the ACLs and keys');
+        ok(
+            $fake->{m}->{ports}->{1}->{links}->{$NQN}
+                && $fake->{m}->{ports}->{2}->{links}->{$NQN},
+            'and publishes it',
+        );
+    }
+
+    # ports are shared, whoever creates them
+    $fake = $new->();
+    {
+        local $LOCK_HOOK = sub($name) {
+            $b_res = flow($fake, sub { activate($scfg_b, $KEY) });
+        };
+        $res = flow($fake, sub { activate($scfg_a, $KEY) });
+    }
+    ok(!$res->{error} && !$b_res->{error}, 'two storages with one key on the same portals');
+    is_deeply(
+        [sort map { $_->{attr}->{addr_traddr} } values $fake->{m}->{ports}->%*],
+        ['192.0.2.21', '192.0.2.22'],
+        'share one port per address',
+    );
+    ok(
+        !grep({ !($_->{links}->{$NQN} && $_->{links}->{$nqn_b}) }
+            values $fake->{m}->{ports}->%*),
+        'both subsystems are published on both',
+    );
+
+    # lifecycle operations of both storages
+    my ($a_vol, $b_vol);
+    {
+        local $LOCK_HOOK = sub($name) {
+            $b_vol = flow(
+                $fake, sub { $PLUGIN->alloc_image('b', $scfg_b, 300, 'raw', undef, 1024) },
+            );
+        };
+        $a_vol =
+            flow($fake, sub { $PLUGIN->alloc_image('a', $scfg_a, 300, 'raw', undef, 1024) });
+    }
+    is_deeply(
+        [$a_vol->{result}, $b_vol->{result}],
+        ['vm-300-disk-0', 'vm-300-disk-0'],
+        'volumes in both pools',
+    );
+    is_deeply(
+        [
+            sort keys $fake->{m}->{subsystems}->{$NQN}->{ns}->%*,
+            sort keys $fake->{m}->{subsystems}->{$nqn_b}->{ns}->%*,
+        ],
+        [1, 1],
+        'with independent namespace IDs',
+    );
+};
+
+subtest 'each port is published on its own' => sub {
+    my $fake = FakeTarget->new(pools => ['tank'], unbindable => { 2 => 1 });
+    my $res = flow($fake, $ACT{activate});
+    is($res->{error}, '', 'a port that cannot bind its address');
+    like(
+        join("\n", $res->{warnings}->@*),
+        qr/cannot publish NVMe subsystem '\Q$NQN\E' on port 2: .*Cannot assign requested address/,
+        'only warns',
+    );
+    ok(
+        $fake->{m}->{ports}->{1}->{links}->{$NQN} && !$fake->{m}->{ports}->{2}->{links}->{$NQN},
+        'while the other port serves the subsystem',
+    );
+    $res = flow($fake, $ACT{activate});
+    ok(grep({ $_ eq 'link NVMe subsystem on port 2' } ops($res)->@*), 'and is retried');
+
+    $fake = FakeTarget->new(pools => ['tank'], unbindable => { 1 => 1, 2 => 1 });
+    $res = flow($fake, $ACT{activate});
+    like(
+        $res->{error},
+        qr/\Acannot publish NVMe subsystem '\Q$NQN\E': ln: .*Cannot assign requested address\n\z/,
+        'without any port the activation fails',
+    );
+};
+
+subtest 'UUIDs are compared in lower case' => sub {
+    my $upper = uc($U{9} =~ tr/9/a/r);
+    my $lower = lc($upper);
+    is(
+        inventory(@POOL, zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $upper))->{volumes}
+            ->{'tank/vm-100-disk-0'}->{uuid},
+        $lower,
+        'the inventory normalizes the UUID',
+    );
+    my $dup = inventory(
+        @POOL,
+        zfs_rows('tank/vm-100-disk-0', 'volume', $NQN, 1, $upper),
+        zfs_rows('tank/vm-101-disk-0', 'volume', $NQN, 2, $lower),
+    );
+    eval { nv('_nvmet_owned_identity', $dup, $NQN, 'tank/vm-100-disk-0') };
+    like($@, qr/duplicate NVMe identity/, 'a UUID that differs only in case is a duplicate');
+
+    my $fake = target_fake();
+    $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $upper]);
+    my $res = flow($fake, $ACT{activate});
+    is($res->{error}, '', 'the volume is exported');
+    ok(exported($fake, 1, $lower, '/dev/zvol/tank/vm-100-disk-0'), 'under its UUID');
+    $res = flow($fake, $ACT{activate});
+    is_deeply(ops($res), ['read target state'], 'which then is converged');
+};
+
+my $INVENTORY_TEXT = 'zfs get -H -p -d 1 -t filesystem,volume -o name,property,value,source'
+    . ' type,proxmox:nvme-subsys,proxmox:nvme-nsid,proxmox:nvme-uuid,proxmox:nvme-last-nsid tank';
+my $MARKER_TEXT = q{printf '%s\n' ZFSNVME-CONFIGFS};
+my $CONFIGFS_TEXT =
+    q{env 'LC_ALL=C' find /sys/kernel/config/nvmet}
+    . q{ '(' -path '/sys/kernel/config/nvmet/subsystems/*/passthru'}
+    . q{ -o -path '/sys/kernel/config/nvmet/ports/*/ana_groups'}
+    . q{ -o -path '/sys/kernel/config/nvmet/ports/*/referrals' ')' -type d -prune}
+    . q{ -o -type d -exec printf 'D %s\n' '{}' +}
+    . q{ -o -type l -exec printf 'L %s\n' '{}' +}
+    . q{ -o -type f '(' -name enable -o -name device_path -o -name device_uuid -o -name buffered_io}
+    . q{ -o -name attr_model -o -name attr_serial -o -name attr_allow_any_host}
+    . q{ -o -name addr_trtype -o -name addr_adrfam -o -name addr_traddr -o -name addr_trsvcid ')'}
+    . q{ -exec grep '' /dev/null '{}' +};
+my $CONFIGFS_KEYS_TEXT =
+    $CONFIGFS_TEXT
+    . q{ -o -type f '('}
+    . join(' -o', map { " -path $ROOT/hosts/$_/dhchap_key" } @HOSTS)
+    . q{ ')' -exec sha256sum '{}' +};
+my $STATE_TEXT = "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_TEXT";
+my $LOCKED_STATE_TEXT = "modprobe nvmet_tcp && $STATE_TEXT";
+
+sub w_text($path, $value) {
+    return "printf '%s\\n' $value > $path";
+}
+
+sub build_text($nsid, $uuid, $dev) {
+    my $ns = "$S/namespaces/$nsid";
+    return join(
+        ' && ',
+        "test -b $dev", "mkdir $ns",
+        w_text("$ns/device_path", $dev),
+        w_text("$ns/device_uuid", $uuid),
+        w_text("$ns/buffered_io", 0),
+        w_text("$ns/enable", 1),
+    );
+}
+
+sub rendered($res) {
+    return [map { $_->{rendered} } $res->{calls}->@*];
+}
+
+subtest 'golden commands' => sub {
+    my @H = map { "$ROOT/hosts/$_" } @HOSTS;
+    my $serial = 'PVEZFS' . substr(sha256_hex($NQN), 0, 14);
+    my $port = sub($id, $address) {
+        my $P = "$ROOT/ports/$id";
+        return join(
+            ' && ',
+            "mkdir $P",
+            w_text("$P/addr_trtype", 'tcp'),
+            w_text("$P/addr_adrfam", 'ipv4'),
+            w_text("$P/addr_traddr", $address),
+            w_text("$P/addr_trsvcid", 4420),
+        );
+    };
+    my $link = sub($id) {
+        return join(
+            ' && ',
+            "grep -qx 0 $S/attr_allow_any_host",
+            (map { "test -L $S/allowed_hosts/$_" } @HOSTS),
+            "ln -s $S $ROOT/ports/$id/subsystems/$NQN",
+        );
+    };
+
+    my $fake = FakeTarget->new(pools => ['tank']);
+    $fake->add_zvol('tank/vm-100-disk-0', identity => [$NQN, 1, $U{1}]);
+    is_deeply(
+        rendered(flow($fake, $ACT{activate})),
+        [
+            "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+            "modprobe nvmet_tcp && $INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+            join(
+                ' && ',
+                "mkdir $S",
+                w_text("$S/attr_model", q{'Proxmox ZFS NVMe'}),
+                w_text("$S/attr_serial", $serial),
+                w_text("$S/attr_allow_any_host", 0),
+                $port->(1, '192.0.2.21'),
+                $port->(2, '192.0.2.22'),
+                "mkdir $H[0]",
+                "mkdir $H[1]",
+                "chmod 0600 $H[0]/dhchap_key $H[0]/dhchap_ctrl_key $H[1]/dhchap_key"
+                    . " $H[1]/dhchap_ctrl_key",
+                "dd ibs=4096 obs=8192 2>/dev/null | tee $H[0]/dhchap_key $H[1]/dhchap_key"
+                    . ' >/dev/null',
+                "ln -s $H[0] $S/allowed_hosts/$HOSTS[0]",
+                "ln -s $H[1] $S/allowed_hosts/$HOSTS[1]",
+                build_text(1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+            ),
+            "$INVENTORY_TEXT && $MARKER_TEXT && $CONFIGFS_KEYS_TEXT",
+            $link->(1),
+            $link->(2),
+        ],
+        'read, configure with a key from stdin, verify and publish',
+    );
+    $fake = lifecycle_fake();
+    is_deeply(
+        rendered(flow($fake, sub { $PLUGIN->path(scfg(), 'vm-100-disk-0', 'st') })),
+        [$INVENTORY_TEXT],
+        'the ZFS inventory',
+    );
+    my $res = flow($fake, sub { $PLUGIN->alloc_image('st', scfg(), 200, 'raw', undef, 1024) });
+    my $uuid = $fake->{m}->{ds}->{'tank/vm-200-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+    is_deeply(
+        rendered($res),
+        [
+            'zfs list -o name,volsize,origin,type -t volume,filesystem -d1 -Hp tank',
+            $LOCKED_STATE_TEXT,
+            "zfs set 'proxmox:nvme-last-nsid=4' tank",
+            "zfs create -s -b 16k -o 'proxmox:nvme-subsys=$NQN' -o 'proxmox:nvme-nsid=4'"
+                . " -o 'proxmox:nvme-uuid=$uuid' -V 1024k tank/vm-200-disk-0",
+            'test -b /dev/zvol/tank/vm-200-disk-0',
+            build_text(4, $uuid, '/dev/zvol/tank/vm-200-disk-0'),
+            $STATE_TEXT,
+        ],
+        'read, reserve, create, wait, export and verify',
+    );
+    is_deeply(
+        rendered(flow(
+            $fake,
+            sub { $PLUGIN->volume_resize(scfg(), 'st', 'vm-200-disk-0', 2 * 1024**3, 0) },
+        )),
+        [
+            $LOCKED_STATE_TEXT,
+            "zfs set 'volsize=2097152k' tank/vm-200-disk-0 && "
+                . w_text("$S/namespaces/4/revalidate_size", 1),
+        ],
+        'read, then resize and revalidate',
+    );
+    is_deeply(
+        rendered(flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') })),
+        [
+            $LOCKED_STATE_TEXT,
+            join(
+                ' && ',
+                w_text("$S/namespaces/2/enable", 0),
+                "rmdir $S/namespaces/2",
+                'zfs destroy -r tank/vm-101-disk-0',
+            ),
+        ],
+        'unexport and destroy',
+    );
+    is_deeply(
+        rendered(flow(
+            $fake,
+            sub { $PLUGIN->volume_snapshot_rollback(scfg(), 'st', 'vm-100-disk-0', 'snap1') },
+        )),
+        [
+            $LOCKED_STATE_TEXT,
+            join(' && ',
+                w_text("$S/namespaces/1/enable", 0),
+                "rmdir $S/namespaces/1",
+                'zfs rollback tank/vm-100-disk-0@snap1',
+                "zfs set 'proxmox:nvme-subsys=$NQN' 'proxmox:nvme-nsid=1'"
+                    . " 'proxmox:nvme-uuid=$U{1}' tank/vm-100-disk-0"),
+            'test -b /dev/zvol/tank/vm-100-disk-0',
+            build_text(1, $U{1}, '/dev/zvol/tank/vm-100-disk-0'),
+        ],
+        'unexport, roll back, write the identity and export again',
+    );
+    is_deeply(
+        rendered(flow($fake, sub { $PLUGIN->create_base('st', scfg(), 'vm-100-disk-0') })),
+        [
+            $LOCKED_STATE_TEXT,
+            join(' && ',
+                w_text("$S/namespaces/1/enable", 0),
+                "rmdir $S/namespaces/1",
+                'zfs rename tank/vm-100-disk-0 tank/base-100-disk-0'),
+            'test -b /dev/zvol/tank/base-100-disk-0',
+            build_text(1, $U{1}, '/dev/zvol/tank/base-100-disk-0')
+                . ' && zfs snapshot tank/base-100-disk-0@__base__',
+        ],
+        'unexport, rename, export and snapshot',
+    );
+    $res = flow($fake, sub { $PLUGIN->clone_image(scfg(), 'st', 'base-102-disk-0', 201) });
+    $uuid = $fake->{m}->{ds}->{'tank/vm-201-disk-0'}->{props}->{'proxmox:nvme-uuid'};
+    is_deeply(
+        [map { $_->{rendered} } $res->{calls}->@[2, 3]],
+        [
+            "zfs set 'proxmox:nvme-last-nsid=5' tank",
+            "zfs clone -o 'proxmox:nvme-subsys=$NQN' -o 'proxmox:nvme-nsid=5'"
+                . " -o 'proxmox:nvme-uuid=$uuid' tank/base-102-disk-0\@__base__ tank/vm-201-disk-0",
+        ],
+        'reserve and clone',
+    );
+
+    $fake = lifecycle_fake(
+        step_fault => sub($s, $c) { step_is($s, 'rmdir', "$S/namespaces/2") ? 'busy' : undef },
+    );
+    $res = flow($fake, sub { $PLUGIN->free_image('st', scfg(), 'vm-101-disk-0') });
+    is(
+        $res->{calls}->[-1]->{rendered},
+        'test -b /dev/zvol/tank/vm-101-disk-0 && ' . w_text("$S/namespaces/2/enable", 1),
+        'enable again',
+    );
+
+    $fake = FakeTarget->new(pools => ['tank']);
+    $fake->{m}->{mounted} = 0;
+    $res = flow($fake, $ACT{activate});
+    ok(grep({ $_ eq 'cat /proc/mounts' } rendered($res)->@*), 'the mount table');
+    ok(
+        grep({ $_ eq 'mount -t configfs none /sys/kernel/config' } rendered($res)->@*),
+        'the mount',
+    );
+
+    $fake = target_fake();
+    $fake->add_port(5, '192.0.2.99', 4420, links => [$NQN]);
+    is(
+        rendered(flow($fake, $ACT{activate}))->[-1],
+        "rm $ROOT/ports/5/subsystems/$NQN",
+        'unlink',
+    );
+
+    $fake = lifecycle_fake();
+    $fake->{m}->{subsystems}->{$NQN}->{attr}->{attr_allow_any_host} = '1';
+    $fake->{m}->{subsystems}->{$NQN}->{acl} = {};
+    is(
+        rendered(flow($fake, $ACT{activate}))->[2],
+        join(
+            ' && ',
+            w_text("$S/attr_allow_any_host", 0),
+            map { "ln -s $ROOT/hosts/$_ $S/allowed_hosts/$_" } @HOSTS,
+        ),
+        'allow_any_host before the ACLs',
+    );
+
+    $fake = lifecycle_fake();
+    my @generic = (
+        [sub { [$PLUGIN->status('st', scfg())] }, 'zfs get -o value -Hp available,used tank'],
+        [
+            sub { $PLUGIN->volume_snapshot_info(scfg(), 'st', 'vm-100-disk-0') },
+            'zfs list -Hp -r -t snapshot -o name,guid,creation tank/vm-100-disk-0',
+        ],
+        [
+            sub { $PLUGIN->volume_rollback_is_possible(scfg(), 'st', 'vm-100-disk-0', 'snap1') }
+            ,
+            'zfs list -H -r -t snapshot -o name -s creation tank/vm-100-disk-0',
+        ],
+        [
+            sub { [$PLUGIN->volume_size_info(scfg(), 'st', 'vm-100-disk-0')] },
+            'zfs get -o value -Hp volsize,usedbydataset tank/vm-100-disk-0',
+        ],
+        [
+            sub { $PLUGIN->volume_snapshot(scfg(), 'st', 'vm-100-disk-0', 'snap2') },
+            'zfs snapshot tank/vm-100-disk-0@snap2',
+        ],
+        [
+            sub { $PLUGIN->volume_snapshot_delete(scfg(), 'st', 'vm-100-disk-0', 'snap2') },
+            'zfs destroy tank/vm-100-disk-0@snap2',
+        ],
+    );
+
+    for my $case (@generic) {
+        is(rendered(flow($fake, $case->[0]))->[0], $case->[1], $case->[1]);
+    }
+    is(
+        rendered(flow($fake, sub { $PLUGIN->list_images('st', scfg()) }))->[1],
+        'zfs get -H -d 1 -o name,value,source proxmox:nvme-subsys tank',
+        'the ownership query',
+    );
+};
+
+sub sh($command, $input = undef) {
+    my $err = gensym;
+    my $pid = open3(my $in, my $out, $err, '/bin/sh', '-c', $command);
+    print {$in} $input if defined($input);
+    close($in);
+    my $stdout = do { local $/; <$out> }
+        // '';
+    my $stderr = do { local $/; <$err> }
+        // '';
+    waitpid($pid, 0) == $pid or die "wait for test shell: $!\n";
+    my $status = $?;
+    return ($status & 127 ? 128 + ($status & 127) : $status >> 8, $stdout, $stderr);
+}
+
+# The subtests that run rendered commands need these tools. A Debian build
+# has them, so a missing one is an error, never a silently skipped test.
+{
+    my @tools = qw(find grep sha256sum dd tee);
+    BAIL_OUT('needs /bin/sh with ' . join(', ', @tools))
+        if !-x '/bin/sh' || (sh('command -v ' . join(' ', @tools)))[0] != 0;
+}
+
+subtest 'quoting' => sub {
+    my $dir = tempdir(CLEANUP => 1);
+    for my $value (
+        'a b',
+        q{it's},
+        "\$(touch $dir/pwned)",
+        "`touch $dir/pwned`",
+        '-n',
+        '*',
+        '%s\n',
+        q{"x"},
+        'x;y',
+        'a && b',
+        '|',
+        '~root',
+        "tab\there",
+        '',
+        '$HOME',
+        'a\\b',
+        '#c',
+    ) {
+        my $file = "$dir/value";
+        my ($rc) = sh(nv('_nvmet_render', [write_step($file, $value)]));
+        is($rc . slurp($file), "0$value\n", 'a write keeps ' . ($value =~ s/\t/\\t/r));
+        my (undef, $out) = sh(nv('_nvmet_render', [['printf', '%s\n', $value]]));
+        is($out, "$value\n", 'an argument keeps ' . ($value =~ s/\t/\\t/r));
+    }
+    ok(!-e "$dir/pwned", 'no value is executed');
+};
+
+subtest 'renderer rejections' => sub {
+    for my $case (
+        ['a newline in a value', [write_step("$S/x", "a\nb")]],
+        ['a NUL in a value', [write_step("$S/x", "a\0b")]],
+        ['a CR in an argument', [['zfs', 'get', "a\rb"]]],
+        ['an undefined argument', [['zfs', 'get', undef]]],
+        ['an undefined value', [write_step("$S/x", undef)]],
+        ['a reference as argument', [['zfs', 'get', []]]],
+        ['a relative write', [write_step('x', 1)]],
+        ['a relative key path', [{ key => ['x'] }]],
+        ['an empty key step', [{ key => [] }]],
+        ['two key steps', [{ key => ['/a'] }, { key => ['/b'] }]],
+        ['bash', [['bash', '-c', 'true']]],
+        ['sh', [['sh', '-c', 'true']]],
+        ['perl', [['perl', '-e', '1']]],
+        ['an absolute command', [['/bin/rm', '/a']]],
+        ['an empty command', [[]]],
+        ['a write with extra keys', [{ write => '/a', value => 1, mode => 1 }]],
+        ['an unknown step', [{ run => '/a' }]],
+        ['a string step', ['mkdir /a']],
+        ['no steps', []],
+        ['a string', 'mkdir /a'],
+    ) {
+        eval { nv('_nvmet_render', $case->[1]) };
+        is($@, "internal error: invalid NVMe target step\n", "rejects $case->[0]");
+    }
+};
+
+subtest 'the rendered chains on a configfs stand-in' => sub {
+    my $dir = tempdir(CLEANUP => 1);
+    my $root = "$dir/nvmet";
+    mkdir($_) or die "mkdir $_: $!\n" for $root, map { "$root/$_" } qw(hosts ports subsystems);
+    my $device = "$dir/device";
+    symlink('/dev/null', $device) or die "symlink: $!\n";
+    my $box = sub($path) { $path =~ s{\A\Q$ROOT\E(?=/|\z)}{$root}r };
+    my $kind = sub($path) {
+        my $rel = substr($path, length($root) + 1);
+        return 'subsystem' if $rel =~ m{\Asubsystems/[^/]+\z};
+        return 'namespace' if $rel =~ m{\Asubsystems/[^/]+/namespaces/[0-9]+\z};
+        return 'port' if $rel =~ m{\Aports/[0-9]+\z};
+        return 'host' if $rel =~ m{\Ahosts/[^/]+\z};
+        die "unexpected directory $path\n";
+    };
+    my %attrs = (
+        subsystem => {
+            attr_model => 'Linux',
+            attr_serial => '0123456789abcdef',
+            attr_allow_any_host => 0,
+        },
+        namespace => {
+            enable => 0,
+            device_path => '(null)',
+            device_uuid => $U{9},
+            buffered_io => 0,
+        },
+        port => { addr_trtype => '', addr_adrfam => '', addr_traddr => '', addr_trsvcid => '' },
+        host => { dhchap_key => '', dhchap_ctrl_key => '' },
+    );
+    my %groups = (subsystem => ['namespaces', 'allowed_hosts'], port => ['subsystems']);
+    # configfs creates attributes and default groups with each directory and removes them with
+    # it, and the stand-in does both with the same commands.
+    my $shim = sub($steps) {
+        my @out;
+        for my $step ($steps->@*) {
+            if (ref($step) eq 'HASH' && exists($step->{write})) {
+                push @out, write_step($box->($step->{write}), $step->{value});
+            } elsif (ref($step) eq 'HASH') {
+                push @out, { key => [map { $box->($_) } $step->{key}->@*] };
+            } elsif ($step->[0] eq 'test' && $step->[1] eq '-b') {
+                push @out, ['test', '-L', $device];
+            } elsif ($step->[0] eq 'mkdir') {
+                for my $path (map { $box->($_) } $step->@[1 .. $step->$#*]) {
+                    my $type = $kind->($path);
+                    push @out, ['mkdir', $path, map { "$path/$_" } ($groups{$type} // [])->@*];
+                    push @out, map { write_step("$path/$_", $attrs{$type}->{$_}) }
+                        sort keys $attrs{$type}->%*;
+                }
+            } elsif ($step->[0] eq 'rmdir') {
+                for my $path (map { $box->($_) } $step->@[1 .. $step->$#*]) {
+                    my $type = $kind->($path);
+                    push @out, ['rm', map { "$path/$_" } sort keys $attrs{$type}->%*];
+                    push @out, ['rmdir', map { "$path/$_" } $groups{$type}->@*]
+                        if $groups{$type};
+                    push @out, ['rmdir', $path];
+                }
+            } else {
+                push @out, [map { $box->($_) } $step->@*];
+            }
+        }
+        return \@out;
+    };
+    my $run = sub($steps, $input = undef) {
+        my ($rc, undef, $err) = sh(nv('_nvmet_render', $shim->($steps)), $input);
+        return ($rc, $err);
+    };
+
+    my $capture = FakeTarget->new(pools => ['tank']);
+    flow($capture, $ACT{activate});
+    my ($find) = grep { step_is($_, 'env') } $capture->{calls}->[0]->{steps}->@*;
+    my $read = sub () {
+        my ($rc, $out, $err) = sh(nv('_nvmet_render', $shim->([$find])));
+        die "configfs read failed: $err\n" if $rc;
+        $out =~ s{\Q$root\E}{$ROOT}g;
+        return nv('_nvmet_parse_configfs', $out);
+    };
+    my $inv = inventory(@POOL, @ONE);
+    my $conf = { nqn => $NQN, portals => $PORTALS, hostnqns => [@HOSTS], keysha => $KEY_SHA };
+    my $plan = nv('_nvmet_plan_activation', $inv, $read->(), $conf);
+    my ($rc, $err) = $run->([map { $_->@* } $plan->{prepublish}->@*], "$KEY\n");
+    is($rc, 0, 'the whole configuration runs as one chain') or diag($err);
+    my $cfs = $read->();
+    is_deeply(
+        nv('_nvmet_plan_activation', $inv, $cfs, $conf)->{prepublish},
+        [],
+        'and converges',
+    );
+    is_deeply(
+        [map { $cfs->{hosts}->{$_}->{key_sha256} } @HOSTS],
+        [$KEY_SHA, $KEY_SHA],
+        'the digests read back equal sha256 of the key and a newline',
+    );
+    is_deeply(
+        [map { (stat("$root/hosts/$_/dhchap_key"))[2] & 07777 } @HOSTS],
+        [0600, 0600],
+        'and the key attributes are readable by their owner only',
+    );
+
+    # Only the kernel's own groups are skipped: the ACL of another tool's
+    # subsystem named like one of them is read and protects the key.
+    my $other = "$root/subsystems/referrals";
+    mkdir($_) or die "mkdir $_: $!\n" for $other, "$other/allowed_hosts", "$other/namespaces";
+    for my $attr (keys $attrs{subsystem}->%*) {
+        open(my $fh, '>', "$other/$attr") or die "open: $!\n";
+        print {$fh} "$attrs{subsystem}->{$attr}\n";
+        close($fh);
+    }
+    symlink("$root/hosts/$HOSTS[0]", "$other/allowed_hosts/$HOSTS[0]") or die "symlink: $!\n";
+    mkdir($_)
+        or die "mkdir $_: $!\n"
+        for "$root/ports/1/referrals", "$root/ports/1/referrals/r";
+    my (undef, $raw) = sh(nv('_nvmet_render', $shim->([$find])));
+    ok(
+        $read->()->{subsystems}->{referrals}->{acl}->{ $HOSTS[0] },
+        'a subsystem named referrals',
+    );
+    unlike($raw, qr{/ports/1/referrals}, 'while the referrals of a port are skipped');
+    unlink("$other/allowed_hosts/$HOSTS[0]", map { "$other/$_" } keys $attrs{subsystem}->%*);
+    rmdir($_)
+        or die "rmdir $_: $!\n"
+        for "$other/allowed_hosts", "$other/namespaces", $other, "$root/ports/1/referrals/r",
+        "$root/ports/1/referrals";
+
+    for my $unit (nv('_nvmet_plan_publish', $cfs, $NQN, $plan->{port_ids}, [@HOSTS])->@*) {
+        ($rc) = $run->($unit->{steps});
+        is($rc, 0, "the guarded link to port $unit->{port}");
+    }
+    is_deeply(nv('_nvmet_plan_publish', $read->(), $NQN, [1, 2], [@HOSTS]), [], 'publishes');
+
+    unlink("$root/ports/1/subsystems/$NQN", "$root/subsystems/$NQN/allowed_hosts/$HOSTS[1]");
+    my ($unit) = nv('_nvmet_plan_publish', $read->(), $NQN, [1], [@HOSTS])->@*;
+    ($rc) = $run->($unit->{steps});
+    ok($rc && !-l "$root/ports/1/subsystems/$NQN", 'the guard blocks a link without every ACL');
+    symlink("$root/hosts/$HOSTS[1]", "$root/subsystems/$NQN/allowed_hosts/$HOSTS[1]") or die;
+    ($rc) = $run->([write_step("$ROOT/subsystems/$NQN/attr_allow_any_host", 1)]);
+    ($rc) = $run->($unit->{steps});
+    ok($rc && !-l "$root/ports/1/subsystems/$NQN", 'and while any host may connect');
+    $run->([write_step("$ROOT/subsystems/$NQN/attr_allow_any_host", 0)]);
+    ($rc) = $run->($unit->{steps});
+    ok(!$rc && -l "$root/ports/1/subsystems/$NQN", 'but links once both hold');
+
+    my ($units) = nv('_nvmet_plan_unexport', $read->(), $NQN, $U{1});
+    ($rc) = $run->([map { $_->@* } $units->@*]);
+    ok(!$rc && !-e "$root/subsystems/$NQN/namespaces/1", 'the unexport chain removes it');
+};
+
+# Last: every command rendered during this test run, and every protocol violation recorded (by a
+# fake target: a key on a command line or in output, a change without the lock, or a local command).
+subtest 'every rendered command is a POSIX command chain' => sub {
+    is_deeply(\@VIOLATIONS, [], 'no flow violated the target protocol');
+    my %shapes;
+    for my $command (keys %CORPUS) {
+        (my $shape = $command) =~ s/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/U/gi;
+        $shape =~ s/[0-9]+/N/g;
+        $shapes{$shape} //= $command;
+    }
+    ok(keys(%shapes) >= 40, 'the corpus covers ' . keys(%shapes) . ' command shapes');
+    my $meta = qr/[;&|<>`\$(){}\\*?\[\]~#!"]/;
+    my @bad;
+    for my $command (sort values %shapes) {
+        push @bad, "sh -n: $command" if system('/bin/sh', '-n', '-c', $command) != 0;
+        push @bad, "bash-ism: $command"
+            if $command =~ /\[\[|\$\(\(|<<<|\$'|pipefail|(?:\A|&& )(?:function|source|\.) /;
+        (my $bare = $command) =~ s/'[^']*'|\\'//g;
+        for my $segment (split / && /, $bare) {
+            next
+                if $segment =~ m{\Add\ ibs=4096\ obs=8192\ 2>/dev/null\ \|\ tee(?:\ /[^\s;&|<>]+)+
+                    \ >/dev/null\z}x;
+            if ($segment =~ /\Aprintf +(\S*) +> (\S+)\z/) {
+                push @bad, "write: $segment" if "$1$2" =~ $meta;
+                next;
+            }
+            push @bad, "shell syntax: $segment" if $segment =~ $meta;
+        }
+    }
+    is_deeply(\@bad, [], 'every command is a plain POSIX command chain');
+};
+
 done_testing();
-- 
2.54.0.windows.1




  parent reply	other threads:[~2026-11-26 15:13 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26 15:09 [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 02/13] zfsnvme: add the target transactions Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 05/13] api: san luns: count zfsnvme storages as owners of their subsystem Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 06/13] api: config: check the cluster version before the first zfsnvme storage Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 08/13] test: zfsnvme: add node side tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 10/13] test: zfsnvme: test the target parsers and planners Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 11/13] test: zfsnvme: test the target flows Joaquin Varela
2026-11-26 15:09 ` Joaquin Varela [this message]
2026-11-26 15:09 ` [PATCH storage v5 13/13] zfsnvme: wait up to 30 seconds for the shared storage lock Joaquin Varela
2026-11-26 15:10 ` [PATCH docs v5] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-11-26 15:11 ` [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela

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=20261126150956.310593-13-joaquinvarela@neatech.ar \
    --to=joaquinvarela@neatech.ar \
    --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