From 0f2f1cfd05970a3debf5914b97b5a269622ca27a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Ferr=C3=A3o?= <2031761+viniciusferrao@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:17:44 -0300 Subject: [PATCH] test(uftp): cover the UFTP transfer listener and its package removal The listener must send the requests for one archive with one sender. It must refuse paths outside the image roots, archives without a checksum, and digests that the checksum file does not list. A queued batch must keep its archive after the next publication. The limits on connections, queued jobs, senders, receivers and time must hold. Package removal must stop and disable the service, and an upgrade must leave it alone. The unit test calls the listener subs of xCAT::UFTP in process, with a fixed clock and a sender start that it records. native/uftp_listener.t runs the listener script with uftp and uftp_keymgt fixtures. It covers key creation, a read-only log directory, sender processes, shutdown and connection limits. The pull-request workflow runs it. --- .github/workflows/xcat_test.yml | 3 + xCAT-test/bats/uftp_listener_removal.bats | 63 ++++ xCAT-test/native/README.md | 16 + xCAT-test/native/uftp_listener.t | 387 ++++++++++++++++++++++ xCAT-test/unit/uftp_listener.t | 359 ++++++++++++++++++++ 5 files changed, 828 insertions(+) create mode 100644 xCAT-test/bats/uftp_listener_removal.bats create mode 100644 xCAT-test/native/uftp_listener.t create mode 100644 xCAT-test/unit/uftp_listener.t diff --git a/.github/workflows/xcat_test.yml b/.github/workflows/xcat_test.yml index da6e641b74..055cb8b05f 100644 --- a/.github/workflows/xcat_test.yml +++ b/.github/workflows/xcat_test.yml @@ -55,6 +55,9 @@ jobs: - name: Exercise the liteimg ramdisk archive if: ${{ !cancelled() }} run: prove xCAT-test/native/liteimg_ramdisk_archive.t + - name: Exercise the UFTP listener + if: ${{ !cancelled() }} + run: prove xCAT-test/native/uftp_listener.t - name: Run tests if: ${{ !cancelled() }} run: perl github_action_xcat_test.pl diff --git a/xCAT-test/bats/uftp_listener_removal.bats b/xCAT-test/bats/uftp_listener_removal.bats new file mode 100644 index 0000000000..dc988570f0 --- /dev/null +++ b/xCAT-test/bats/uftp_listener_removal.bats @@ -0,0 +1,63 @@ +#!/usr/bin/env bats + +load 'helpers/shell_source' + +setup() +{ + [ "$(uname -s)" = Linux ] || skip 'package scriptlets run in a Linux sandbox' + bwrap=$(PATH=/usr/bin:/bin type -P bwrap) || { + echo 'Install bubblewrap to run the package removal test' >&2 + return 1 + } + fixture="$BATS_TEST_TMPDIR/fixture" + mkdir -p "$fixture/bin" "$fixture/opt/xcat/share/xcat/scripts" + cat >"$fixture/bin/systemctl" <<'SH' +#!/bin/sh +printf '%s\n' "$*" >>/tmp/fixture/systemctl.log +SH + cat >"$fixture/opt/xcat/share/xcat/scripts/xcatd-init-compat" <<'SH' +#!/bin/sh +printf '%s\n' "$*" >>/tmp/fixture/compat.log +exit 0 +SH + chmod +x "$fixture/bin/systemctl" "$fixture/opt/xcat/share/xcat/scripts/xcatd-init-compat" + awk '/^%preun$/ { copy = 1; next } copy && !/^%/' "$(repo_path xCAT-server/xCAT-server.spec)" >"$fixture/preun" + [ -s "$fixture/preun" ] + sandbox=("$bwrap" --unshare-all --die-with-parent --new-session + --ro-bind / / --tmpfs /tmp --tmpfs /opt --tmpfs /usr/sbin --proc /proc --dev /dev + --bind "$fixture" /tmp/fixture --bind "$fixture/opt/xcat" /opt/xcat + --ro-bind "$(repo_path xCAT-server/debian/prerm)" /tmp/prerm + --setenv PATH /tmp/fixture/bin:/usr/bin:/bin --setenv RPM_INSTALL_PREFIX0 /opt/xcat) +} + +@test 'RPM erase stops and disables the UFTP listener' { + run "${sandbox[@]}" /bin/bash /tmp/fixture/preun 0 + [ "$status" -eq 0 ] + grep -qx 'stop xcatd.service' "$fixture/systemctl.log" + grep -qx 'disable --now xcat-uftp-listener.service' "$fixture/systemctl.log" +} + +@test 'RPM upgrade leaves the UFTP listener alone' { + run "${sandbox[@]}" /bin/bash /tmp/fixture/preun 1 + [ "$status" -eq 0 ] + if grep -q uftp "$fixture/systemctl.log" 2>/dev/null; then + echo 'an upgrade touched the listener' + return 1 + fi +} + +@test 'Debian removal stops and disables the UFTP listener' { + run "${sandbox[@]}" /bin/sh /tmp/prerm remove + [ "$status" -eq 0 ] + grep -qx 'stop xcatd.service' "$fixture/systemctl.log" + grep -qx 'disable --now xcat-uftp-listener.service' "$fixture/systemctl.log" +} + +@test 'Debian upgrade leaves the UFTP listener alone' { + run "${sandbox[@]}" /bin/sh /tmp/prerm upgrade 2.19.1 + [ "$status" -eq 0 ] + if grep -q uftp "$fixture/systemctl.log" 2>/dev/null; then + echo 'an upgrade touched the listener' + return 1 + fi +} diff --git a/xCAT-test/native/README.md b/xCAT-test/native/README.md index 3fe5ac7738..b60f596125 100644 --- a/xCAT-test/native/README.md +++ b/xCAT-test/native/README.md @@ -144,6 +144,22 @@ Compressor and ctorrent fixtures record what nodes can download during the pack, or fail on request. The image lock and the ilitefile query are test doubles. This case does not boot the image. +The pull-request workflow runs the UFTP listener case explicitly. It starts the +checkout's `xcat-uftp-listener` on loopback addresses and sends it requests +over TCP. It needs Bubblewrap with unprivileged user namespaces, GNU timeout, +the loopback address 127.0.0.2, and the Perl modules of the unit suite, +including DBD::SQLite and Capture::Tiny. Run it as an ordinary user: + +``` +prove xCAT-test/native/uftp_listener.t +``` + +Fixtures replace `uftp` and `uftp_keymgt`. The `uftp` fixture records its +arguments, its host list and the bytes it reads from descriptor 3, or exits +or blocks on request. The case checks key creation, the runtime check on a +read-only log directory, sender processes, timeouts, shutdown and connection +limits. It does not send multicast or boot a node. + The disk, kdump, sudoer and remoteshell cases require bats-core 1.4 or newer, Bubblewrap, GNU timeout, diffutils, Capture::Tiny, File::Slurper and sudo's `visudo`. The remoteshell case also needs `/usr/bin/openssl` and `ssh-keygen` diff --git a/xCAT-test/native/uftp_listener.t b/xCAT-test/native/uftp_listener.t new file mode 100644 index 0000000000..55c10f8f3b --- /dev/null +++ b/xCAT-test/native/uftp_listener.t @@ -0,0 +1,387 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use FindBin; +use lib "$FindBin::Bin/../lib"; +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use Cwd qw(realpath); +use Digest::SHA qw(sha256_hex); +use File::Path qw(make_path); +use File::Slurper qw(read_binary write_binary); +use File::Temp qw(tempdir); +use IO::Select; +use IO::Socket::INET; +use POSIX qw(WNOHANG); +use Test::More; +use Time::HiRes qw(sleep time); +use XCAT::Test::File qw(repo_path); +use XCAT::Test::Process qw(run_command); +use xCAT::SvrUtils; + +plan skip_all => 'the UFTP listener test binds loopback addresses and uses Linux namespaces' unless $^O eq 'linux'; +my ($bwrap) = grep { -x $_ } qw(/usr/bin/bwrap /bin/bwrap); +die "The UFTP listener test requires bubblewrap\n" unless $bwrap; +die "The UFTP listener test requires GNU timeout\n" unless grep { -x $_ } qw(/usr/bin/timeout /bin/timeout); +my $probe_client = IO::Socket::INET->new(LocalAddr => '127.0.0.2', LocalPort => 0, Proto => 'tcp') + or die "The UFTP listener test cannot bind 127.0.0.2: $!\n"; +close($probe_client); + +my $listener = repo_path('xCAT-server/sbin/xcat-uftp-listener'); +my $modules = repo_path('xCAT-server/lib/perl'); +my $tmp = realpath(tempdir(CLEANUP => 1)); +my $calls = "$tmp/calls"; +my $root = "$tmp/install/netboot"; +my $fp = '31:94:09:9D:B1:24:3F:32:C0:B9:1A:BB:AC:F4:74:2B:80:F9:77:B2'; +make_path($calls, $root, "$tmp/xcatroot/lib/perl", "$tmp/log"); +local $ENV{XCATROOT} = "$tmp/xcatroot"; +local $ENV{FAKE_UFTP_DIR} = $calls; + +# The sender fixture records its arguments, its host list and the bytes of /dev/fd/3. +write_binary("$tmp/fake-uftp", <<'EOF'); +#!/usr/bin/env perl +# The listener looks for: UFTP version 5.0.4 (xCAT build 1) +use strict; +use warnings; +my $dir = $ENV{FAKE_UFTP_DIR}; +my @args = @ARGV; +my %value; +for (my $i = 0; $i < $#args; $i++) { + $value{ $args[$i] } = $args[ $i + 1 ] if $args[$i] =~ /^-[A-Za-z]$/; +} +open(my $argv, '>', "$dir/$$.argv") or die; +print {$argv} join("\n", @args), "\n"; +close($argv); +if (($value{'-H'} // '') =~ /^\@(.+)$/ && open(my $hosts, '<', $1)) { + local $/; + my $list = <$hosts>; + open(my $copy, '>', "$dir/$$.hosts") or die; + print {$copy} $list; + close($copy); +} +open(my $image, '<:raw', $args[-1]) or exit 66; +my $bytes = do { local $/; <$image> }; +open(my $out, '>:raw', "$dir/$$.bytes") or die; +print {$out} $bytes; +close($out); +my $mode = 'exit:0'; +if (open(my $control, '<', "$dir/mode")) { + $mode = <$control>; + chomp($mode); +} +exit $1 if $mode =~ /^exit:(\d+)$/; +if ($mode =~ /^block:(\d+)$/) { + sleep $1; + exit 0; +} +exit 0; +EOF +write_binary("$tmp/fake-keymgt", <<"EOF"); +#!/bin/sh +if [ "\$1" = -g ]; then + printf 'fixture private key\\n' > "\$3" + exit 0 +fi +[ -r "\$1" ] || exit 1 +printf '%s: ECDSA, curve prime256v1, fingerprint: $fp\\n' "\$1" >&2 +EOF +chmod(0755, "$tmp/fake-uftp", "$tmp/fake-keymgt"); + +# packimage publishes the archive with its checksum, and the listener sends only such an archive. +sub publish { + my ($dir, $content) = @_; + make_path($dir); + chmod(0755, $dir); + my ($stage, $error) = xCAT::SvrUtils->rootimg_stage($dir); + die $error unless $stage; + write_binary("$stage/rootimg.cpio.gz", $content); + chmod(0644, "$stage/rootimg.cpio.gz"); + $error = xCAT::SvrUtils->write_rootimg_checksum("$stage/rootimg.cpio.gz") + // xCAT::SvrUtils->publish_rootimg("$stage/rootimg.cpio.gz", "$dir/rootimg.cpio.gz"); + die $error if $error; + return sha256_hex($content); +} + +sub free_port { + my $probe = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 0, Proto => 'tcp', Listen => 1) + or die "probe: $!"; + my $port = $probe->sockport(); + close($probe); + return $port; +} + +my $config_seq = 0; +sub config { + my (%override) = @_; + my %settings = ( + listen_address => '127.0.0.1', + listen_port => free_port(), + image_roots => $root, + batch_delay => 1, + transfer_timeout => 30, + request_timeout => 2, + key_file => "$tmp/server.key", + fingerprint_file => "$tmp/server.fingerprint", + uftp => "$tmp/fake-uftp", + uftp_keymgt => "$tmp/fake-keymgt", + log_dir => "$tmp/log", + %override, + ); + my $path = "$tmp/listener." . ++$config_seq . '.conf'; + write_binary($path, join('', map { "$_ = $settings{$_}\n" } sort keys %settings)); + return ($path, $settings{listen_port}); +} + +sub run_listener { + my ($config, @args) = @_; + return run_command('timeout', '20', $^X, "-I$modules", $listener, '--config', $config, @args); +} + +my %running; +sub start_listener { + my ($config) = @_; + my $log = "$tmp/listener.$config_seq.log"; + my $pid = fork(); + die "fork: $!" unless defined($pid); + if ($pid == 0) { + open(STDOUT, '>', $log) or die; + open(STDERR, '>&', \*STDOUT) or die; + exec($^X, "-I$modules", $listener, '--config', $config) or die; + } + $running{$pid} = 1; + return ($pid, $log); +} + +sub stop_listener { + my ($pid) = @_; + delete $running{$pid}; + kill('TERM', $pid); + my $deadline = time() + 15; + while (time() < $deadline) { + return $? if waitpid($pid, WNOHANG) == $pid; + sleep(0.1); + } + kill('KILL', $pid); + waitpid($pid, 0); + return -1; +} + +END { + for my $pid (keys %running) { + kill('KILL', $pid); + waitpid($pid, 0); + } +} + +sub http { + my ($port, $raw, $client) = @_; + my $sock = IO::Socket::INET->new( + PeerAddr => '127.0.0.1', + PeerPort => $port, + LocalAddr => $client || '127.0.0.2', + Proto => 'tcp', + Timeout => 5, + ) or return { code => 0, error => "$!" }; + print {$sock} $raw; + my $response = ''; + my $select = IO::Select->new($sock); + while ($select->can_read(5)) { + last unless sysread($sock, my $chunk, 4096); + $response .= $chunk; + } + close($sock); + my ($head, $body) = split /\r\n\r\n/, $response, 2; + my ($status) = ($head // '') =~ m{^HTTP/1\.0 (\d{3}) }; + my %record = map { split /=/, $_, 2 } grep { /=/ } split /\n/, $body // ''; + return { %record, code => $status // 0 }; +} + +sub request { + my ($port, $digest, $path, $client) = @_; + return http($port, "GET /xcat-uftp/v1/transfer/$digest$path HTTP/1.0\r\nHost: test\r\n\r\n", $client); +} + +sub job_state { + my ($port, $job, $client) = @_; + return http($port, "GET /xcat-uftp/v1/job/$job HTTP/1.0\r\n\r\n", $client); +} + +sub wait_state { + my ($port, $job, $client, @states) = @_; + my %want = map { $_ => 1 } @states; + my $deadline = time() + 20; + my $state; + while (time() < $deadline) { + $state = job_state($port, $job, $client); + return $state if $want{ $state->{state} // '' }; + sleep(0.2); + } + return $state; +} + +sub wait_port { + my ($port) = @_; + my $deadline = time() + 10; + while (time() < $deadline) { + my $sock = IO::Socket::INET->new(PeerAddr => '127.0.0.1', PeerPort => $port, Proto => 'tcp'); + if ($sock) { + close($sock); + return 1; + } + sleep(0.1); + } + return 0; +} + +sub first_request { + my ($port, @args) = @_; + my $deadline = time() + 10; + my $reply; + while (time() < $deadline) { + $reply = request($port, @args); + return $reply if $reply->{code}; + sleep(0.05); + } + return $reply; +} + +sub sender_calls { + opendir(my $dh, $calls) or return (); + my @pids = sort { $a <=> $b } map { /^(\d+)\.argv$/ ? $1 : () } readdir($dh); + closedir($dh); + return map { + my $pid = $_; + { pid => $pid, argv => [ split /\n/, read_binary("$calls/$pid.argv") ], + hosts => -e "$calls/$pid.hosts" ? read_binary("$calls/$pid.hosts") : '', + bytes => -e "$calls/$pid.bytes" ? read_binary("$calls/$pid.bytes") : undef } + } @pids; +} + +sub wait_call { + my ($hosts) = @_; + my $deadline = time() + 10; + while (time() < $deadline) { + my ($call) = grep { $_->{hosts} eq $hosts && defined($_->{bytes}) } sender_calls(); + return $call if $call; + sleep(0.1); + } + return undef; +} + +sub reset_calls { + unlink(glob("$calls/*")); +} + +sub mode { + write_binary("$calls/mode", "$_[0]\n"); +} + +my ($check_config) = config(); +my ($rc, $out) = run_listener($check_config, '--check'); +is($rc, 1, 'the listener refuses to start without a server key'); +like($out, qr/run xcat-uftp-listener --init-key/, 'the missing key error says how to create it'); +($rc, $out) = run_listener($check_config, '--init-key'); +is($rc, 0, 'the server key is created') or diag($out); +is((stat("$tmp/server.key"))[2] & 07777, 0600, 'the server key is readable only by its owner'); +is(scalar(read_binary("$tmp/server.fingerprint")), "$fp\n", 'the fingerprint that uftp_keymgt reports is published for nodeset'); +($rc, $out) = run_listener($check_config, '--check'); +is($rc, 0, 'the configuration check passes') or diag($out); +like($out, qr/server key fingerprint \Q$fp\E/, 'the check reports the fingerprint of the server key'); + +# The service sandbox mounts every path except its LogsDirectory read-only, and the listener runs as root. +make_path("$tmp/readonly-log"); +my ($readonly_config) = config(log_dir => "$tmp/readonly-log"); +($rc, $out) = run_command('timeout', '20', $bwrap, '--dev-bind', '/', '/', '--ro-bind', "$tmp/readonly-log", "$tmp/readonly-log", + '--unshare-user', '--uid', '0', '--gid', '0', '--', $^X, "-I$modules", $listener, '--config', $readonly_config, '--check'); +isnt($rc, 0, 'the check fails as root when log_dir is on a read-only mount'); +like($out, qr/Cannot write to \Q$tmp\E\/readonly-log: Read-only file system/, 'the check names the log directory and the reason'); + +my $image_a = "$root/rhels9/x86_64/compute"; +my $content_a = "image A generation 1\n" x 200; +my $sum_a = publish($image_a, $content_a); +my $path_a = "$image_a/rootimg.cpio.gz"; + +my ($main_config, $port) = config(batch_delay => 2); +my ($pid, $main_log) = start_listener($main_config); +my $first = first_request($port, $sum_a, $path_a, '127.0.0.2'); +is($first->{code}, 200, 'the first connection after startup is answered as a transfer request'); +is($first->{client_ip}, '127.0.0.2', 'the reply gives the address of the connection'); +($rc, $out) = run_listener($main_config); +is($rc, 1, 'a second listener on an occupied port exits with an error'); +like($out, qr/Cannot listen on 127\.0\.0\.1:$port: Address already in use/, 'the occupied port is reported'); +is(request($port, $sum_a, $path_a, '127.0.0.3')->{job}, $first->{job}, 'a request from another node joins the job'); + +my $done = wait_state($port, $first->{job}, '127.0.0.2', 'done', 'failed'); +is($done->{state}, 'done', 'the job completes when its sender exits'); +my @sent = sender_calls(); +is(scalar(@sent), 1, 'one sender serves the job'); +is($sent[0]{hosts}, "127.0.0.2\n127.0.0.3\n", 'the sender reads the host list of the job'); +is($sent[0]{bytes}, $content_a, 'the sender reads the published bytes from its inherited descriptor'); +is_deeply([ @{ $sent[0]{argv} }[ -3 .. -1 ] ], [ '-D', 'rootimg.cpio.gz', '/dev/fd/3' ], 'the sender reads the image from descriptor 3'); +like(scalar(read_binary("$tmp/log/job-$first->{job}.log")), qr/^starting: \Q$tmp\E\/fake-uftp /m, 'the job log records the sender command'); +like(scalar(read_binary($main_log)), qr/job \Q$first->{job}\E: done$/m, 'the listener log reports the finished job'); +reset_calls(); + +mode('exit:7'); +my $failing = request($port, $sum_a, $path_a, '127.0.0.5'); +my $failed = wait_state($port, $failing->{job}, '127.0.0.5', 'failed', 'done'); +is($failed->{state}, 'failed', 'a sender failure fails the job'); +is($failed->{reason}, 'uftp exited with status 7', 'the job reports the exit status of the sender'); +mode('exit:0'); +reset_calls(); + +my $idle = IO::Socket::INET->new(PeerAddr => '127.0.0.1', PeerPort => $port, LocalAddr => '127.0.0.2', Proto => 'tcp'); +my $idle_started = time(); +my $idle_read = sysread($idle, my $nothing, 10); +ok(defined($idle_read) && $idle_read == 0 && time() - $idle_started < 6, 'an idle connection is closed after the request timeout'); +close($idle); +is(stop_listener($pid), 0, 'the listener stops cleanly'); + +my $image_b = "$root/rhels9/x86_64/service"; +my $sum_b = publish($image_b, "image B\n" x 100); +my ($limited, $limited_port) = config(batch_delay => 0, max_transfers => 1, transfer_timeout => 3); +($pid) = start_listener($limited); +wait_port($limited_port); +mode('block:20'); +my $blocking = request($limited_port, $sum_a, $path_a, '127.0.0.2'); +is(wait_state($limited_port, $blocking->{job}, '127.0.0.2', 'running')->{state}, 'running', 'the transfer starts'); +# A waiting job fails after transfer_timeout, so it must arrive at least a second after the running one started. +sleep(1.5); +my $waiting = request($limited_port, $sum_b, "$image_b/rootimg.cpio.gz", '127.0.0.3'); +is(job_state($limited_port, $waiting->{job}, '127.0.0.3')->{state}, 'pending', 'a second image waits while the transfer limit is reached'); +my $timed_out = wait_state($limited_port, $blocking->{job}, '127.0.0.2', 'failed', 'done'); +like($timed_out->{reason}, qr/transfer exceeded 3s/, 'a sender that exceeds its timeout fails the job'); +my $blocked_call = wait_call("127.0.0.2\n"); +ok($blocked_call && !kill(0, $blocked_call->{pid}), 'the timed out sender was stopped'); +is(wait_state($limited_port, $waiting->{job}, '127.0.0.3', 'running')->{state}, 'running', 'the waiting transfer starts when the slot frees'); +my $held = wait_call("127.0.0.3\n"); +is(stop_listener($pid), 0, 'the listener stops while a transfer runs'); +ok($held && !kill(0, $held->{pid}), 'stopping the listener stops its senders'); +mode('exit:0'); +reset_calls(); + +my ($crowded, $crowded_port) = config(max_connections => 2, request_timeout => 30, allowed_networks => '127.0.0.2/32'); +($pid) = start_listener($crowded); +wait_port($crowded_port); +sleep(0.5); +my @held = map { + IO::Socket::INET->new(PeerAddr => '127.0.0.1', PeerPort => $crowded_port, LocalAddr => '127.0.0.2', Proto => 'tcp') +} 1 .. 2; +sleep(0.5); +my $fds_before = () = glob("/proc/$pid/fd/*"); +my @refused; +for (1 .. 20) { + my $started = time(); + my $reply = http($crowded_port, ''); + push @refused, $reply->{code} == 503 && time() - $started < 2 ? 1 : 0; +} +is(scalar(grep { $_ } @refused), 20, 'connections beyond max_connections are refused at once'); +my $fds_after = () = glob("/proc/$pid/fd/*"); +is($fds_after, $fds_before, 'refused connections are not kept open'); +close($_) for @held; +sleep(0.5); +is(request($crowded_port, $sum_a, $path_a, '127.0.0.3')->{code}, 403, 'the address of the connection is checked against allowed_networks'); +is(request($crowded_port, $sum_a, $path_a, '127.0.0.2')->{code}, 200, 'the listener serves requests again when connections close'); +stop_listener($pid); + +done_testing(); diff --git a/xCAT-test/unit/uftp_listener.t b/xCAT-test/unit/uftp_listener.t new file mode 100644 index 0000000000..f492bdf38e --- /dev/null +++ b/xCAT-test/unit/uftp_listener.t @@ -0,0 +1,359 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use Cwd qw(realpath); +use Digest::SHA qw(sha256_hex); +use File::Path qw(make_path); +use File::Slurper qw(read_binary write_binary); +use File::Temp qw(tempdir); +use FindBin; +use Test::More; + +use lib "$FindBin::Bin/../../perl-xCAT"; +use lib "$FindBin::Bin/../../xCAT-server/lib/perl"; +use xCAT::SvrUtils; +use xCAT::UFTP; + +my $tmp = realpath(tempdir(CLEANUP => 1)); +my $root = "$tmp/install/netboot"; +my $fp = '31:94:09:9D:B1:24:3F:32:C0:B9:1A:BB:AC:F4:74:2B:80:F9:77:B2'; +make_path($root, "$tmp/log"); + +# packimage publishes the archive with its checksum, and the listener sends only such an archive. +sub publish { + my ($dir, $content, $name) = @_; + $name ||= 'rootimg.cpio.gz'; + make_path($dir); + chmod(0755, $dir); + my ($stage, $error) = xCAT::SvrUtils->rootimg_stage($dir); + die $error unless $stage; + write_binary("$stage/$name", $content); + chmod(0644, "$stage/$name"); + $error = xCAT::SvrUtils->write_rootimg_checksum("$stage/$name") // xCAT::SvrUtils->publish_rootimg("$stage/$name", "$dir/$name"); + die $error if $error; + return sha256_hex($content); +} + +my $config_seq = 0; +sub config { + my (%override) = @_; + my %settings = ( + listen_address => '192.0.2.1', + image_roots => $root, + batch_delay => 2, + transfer_timeout => 30, + job_retention => 60, + key_file => "$tmp/server.key", + fingerprint_file => "$tmp/server.fingerprint", + uftp => "$tmp/uftp", + log_dir => "$tmp/log", + %override, + ); + my $path = "$tmp/listener." . ++$config_seq . '.conf'; + write_binary($path, join('', map { "$_ = $settings{$_}\n" } sort keys %settings)); + my ($config, $error) = xCAT::UFTP::load_listener_config($path); + die $error if $error; + return $config; +} + +# The listener starts uftp in a child process, so the test records each start instead. +my (@log, @senders, @signals, $spawn_error); +my $next_pid = 4000; +sub spawn { + my ($job, $log, @command) = @_; + return (undef, $spawn_error) if $spawn_error; + my ($hostlist) = map { /^\@(.+)$/ ? $1 : () } @command; + sysseek($job->{fh}, 0, 0) or die "sysseek: $!"; + my $bytes = ''; + while (sysread($job->{fh}, my $chunk, 65536)) { + $bytes .= $chunk; + } + push @senders, { + pid => ++$next_pid, + log => $log, + command => \@command, + hostlist => $hostlist, + hosts => scalar(read_binary($hostlist)), + mode => (stat($hostlist))[2] & 07777, + bytes => $bytes, + }; + return ($next_pid, undef); +} + +sub listener { + my $config = config(@_); + @log = @senders = @signals = (); + return xCAT::UFTP::listener_state($config, workdir => tempdir(DIR => $tmp), spawn => \&spawn, + log => sub { push @log, "$_[0]: $_[1]" }, + signal => sub { push @signals, "$_[0] $_[1]" }); +} + +sub reply { + my ($state, $peer, $raw, $now) = @_; + my ($status, $body) = xCAT::UFTP::listener_reply($state, $peer, $raw, $now); + return { code => $status, body => $body, map { split /=/, $_, 2 } grep { /=/ } split /\n/, $body // '' }; +} + +sub transfer { + my ($state, $peer, $digest, $path, $now) = @_; + return reply($state, $peer, "GET /xcat-uftp/v1/transfer/$digest$path HTTP/1.0\r\nHost: test\r\n\r\n", $now); +} + +sub job_state { + my ($state, $peer, $job, $now) = @_; + return reply($state, $peer, "GET /xcat-uftp/v1/job/$job HTTP/1.0\r\n\r\n", $now); +} + +sub runtime { + my ($config, $key_fingerprint) = @_; + return xCAT::UFTP::check_listener_runtime($config, $key_fingerprint || sub { ($fp, undef) }); +} + +write_binary("$tmp/uftp", ("\0" x 64) . "UFTP version 5.0.4 (xCAT build 1) Copyright\0"); +write_binary("$tmp/uftp4", "\0UFTP version 4.10.2 Copyright\0"); +write_binary("$tmp/uftp-stock", "\0UFTP version 5.0.4 Copyright\0"); +chmod(0755, "$tmp/uftp", "$tmp/uftp4", "$tmp/uftp-stock"); + +my $checked = config(); +my ($fingerprint, $error) = runtime($checked); +like($error, qr/^UFTP server key \Q$tmp\E\/server\.key is missing; run xcat-uftp-listener --init-key$/, + 'a missing server key is refused with the command that creates it'); +write_binary("$tmp/server.key", "fixture private key\n"); +chmod(0600, "$tmp/server.key"); +($fingerprint, $error) = runtime($checked); +like($error, qr/^Cannot read UFTP server fingerprint .*; run xcat-uftp-listener --init-key$/, + 'a missing fingerprint file is refused'); +write_binary("$tmp/server.fingerprint", "$fp\n"); +($fingerprint, $error) = runtime($checked); +is($error, undef, 'the runtime check passes'); +is($fingerprint, $fp, 'the runtime check returns the fingerprint of the server key'); +is(scalar(() = glob("$tmp/log/.write-check*")), 0, 'the write check leaves no file in log_dir'); +(undef, $error) = runtime($checked, sub { (undef, "$tmp/uftp_keymgt failed for $tmp/server.key") }); +is($error, "$tmp/uftp_keymgt failed for $tmp/server.key", 'a key that uftp_keymgt cannot read is refused'); +chmod(0640, "$tmp/server.key"); +(undef, $error) = runtime($checked); +like($error, qr/must not be accessible by other users/, 'a private key that others can read is refused'); +chmod(0600, "$tmp/server.key"); +write_binary("$tmp/server.fingerprint", "00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33\n"); +(undef, $error) = runtime($checked); +like($error, qr/server\.fingerprint does not match \Q$tmp\E\/server\.key; run xcat-uftp-listener --init-key$/, + 'a fingerprint file for another key is refused'); +write_binary("$tmp/server.fingerprint", "$fp\n"); +chmod(0644, "$tmp/uftp"); +(undef, $error) = runtime($checked); +like($error, qr/UFTP sender \Q$tmp\E\/uftp is not executable; install the uftp package/, 'a sender that cannot run is refused'); +chmod(0755, "$tmp/uftp"); +(undef, $error) = runtime(config(uftp => "$tmp/uftp4")); +like($error, qr/UFTP 4\.10\.2; UFTP 5\.x is required/, 'a UFTP 4 sender is refused'); +(undef, $error) = runtime(config(uftp => "$tmp/uftp-stock")); +like($error, qr/UFTP 5\.0\.4 without the xCAT fixes/, 'a UFTP 5 sender without the xCAT build mark is refused'); +write_binary("$tmp/log-file", "not a directory\n"); +(undef, $error) = runtime(config(log_dir => "$tmp/log-file")); +is($error, "Cannot create $tmp/log-file", 'a log_dir that cannot be created is refused'); +(undef, $error) = runtime(config(log_dir => "$tmp/new/log")); +ok(!defined($error) && -d "$tmp/new/log", 'a missing log_dir is created'); + +my $image_a = "$root/rhels9/x86_64/compute"; +my $content_a = "image A generation 1\n" x 200; +my $sum_a = publish($image_a, $content_a); +my $path_a = "$image_a/rootimg.cpio.gz"; + +my $t = 1000; +my $state = listener(); +my $first = transfer($state, '192.0.2.10', $sum_a, $path_a, $t); +is($first->{code}, 200, 'a request for a published image is accepted'); +like($first->{job}, qr/^[0-9a-f]{16}$/, 'the reply names the transfer job'); +is($first->{file}, 'rootimg.cpio.gz', 'the reply names the artifact'); +is($first->{size}, length($content_a), 'the reply gives the artifact size'); +is($first->{port}, 1044, 'the reply gives the server-owned UDP port'); +is($first->{mcast}, '230.4.4.1', 'the reply gives the public multicast address'); +is($first->{server_id}, '0xC0000201', 'the reply gives the UFTP server ID'); +is($first->{server_ip}, '192.0.2.1', 'the reply gives the sending address'); +is($first->{client_ip}, '192.0.2.10', 'the reply gives the address the server saw'); +is($first->{start_in}, 2, 'the reply gives the batch delay'); +is($first->{timeout}, 30, 'the reply gives the transfer timeout'); + +my $again = transfer($state, '192.0.2.10', $sum_a, $path_a, $t + 1); +is($again->{job}, $first->{job}, 'a duplicate request joins the same job'); +is($again->{start_in}, 1, 'a later request gets the remaining batch delay'); +is(transfer($state, '192.0.2.11', $sum_a, "/$path_a", $t + 1)->{code}, 400, 'an unnormalized image path is refused'); +is(transfer($state, '192.0.2.11', $sum_a, $path_a, $t + 1)->{job}, $first->{job}, + 'a compatible request from another node joins the same job'); +my @added = map { /: job \Q$first->{job}\E: added (\S+)$/ ? $1 : () } @log; +is_deeply(\@added, [ '192.0.2.10', '192.0.2.11' ], 'the log adds each node to the job once'); +ok((grep { $_ eq "info: job $first->{job}: 192.0.2.10 asked again" } @log), 'the log reports the repeated request'); +my $pending = job_state($state, '192.0.2.10', $first->{job}, $t + 1); +is($pending->{state}, 'pending', 'a member sees the job wait for its batch'); +is($pending->{start_in}, 1, 'a waiting job reports the remaining batch delay'); + +xCAT::UFTP::run_jobs($state, $t + 1); +is(scalar(@senders), 0, 'no sender starts before the batch delay ends'); +xCAT::UFTP::run_jobs($state, $t + 2); +is(scalar(@senders), 1, 'one sender serves the coalesced requests'); +my $sent = $senders[0]; +is($sent->{hosts}, "192.0.2.10\n192.0.2.11\n", 'the closed group lists each requesting node once'); +is($sent->{mode}, 0600, 'only the listener can read the host list'); +is($sent->{bytes}, $content_a, 'the sender gets the published bytes'); +is($sent->{log}, "$tmp/log/job-$first->{job}.log", 'the sender writes the log of its job'); +is_deeply($sent->{command}, [ "$tmp/uftp", '-I', '192.0.2.1', '-U', '0xC0000201', '-p', '1044', '-M', '230.4.4.1', + '-P', '230.5.5.x', '-t', '1', '-R', '100000', '-b', '1300', '-N', '98', '-Y', 'aes256-gcm', + '-h', 'sha256', '-k', "$tmp/server.key", '-H', "\@$sent->{hostlist}", '-x', '2', '-l', + '-D', 'rootimg.cpio.gz', '/dev/fd/3' ], 'the sender gets only server-owned arguments'); +is_deeply([ xCAT::UFTP::sender_pids($state) ], [ $sent->{pid} ], 'the listener tracks the running sender'); +is(job_state($state, '192.0.2.10', $first->{job}, $t + 2)->{state}, 'running', 'a member sees the job run'); +is(job_state($state, '192.0.2.99', $first->{job}, $t + 2)->{code}, 404, 'a node outside the job cannot query it'); +my $late = transfer($state, '192.0.2.12', $sum_a, $path_a, $t + 3); +isnt($late->{job}, $first->{job}, 'a node arriving after the transfer started gets a new job'); + +xCAT::UFTP::sender_exited($state, $sent->{pid}, 0, $t + 4); +is(job_state($state, '192.0.2.10', $first->{job}, $t + 4)->{state}, 'done', 'a sender that exits with status 0 completes the job'); +ok(!-e $sent->{hostlist}, 'the host list is removed when the job finishes'); +is(scalar(xCAT::UFTP::sender_pids($state)), 0, 'a finished sender is no longer tracked'); +xCAT::UFTP::sender_exited($state, 999999, 0, $t + 4); +is(job_state($state, '192.0.2.10', $first->{job}, $t + 4)->{state}, 'done', 'the exit of an unknown process changes no job'); +xCAT::UFTP::run_jobs($state, $t + 63); +is(job_state($state, '192.0.2.10', $first->{job}, $t + 63)->{state}, 'done', 'a finished job stays for job_retention'); +xCAT::UFTP::run_jobs($state, $t + 64); +is(job_state($state, '192.0.2.10', $first->{job}, $t + 64)->{code}, 404, 'a finished job is forgotten after job_retention'); + +$state = listener(); +is(reply($state, '192.0.2.10', "GET / HTTP/1.0\r\nX-Image: $path_a\r\nReferer: /xcat-uftp/v1/transfer/$sum_a$path_a\r\n\r\n", $t)->{code}, + 404, 'an image path in a header does not select an image'); +is(transfer($state, '192.0.2.10', $sum_a, '/etc/passwd', $t)->{code}, 400, 'a request for an unrelated file is refused'); +ok((grep { /^warning: 192\.0\.2\.10: rejected request: unsupported image artifact$/ } @log), 'the log reports why a request is refused'); +write_binary("$image_a/rootimg.tar.gz", "unrelated archive\n"); +chmod(0644, "$image_a/rootimg.tar.gz"); +is(transfer($state, '192.0.2.10', sha256_hex("unrelated archive\n"), "$image_a/rootimg.tar.gz", $t)->{code}, 403, + 'an existing image file that was not published is refused'); +is(transfer($state, '192.0.2.10', $sum_a, "$root/rhels9/../../../etc/rootimg.cpio.gz", $t)->{code}, 400, 'traversal is refused'); +is(reply($state, '192.0.2.10', "GET /xcat-uftp/v1/transfer/$sum_a/install/%2e%2e/rootimg.cpio.gz HTTP/1.0\r\n\r\n", $t)->{code}, + 400, 'percent-encoded paths are refused'); +is(transfer($state, '192.0.2.10', 'f' x 64, $path_a, $t)->{code}, 403, 'an unpublished digest is refused'); +my $outside = "$tmp/outside/compute"; +my $sum_out = publish($outside, "outside\n"); +symlink($outside, "$root/escape") or die $!; +is(transfer($state, '192.0.2.10', $sum_out, "$root/escape/rootimg.cpio.gz", $t)->{code}, 403, + 'a symbolic link escaping the image roots is refused'); +is(reply($state, '192.0.2.10', "GET /xcat-uftp/v1/job/0123456789abcdef HTTP/1.0\r\n\r\n", $t)->{code}, 404, + 'an unknown job is not found'); +is(reply($state, '192.0.2.10', 'GET /x HTTP/1.0' . ('y' x 9000) . "\r\n\r\n", $t)->{code}, 413, 'an oversized request is refused'); +is(scalar(my @none = xCAT::UFTP::listener_reply($state, '192.0.2.10', "GET / HTTP/1.0\r\n", $t)), 0, + 'an incomplete request gets no reply yet'); +is(reply($state, '192.0.2.10', "POST /xcat-uftp/v1/transfer/$sum_a$path_a HTTP/1.0\r\n\r\n", $t)->{code}, 405, + 'a method other than GET is refused'); +is(scalar(keys %{ $state->{jobs} }), 0, 'refused requests create no job'); + +my $odd = "$root/-H/-x"; +my $sum_odd = publish($odd, "option-looking directory\n", 'rootimg.sfs'); +is(transfer($state, '192.0.2.10', $sum_odd, "$odd/rootimg.sfs", $t)->{code}, 200, 'an image in an option-looking directory is accepted'); +xCAT::UFTP::run_jobs($state, $t + 2); +is_deeply([ @{ $senders[0]{command} }[ -3 .. -1 ] ], [ '-D', 'rootimg.sfs', '/dev/fd/3' ], + 'the sender gets the file name of the image'); +is(scalar(grep { index($_, '/-H/-x') >= 0 } @{ $senders[0]{command} }), 0, 'no request text is passed to the sender'); +is($senders[0]{bytes}, "option-looking directory\n", 'the option-looking image is sent intact'); + +my $image_b = "$root/rhels9/x86_64/service"; +my $gen1 = "image B generation 1\n" x 100; +my $gen2 = "image B generation 2\n" x 120; +$state = listener(); +my $sum_b1 = publish($image_b, $gen1); +my $old_gen = transfer($state, '192.0.2.20', $sum_b1, "$image_b/rootimg.cpio.gz", $t); +my $sum_b2 = publish($image_b, $gen2); +is(transfer($state, '192.0.2.21', $sum_b1, "$image_b/rootimg.cpio.gz", $t)->{code}, 403, 'a repacked generation is no longer offered'); +my $new_gen = transfer($state, '192.0.2.21', $sum_b2, "$image_b/rootimg.cpio.gz", $t); +isnt($new_gen->{job}, $old_gen->{job}, 'different image generations never share a job'); +xCAT::UFTP::run_jobs($state, $t + 2); +my %by_hosts = map { $_->{hosts} => $_->{bytes} } @senders; +is($by_hosts{"192.0.2.20\n"}, $gen1, 'a queued job still sends the generation it validated'); +is($by_hosts{"192.0.2.21\n"}, $gen2, 'the new generation is sent to its own job'); + +$state = listener(); +my $failing = transfer($state, '192.0.2.30', $sum_a, $path_a, $t); +xCAT::UFTP::run_jobs($state, $t + 2); +xCAT::UFTP::sender_exited($state, $senders[-1]{pid}, 7 << 8, $t + 3); +my $failed = job_state($state, '192.0.2.30', $failing->{job}, $t + 3); +is($failed->{state}, 'failed', 'a sender failure fails the job'); +is($failed->{reason}, 'uftp exited with status 7', 'the job reports why the sender failed'); +ok((grep { $_ eq "error: job $failing->{job}: failed (uftp exited with status 7)" } @log), 'the log reports the failed job'); +my $retry = transfer($state, '192.0.2.30', $sum_a, $path_a, $t + 3); +isnt($retry->{job}, $failing->{job}, 'a retry after a failure gets a new job'); +xCAT::UFTP::run_jobs($state, $t + 5); +xCAT::UFTP::sender_exited($state, $senders[-1]{pid}, 9, $t + 6); +is(job_state($state, '192.0.2.30', $retry->{job}, $t + 6)->{reason}, 'uftp killed by signal 9', 'the job reports the signal that stopped the sender'); +my $unstarted = transfer($state, '192.0.2.31', $sum_a, $path_a, $t + 6); +$spawn_error = 'fork failed: Resource temporarily unavailable'; +xCAT::UFTP::run_jobs($state, $t + 8); +undef $spawn_error; +my $unstarted_state = job_state($state, '192.0.2.31', $unstarted->{job}, $t + 8); +is($unstarted_state->{state}, 'failed', 'a sender that cannot start fails the job'); +is($unstarted_state->{reason}, 'fork failed: Resource temporarily unavailable', 'the job reports why the sender did not start'); +is(scalar(() = glob("$state->{workdir}/*.hosts")), 0, 'no host list stays after the jobs finish'); + +$state = listener(batch_delay => 0, max_transfers => 1, max_queued_jobs => 2, max_clients_per_job => 2, transfer_timeout => 3); +my $c_image = "$root/rhels9/x86_64/login"; +my $sum_c = publish($c_image, "image C\n"); +my $blocking = transfer($state, '192.0.2.40', $sum_a, $path_a, $t); +xCAT::UFTP::run_jobs($state, $t); +is(job_state($state, '192.0.2.40', $blocking->{job}, $t)->{state}, 'running', 'a zero batch delay starts the transfer at once'); +my $waiting = transfer($state, '192.0.2.41', $sum_b2, "$image_b/rootimg.cpio.gz", $t); +xCAT::UFTP::run_jobs($state, $t + 1); +is(job_state($state, '192.0.2.41', $waiting->{job}, $t + 1)->{state}, 'pending', 'a second image waits while the transfer limit is reached'); +is(transfer($state, '192.0.2.42', $sum_c, "$c_image/rootimg.cpio.gz", $t + 1)->{code}, 503, 'the queue limit refuses further images'); +is(transfer($state, '192.0.2.42', $sum_b2, "$image_b/rootimg.cpio.gz", $t + 1)->{job}, $waiting->{job}, 'a node joins the waiting job'); +my $full = transfer($state, '192.0.2.43', $sum_b2, "$image_b/rootimg.cpio.gz", $t + 1); +is($full->{code}, 503, 'the per-job client limit refuses further nodes'); +is($full->{error}, 'transfer is full', 'the reply says the job is full'); +xCAT::UFTP::run_jobs($state, $t + 2); +is_deeply(\@signals, [], 'a sender within its timeout keeps running'); +xCAT::UFTP::run_jobs($state, $t + 3); +is_deeply(\@signals, ["TERM $senders[0]{pid}"], 'a sender that exceeds transfer_timeout is asked to stop'); +xCAT::UFTP::sender_exited($state, $senders[0]{pid}, 15, $t + 3); +my $timed_out = job_state($state, '192.0.2.40', $blocking->{job}, $t + 3); +is($timed_out->{state}, 'failed', 'a transfer that exceeds its timeout fails'); +is($timed_out->{reason}, 'transfer exceeded 3s', 'the timeout is reported'); +xCAT::UFTP::run_jobs($state, $t + 3); +is(job_state($state, '192.0.2.41', $waiting->{job}, $t + 3)->{state}, 'running', 'the waiting transfer starts when the slot frees'); +is($senders[1]{hosts}, "192.0.2.41\n192.0.2.42\n", 'the waiting transfer sends to the nodes that joined it'); +@signals = (); +xCAT::UFTP::run_jobs($state, $t + 6); +xCAT::UFTP::run_jobs($state, $t + 10); +is_deeply(\@signals, ["TERM $senders[1]{pid}"], 'a sender gets the kill grace time after it is asked to stop'); +xCAT::UFTP::run_jobs($state, $t + 11); +is_deeply(\@signals, [ "TERM $senders[1]{pid}", "KILL $senders[1]{pid}" ], 'a sender that ignores the request to stop is killed'); +xCAT::UFTP::sender_exited($state, $senders[1]{pid}, 9, $t + 11); +is(job_state($state, '192.0.2.41', $waiting->{job}, $t + 11)->{reason}, 'transfer exceeded 3s', 'a killed sender reports the timeout'); + +$state = listener(batch_delay => 0, max_transfers => 1, transfer_timeout => 3); +transfer($state, '192.0.2.50', $sum_a, $path_a, $t); +xCAT::UFTP::run_jobs($state, $t); +my $starved = transfer($state, '192.0.2.51', $sum_c, "$c_image/rootimg.cpio.gz", $t); +xCAT::UFTP::run_jobs($state, $t + 3); +is(job_state($state, '192.0.2.51', $starved->{job}, $t + 3)->{state}, 'pending', 'a waiting job waits up to transfer_timeout for a slot'); +xCAT::UFTP::run_jobs($state, $t + 4); +my $starved_state = job_state($state, '192.0.2.51', $starved->{job}, $t + 4); +is($starved_state->{state}, 'failed', 'a job that gets no slot within transfer_timeout fails'); +is($starved_state->{reason}, 'no transfer slot became free', 'the job reports that no slot became free'); + +$state = listener(); +my $queued = transfer($state, '192.0.2.60', $sum_a, $path_a, $t); +my $sending = transfer($state, '192.0.2.61', $sum_c, "$c_image/rootimg.cpio.gz", $t - 2); +xCAT::UFTP::run_jobs($state, $t); +xCAT::UFTP::sender_exited($state, $senders[0]{pid}, 15, $t, 'listener stopped'); +xCAT::UFTP::stop_jobs($state, $t); +is(job_state($state, '192.0.2.61', $sending->{job}, $t)->{reason}, 'listener stopped', 'a sender stopped with the listener fails its job'); +my $stopped = job_state($state, '192.0.2.60', $queued->{job}, $t); +is($stopped->{state}, 'failed', 'a queued job fails when the listener stops'); +is($stopped->{reason}, 'listener stopped', 'the queued job reports that the listener stopped'); + +$state = listener(max_connections => 2, allowed_networks => '192.0.2.8/30'); +is_deeply([ xCAT::UFTP::connection_refusal($state, 1, '192.0.2.9') ], [], 'an address inside allowed_networks is accepted'); +is_deeply([ xCAT::UFTP::connection_refusal($state, 2, '192.0.2.9') ], [ 503, "error=too many connections\n" ], + 'a connection beyond max_connections is refused'); +is_deeply([ xCAT::UFTP::connection_refusal($state, 0, '192.0.2.12') ], [ 403, "error=client address is not allowed\n" ], + 'an address outside allowed_networks is refused'); +is_deeply(\@log, ['warning: 192.0.2.12: address is not in allowed_networks'], 'the log names the refused address'); +$state = listener(); +is_deeply([ xCAT::UFTP::connection_refusal($state, 0, '198.51.100.7') ], [], 'any address is accepted without allowed_networks'); + +done_testing();