From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id F0C9C1FF0B7 for ; Mon, 30 Nov 2026 02:15:41 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 0A5A5216F0; Mon, 30 Nov 2026 02:15:40 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH apiclient 04/09] add non-blocking AnyEvent API client Date: Mon, 30 Nov 2026 01:58:08 +0100 Message-ID: <20261130010113.2166775-5-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com> References: <20261130010113.2166775-1-t.lamprecht@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796000480828 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.002 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) POISEN_SPAM_PILL 0.1 Meta: its spam POISEN_SPAM_PILL_1 0.1 random spam to be learned in bayes POISEN_SPAM_PILL_3 0.1 random spam to be learned in bayes RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Hits: max-size X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; news-moderation; no-subject; digests; suspicious-header Message-ID-Hash: DYDQUQ2VOVGMS2L6AB65WG4NEXH4A2Q7 X-Message-ID-Hash: DYDQUQ2VOVGMS2L6AB65WG4NEXH4A2Q7 X-Mailman-Approved-At: Mon, 30 Nov 2026 02:15:37 +0100 X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Services running inside an AnyEvent event loop (such as pveproxy) cannot use PVE::APIClient::LWP without blocking the event loop on remote API calls. Add PVE::APIClient::AnyEvent as a non-blocking counterpart built on AnyEvent::HTTP and AnyEvent::TLS. The client supports API token and ticket/CSRF authentication, IPv6 host bracketing, per-client persistent connection cache isolation, strict header name/value validation, CA/hostname verification with SHA-256 fingerprint pinning and fallback callbacks, and idempotent request cancellation. request_raw() exposes buffered response bodies after HTTP transfer decoding and defers setup errors via AE::postpone, call() delivers the full decoded JSON envelope, and get()/post()/put()/delete() extract the response data field. Signed-off-by: Thomas Lamprecht --- Makefile | 4 + debian/control | 12 +- src/Makefile | 7 +- src/PVE/APIClient/AnyEvent.pm | 496 ++++++++++ src/test/anyevent_client.t | 1653 +++++++++++++++++++++++++++++++++ 5 files changed, 2170 insertions(+), 2 deletions(-) create mode 100644 src/PVE/APIClient/AnyEvent.pm create mode 100644 src/test/anyevent_client.t diff --git a/Makefile b/Makefile index c270ea1..da4831e 100644 --- a/Makefile +++ b/Makefile @@ -18,6 +18,10 @@ all: $(DEB) tidy: git ls-files ':*.p[ml]'| xargs -n4 -P0 proxmox-perltidy +.PHONY: check +check: + $(MAKE) -C src check + $(BUILDSRC): rm -rf $@ $@.tmp cp -a src $@.tmp diff --git a/debian/control b/debian/control index e7ed070..0887c9a 100644 --- a/debian/control +++ b/debian/control @@ -3,16 +3,26 @@ Section: perl Priority: optional Maintainer: Proxmox Support Team Build-Depends: debhelper-compat (= 13), + libanyevent-http-perl, + libanyevent-perl, + libhttp-message-perl, + libjson-perl, + libnet-ssleay-perl, + liburi-perl, + openssl, perl, Standards-Version: 4.5.1 Homepage: https://www.proxmox.com Package: libpve-apiclient-perl Architecture: all -Depends: libcrypt-ssleay-perl, +Depends: libanyevent-http-perl, + libanyevent-perl, + libcrypt-ssleay-perl, libhttp-message-perl, libio-socket-ssl-perl, libjson-perl, + libnet-ssleay-perl, liburi-perl, libwww-perl, ${misc:Depends}, diff --git a/src/Makefile b/src/Makefile index bc19e9f..d6327c6 100644 --- a/src/Makefile +++ b/src/Makefile @@ -6,8 +6,9 @@ DOCDIR=$(DESTDIR)/usr/share/doc/$(PACKAGE) all: -install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm examples/*.pl +install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm PVE/APIClient/AnyEvent.pm examples/*.pl install -D -m 0644 PVE/APIClient/LWP.pm $(PERL5DIR)/PVE/APIClient/LWP.pm + install -m 0644 PVE/APIClient/AnyEvent.pm $(PERL5DIR)/PVE/APIClient/AnyEvent.pm install -m 0644 PVE/APIClient/Exception.pm $(PERL5DIR)/PVE/APIClient/Exception.pm install -d -m 755 $(DOCDIR)/examples install -m 0755 examples/example1.pl $(DOCDIR)/examples @@ -15,3 +16,7 @@ install: PVE/APIClient/Exception.pm PVE/APIClient/LWP.pm examples/*.pl install -m 0755 examples/perftest1.pl $(DOCDIR)/examples clean: + +.PHONY: check +check: + prove -I. test/*.t diff --git a/src/PVE/APIClient/AnyEvent.pm b/src/PVE/APIClient/AnyEvent.pm new file mode 100644 index 0000000..0b29ab7 --- /dev/null +++ b/src/PVE/APIClient/AnyEvent.pm @@ -0,0 +1,496 @@ +package PVE::APIClient::AnyEvent; + +# Non-blocking AnyEvent counterpart to PVE::APIClient::LWP for services running inside an AnyEvent +# event loop. Key differences from LWP.pm: +# - Explicit ticket/CSRF or API token auth only; no auto-login or interactive fingerprint prompt. +# - ssl_opts targets AnyEvent::TLS (verify_hostname defaults to 0 only with cached_fingerprints). +# - request_raw() yields the buffered response body after HTTP transfer decoding (before +# decompression or JSON decoding); call() delivers the full decoded JSON envelope; +# get()/post()/put()/delete() extract the response data field. +# - Each client instance isolates AnyEvent::HTTP's persistent connection cache via a unique +# sessionid so TLS verification contexts and fingerprint pins are never shared across clients. + +use v5.36; + +use AnyEvent; +use AnyEvent::HTTP; +use AnyEvent::TLS; +use Carp; +use Compress::Zlib (); +use JSON qw(from_json); +use Net::SSLeay; +use URI::Escape qw(uri_escape); +use URI; + +use PVE::APIClient::Exception; + +my $NEXT_SESSION_ID = 0; +my $HEADER_NAME_RE = qr/^[!#\$%&'*+\-.^_`|~0-9a-zA-Z]+\z/; + +# Decode a raw JSON API response body, gunzipping first when $is_gzip is true. +sub decode_json_body($body_ref, $is_gzip = 0) { + croak "body_ref must be a SCALAR ref" if ref($body_ref) ne 'SCALAR'; + + my $raw = $$body_ref; + if ($is_gzip) { + # Copy because Compress::Zlib::memGunzip consumes its input scalar in place. + my $copy = $raw; + $raw = Compress::Zlib::memGunzip($copy); + die "failed to gunzip response\n" if !defined($raw); + } + + return from_json($raw, { utf8 => 1, allow_nonref => 1 }); +} + +my sub invoke_callback($cb, @args) { + eval { $cb->(@args); }; + my $err = $@; + # Clear OpenSSL errors left by TLS work or user callbacks (see PVE::APIServer::AnyEvent). + Net::SSLeay::ERR_clear_error(); + warn $err if $err; +} + +my sub validate_header($name, $value) { + if (!defined($name) || ref($name) || $name !~ $HEADER_NAME_RE) { + croak "invalid HTTP header name"; + } + if (!defined($value) || ref($value) || $value =~ /[\r\n\0]/) { + croak "invalid HTTP header value for '$name'"; + } +} + +my sub normalize_headers($headers = undef) { + my %norm; + return \%norm if !$headers; + croak "headers must be a HASH ref" if ref($headers) ne 'HASH'; + for my $key (keys %$headers) { + validate_header($key, $headers->{$key}); + $norm{ lc($key) } = $headers->{$key}; + } + return \%norm; +} + +my sub build_tls_ctx($self) { + return $self->{tls_ctx} if $self->{tls_ctx}; + + my %ssl_opts = %{ $self->{ssl_opts} || {} }; + my ($fingerprints, $verify_fp_cb) = $self->@{ 'cached_fingerprints', 'verify_fingerprint_cb' }; + my $has_cached_fp = scalar(keys %$fingerprints) > 0 ? 1 : 0; + my $has_fp_pinning = ($has_cached_fp || defined($verify_fp_cb)) ? 1 : 0; + + if (exists($ssl_opts{verify}) && !$ssl_opts{verify}) { + die PVE::APIClient::Exception->new( + "cannot disable TLS certificate verification (verify => 0)\n"); + } + + my $explicit_verify_hostname = + defined($ssl_opts{verify_hostname}) ? ($ssl_opts{verify_hostname} ? 1 : 0) : undef; + my $verify_hostname; + if (defined($explicit_verify_hostname)) { + $verify_hostname = $explicit_verify_hostname; + } else { + # Match LWP.pm: purely trust configured cached fingerprints by default, otherwise enforce + # hostname verification (falling back to verify_fingerprint_cb for untrusted certs). + $verify_hostname = $has_cached_fp ? 0 : 1; + } + delete $ssl_opts{verify_hostname}; + + if ( + $explicit_verify_hostname + && defined($ssl_opts{verify_peername}) + && $ssl_opts{verify_peername} eq 'none' + ) { + die PVE::APIClient::Exception->new( + "conflicting ssl_opts: verify_hostname => 1 with verify_peername => 'none'\n"); + } + + my %tls_args = ( + method => 'any', + sslv2 => 0, + sslv3 => 0, + verify => 1, + dh => undef, + %ssl_opts, + ); + + if ( + !defined($tls_args{ca_file}) + && !defined($tls_args{ca_cert}) + && !defined($tls_args{ca_path}) + ) { + # Use hashed CA directory lookup so per-peer contexts skip eager CA bundle parsing. + $tls_args{ca_path} = '/usr/lib/ssl/certs'; + } + + $tls_args{verify_peername} //= $verify_hostname ? 'https' : 'none'; + + if (!$has_fp_pinning && !$tls_args{verify_cb} && $tls_args{verify_peername} eq 'none') { + die PVE::APIClient::Exception->new( + "cannot disable verify_hostname without cached_fingerprints, verify_fingerprint_cb, or verify_cb\n" + ); + } + + if ($tls_args{verify_cb}) { + my $user_verify_cb = $tls_args{verify_cb}; + $tls_args{verify_cb} = sub { + my $ok = eval { $user_verify_cb->(@_) }; + if (my $err = $@) { + warn $err; + return 0; + } + return $ok ? 1 : 0; + }; + } elsif ($has_fp_pinning) { + my %chain_failed; + $tls_args{verify_cb} = sub { + my (undef, undef, undef, $depth, $preverify_ok, $ctx, $cert) = @_; + + if ($verify_hostname && !$preverify_ok && defined($ctx)) { + $chain_failed{$ctx} = 1; + } + return 1 if $depth != 0; + + my $failed = defined($ctx) ? delete($chain_failed{$ctx}) : 0; + return 1 if $verify_hostname && $preverify_ok && !$failed; + + return 0 if !$cert; + my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256'); + return 0 if !defined($fp) || $fp eq ''; + + my $cached = $fingerprints->{$fp}; + return $cached if defined($cached); + + if ($verify_fp_cb) { + my $valid = eval { $verify_fp_cb->($cert) ? 1 : 0 }; + if (my $err = $@) { + warn $err; + return 0; + } + $fingerprints->{$fp} = $valid; + return $valid; + } + + return 0; + }; + } + + Net::SSLeay::ERR_clear_error(); + $self->{tls_ctx} = AnyEvent::TLS->new(%tls_args); + Net::SSLeay::ERR_clear_error(); + + return $self->{tls_ctx}; +} + +my sub build_uri($self, $path, $query_param = undef) { + my $uri = URI->new(); + $uri->scheme($self->{protocol}); + $uri->host($self->{host}); + $uri->port($self->{port}); + + $path //= ''; + $path =~ s!^/+!!; + if ($path !~ m!^api2/!) { + $uri->path("api2/json/$path"); + } else { + $uri->path($path); + } + + if (defined($query_param) && ref($query_param) eq 'HASH' && %$query_param) { + $uri->query_form($query_param); + } + + return $uri; +} + +sub new($class, %param) { + my $host = $param{host} || 'localhost'; + my $port = $param{port} || ($host eq 'localhost' ? 85 : 8006); + my $protocol = $param{protocol}; + if (!$protocol) { + # Match LWP.pm: default to plain HTTP only for privileged localhost ports (e.g. 85). + $protocol = $host eq 'localhost' && $port < 1024 ? 'http' : 'https'; + } else { + $protocol = lc($protocol); + if ($protocol ne 'http' && $protocol ne 'https') { + croak "unsupported protocol '$protocol'"; + } + } + + my $cookie_name = $param{cookie_name} // 'PVEAuthCookie'; + my $api_token_name = $param{api_token_name} // 'PVEAPIToken'; + + my $default_headers = normalize_headers($param{headers}); + + my $api_token = $param{api_token} // $param{apitoken}; + if (defined($api_token)) { + warn "ticket will be ignored in favor of API token\n" if defined($param{ticket}); + my $auth_header = $api_token; + if ($auth_header !~ /^\w+(?:=| )/) { + $auth_header = "${api_token_name}=${api_token}"; + } + $default_headers->{authorization} = $auth_header; + } elsif (defined($param{ticket})) { + my $encticket = uri_escape($param{ticket}); + $default_headers->{cookie} = "$cookie_name=$encticket; path=/; secure; SameSite=Strict;"; + } + + if (defined($param{csrftoken})) { + $default_headers->{csrfpreventiontoken} = $param{csrftoken}; + } + + for my $key (keys %$default_headers) { + validate_header($key, $default_headers->{$key}); + } + + my $self = { + host => $host, + port => $port, + protocol => $protocol, + cookie_name => $cookie_name, + api_token_name => $api_token_name, + timeout => $param{timeout} || 60, + cached_fingerprints => { %{ $param{cached_fingerprints} || {} } }, + verify_fingerprint_cb => $param{verify_fingerprint_cb}, + ssl_opts => $param{ssl_opts} ? { %{ $param{ssl_opts} } } : {}, + headers => $default_headers, + persistent => $param{persistent} ? 1 : 0, + keepalive => $param{keepalive} ? 1 : 0, + # Isolate AnyEvent::HTTP's persistent connection cache per client TLS context/pin. + sessionid => 'pve-apiclient-ae-' . ++$NEXT_SESSION_ID, + tls_ctx => undef, + }; + + return bless $self, $class; +} + +# Execute a non-blocking HTTP request against the PVE API. +# +# Delivers exactly one terminal callback (and none after $cancel->()): +# - on_response->($status, $body_ref, $hdr): AnyEvent::HTTP buffers the response body after HTTP +# transfer decoding (e.g. chunked framing removed), and $body_ref points to it before +# decompression or JSON decoding. +# - on_error->($err): $err is a PVE::APIClient::Exception for transport/59x/setup failures. +# Thrown setup errors are deferred via AE::postpone so on_error never fires before $cancel is +# returned (invalid callback/body+param arguments croak synchronously). +# Returns an idempotent, cycle-free cancel coderef. +sub request_raw($self, $method, $path, $param, %opts) { + my ($on_response, $on_error) = @opts{ 'on_response', 'on_error' }; + croak "on_response must be a CODE ref" if ref($on_response) ne 'CODE'; + croak "on_error must be a CODE ref" if ref($on_error) ne 'CODE'; + + my $uc_method = uc($method // ''); + if ( + ($uc_method eq 'POST' || $uc_method eq 'PUT') + && defined($opts{body}) + && defined($param) + && ref($param) eq 'HASH' + && %$param + ) { + croak "cannot pass both body and param"; + } + + my $state = { + done => 0, + guard => undef, + }; + + my $cancel = sub { + return if $state->{done}; + $state->{done} = 1; + undef $state->{guard}; + Net::SSLeay::ERR_clear_error(); + }; + + my $guard = eval { + if ($uc_method !~ /^(?:GET|POST|PUT|DELETE|HEAD)$/) { + die PVE::APIClient::Exception->new("method $uc_method not implemented\n"); + } + + my %headers = ( + %{ $self->{headers} }, %{ normalize_headers($opts{headers}) }, + ); + for my $key (keys %headers) { + validate_header($key, $headers{$key}); + } + + my ($uri, $body); + if ($uc_method eq 'POST' || $uc_method eq 'PUT') { + $uri = build_uri($self, $path); + if (defined($opts{body})) { + $body = $opts{body}; + } elsif (defined($param) && ref($param) eq 'HASH' && %$param) { + my $tmpurl = URI->new('http:'); + $tmpurl->query_form(%$param); + $body = $tmpurl->query; + if (!exists($headers{'content-type'})) { + $headers{'content-type'} = 'application/x-www-form-urlencoded'; + } + } + } else { + $uri = build_uri($self, $path, $param); + } + + my %req_args = ( + headers => \%headers, + timeout => $opts{timeout} // $self->{timeout}, + proxy => undef, + persistent => $opts{persistent} // $self->{persistent}, + recurse => 0, + keepalive => $opts{keepalive} // $self->{keepalive}, + sessionid => $self->{sessionid}, + ); + $req_args{body} = $body if defined($body); + $req_args{tls_ctx} = build_tls_ctx($self) if $self->{protocol} eq 'https'; + + Net::SSLeay::ERR_clear_error(); + return AnyEvent::HTTP::http_request( + $uc_method => $uri->as_string(), + %req_args, + sub { + my (undef, $hdr) = @_; + + return if $state->{done}; + $state->{done} = 1; + undef $state->{guard}; + + Net::SSLeay::ERR_clear_error(); + + my $status = $hdr->{Status} // 599; + if ($status >= 590 && $status <= 599) { + my $reason = $hdr->{Reason} // 'request failed'; + my $exc = PVE::APIClient::Exception->new("$reason\n", code => $status); + invoke_callback($on_error, $exc); + return; + } + + invoke_callback($on_response, $status, \$_[0], $hdr); + }, + ); + }; + my $err = $@; + + Net::SSLeay::ERR_clear_error(); + + if ($err) { + if (!$state->{done}) { + my $exc = + ref($err) eq 'PVE::APIClient::Exception' + ? $err + : PVE::APIClient::Exception->new("$err"); + AE::postpone { + return if $state->{done}; + $state->{done} = 1; + undef $state->{guard}; + invoke_callback($on_error, $exc); + }; + } else { + warn $err; + } + } elsif (!$state->{done}) { + $state->{guard} = $guard; + } + + return $cancel; +} + +# Execute a JSON API call with gzip support and deliver the full decoded JSON response to +# on_response (matching PVE::APIClient::LWP::call). +sub call($self, $method, $path, $param, %opts) { + my ($on_response, $on_error) = delete @opts{ 'on_response', 'on_error' }; + croak "on_response must be a CODE ref" if ref($on_response) ne 'CODE'; + croak "on_error must be a CODE ref" if ref($on_error) ne 'CODE'; + + my $headers = normalize_headers($opts{headers}); + if (!exists($headers->{'accept-encoding'}) && !exists($self->{headers}->{'accept-encoding'})) { + $headers->{'accept-encoding'} = 'gzip'; + } + $opts{headers} = $headers; + + return $self->request_raw( + $method, + $path, + $param, + %opts, + on_error => $on_error, + on_response => sub { + my ($status, $body_ref, $hdr) = @_; + + my $ct = $hdr->{'content-type'} // ''; + my $is_gzip = (($hdr->{'content-encoding'} // '') =~ /\bgzip\b/i) ? 1 : 0; + + if ($status < 200 || $status >= 300) { + my $reason = $hdr->{Reason} // "HTTP $status"; + my $errors = eval { + return if $ct !~ m|application/json|i; + my $res = decode_json_body($body_ref, $is_gzip); + return ref($res) eq 'HASH' ? $res->{errors} : undef; + }; + my $exc = PVE::APIClient::Exception->new( + "$reason\n", + code => $status, + errors => $errors, + ); + $on_error->($exc); + return; + } + + if ($ct !~ m|application/json|i) { + $on_error->( + PVE::APIClient::Exception->new( + "got unexpected content type\n", + code => $status, + ), + ); + return; + } + + my $decoded = eval { decode_json_body($body_ref, $is_gzip) }; + if (my $err = $@) { + $on_error->(PVE::APIClient::Exception->new("$err", code => $status)); + return; + } + + $on_response->($decoded); + }, + ); +} + +my sub call_data($self, $method, $path, $param, %opts) { + my ($on_response, $on_error) = delete @opts{ 'on_response', 'on_error' }; + croak "on_response must be a CODE ref" if ref($on_response) ne 'CODE'; + croak "on_error must be a CODE ref" if ref($on_error) ne 'CODE'; + + return $self->call( + $method, + $path, + $param, + %opts, + on_error => $on_error, + on_response => sub { + my ($res) = @_; + if (ref($res) ne 'HASH' || !exists($res->{data})) { + $on_error->(PVE::APIClient::Exception->new("unexpected response format\n")); + return; + } + $on_response->($res->{data}); + }, + ); +} + +sub get($self, $path, $param, %opts) { + return call_data($self, 'GET', $path, $param, %opts); +} + +sub post($self, $path, $param, %opts) { + return call_data($self, 'POST', $path, $param, %opts); +} + +sub put($self, $path, $param, %opts) { + return call_data($self, 'PUT', $path, $param, %opts); +} + +sub delete($self, $path, $param, %opts) { + return call_data($self, 'DELETE', $path, $param, %opts); +} + +1; diff --git a/src/test/anyevent_client.t b/src/test/anyevent_client.t new file mode 100644 index 0000000..a74939d --- /dev/null +++ b/src/test/anyevent_client.t @@ -0,0 +1,1653 @@ +#!/usr/bin/perl + +use strict; +use warnings; +use feature 'current_sub'; + +use AnyEvent; +use AnyEvent::Handle; +use AnyEvent::HTTP; +use AnyEvent::Socket; +use AnyEvent::TLS; +use Compress::Zlib qw(memGzip); +use File::Temp qw(tempdir); +use JSON qw(to_json); +use Net::SSLeay; +use Scalar::Util qw(weaken); +use Test::More; + +use PVE::APIClient::AnyEvent; +use PVE::APIClient::Exception; + +my $tmpdir = tempdir(CLEANUP => 1); +my $key_file = "$tmpdir/server.key"; +my $cert_file = "$tmpdir/server.crt"; + +my @openssl_cmd = ( + 'openssl', + 'req', + '-x509', + '-newkey', + 'ec', + '-pkeyopt', + 'ec_paramgen_curve:prime256v1', + '-nodes', + '-keyout', + $key_file, + '-out', + $cert_file, + '-days', + '1', + '-subj', + '/CN=127.0.0.1', +); +my $rc; +{ + open(my $saved_err, '>&', \*STDERR) or BAIL_OUT("failed to dup STDERR: $!"); + open(STDERR, '>', '/dev/null') or BAIL_OUT("failed to redirect STDERR: $!"); + $rc = system(@openssl_cmd, '-batch'); + if ($rc != 0) { + # Fallback for older openssl without -batch + $rc = system(@openssl_cmd); + } + open(STDERR, '>&', $saved_err) or BAIL_OUT("failed to restore STDERR: $!"); +} +BAIL_OUT("failed to generate ephemeral test certificate with openssl") if $rc != 0; + +open(my $fp_fh, '-|', 'openssl', 'x509', '-in', $cert_file, '-noout', '-fingerprint', '-sha256') + or BAIL_OUT("failed to compute test certificate fingerprint: $!"); +my $fp_line = <$fp_fh>; +close($fp_fh); +my ($cert_fp) = ($fp_line // '') =~ /([0-9A-Fa-f:]{95})/; +BAIL_OUT("could not parse certificate SHA-256 fingerprint from '$fp_line'") if !$cert_fp; +$cert_fp = uc($cert_fp); + +my $wrong_fp = $cert_fp; +$wrong_fp =~ s/^[0-9A-F]{2}/$wrong_fp =~ m|^00| ? 'FF' : '00'/e; + +my $server_tls = AnyEvent::TLS->new( + cert_file => $cert_file, + key_file => $key_file, +); + +my %slow_hooks; +my $slow_req_seen = 0; +my $slow_eof_seen = 0; +my %active_server_handles; + +my sub send_http_response { + my ($hdl, $status_line, $headers, $body, $keepalive) = @_; + + $body //= ''; + my $resp = "HTTP/1.1 $status_line\r\n"; + $resp .= "Content-Length: " . length($body) . "\r\n"; + $resp .= "Connection: " . ($keepalive ? "keep-alive" : "close") . "\r\n"; + for my $k (sort keys %$headers) { + $resp .= "$k: $headers->{$k}\r\n"; + } + $resp .= "\r\n$body"; + + $hdl->push_write($resp); + $hdl->push_shutdown() if !$keepalive; +} + +my sub dispatch_server_request { + my ($hdl, $id, $method, $target, $headers, $body, $on_keepalive) = @_; + + my ($path, $query) = split(/\?/, $target, 2); + + if ($path eq '/api2/json/keepalive') { + my $payload = to_json({ data => { conn_id => $id } }, { utf8 => 1 }); + send_http_response( + $hdl, + '200 OK', + { 'Content-Type' => 'application/json;charset=UTF-8' }, + $payload, + 1, + ); + $on_keepalive->() if $on_keepalive; + } elsif ($path eq '/api2/json/echo-headers') { + my $payload = to_json( + { + data => { + method => $method, + path => $path, + query => $query, + headers => $headers, + body => $body, + }, + }, + { utf8 => 1 }, + ); + my %resp_hdr = ('Content-Type' => 'application/json;charset=UTF-8'); + if (($headers->{'accept-encoding'} // '') =~ /\bgzip\b/i) { + $payload = memGzip($payload); + $resp_hdr{'Content-Encoding'} = 'gzip'; + } + send_http_response($hdl, '200 OK', \%resp_hdr, $payload); + } elsif ($path eq '/api2/json/gzip-raw') { + my $payload = memGzip(to_json({ data => { hello => 'world' } }, { utf8 => 1 })); + send_http_response( + $hdl, + '200 OK', + { + 'Content-Type' => 'application/json', + 'Content-Encoding' => 'gzip', + }, + $payload, + ); + } elsif ($path eq '/api2/json/error-500') { + my $payload = to_json( + { + data => undef, + errors => { node => 'offline' }, + }, + { utf8 => 1 }, + ); + send_http_response( + $hdl, + '500 Internal Failure', + { 'Content-Type' => 'application/json' }, + $payload, + ); + } elsif ($path eq '/api2/json/plain-text') { + send_http_response($hdl, '200 OK', { 'Content-Type' => 'text/plain' }, 'plain body'); + } elsif ($path eq '/api2/json/bad-json') { + send_http_response( + $hdl, + '200 OK', + { 'Content-Type' => 'application/json' }, + '{not valid json', + ); + } elsif ($path eq '/api2/json/with-total') { + send_http_response( + $hdl, + '200 OK', + { 'Content-Type' => 'application/json' }, + to_json({ data => { ok => 1 }, total => 42 }, { utf8 => 1 }), + ); + } elsif ($path eq '/api2/json/no-data') { + send_http_response( + $hdl, + '200 OK', + { 'Content-Type' => 'application/json' }, + to_json({ total => 0 }, { utf8 => 1 }), + ); + } elsif ($path eq '/api2/json/slow') { + $slow_req_seen++; + $slow_hooks{on_seen}->() if $slow_hooks{on_seen}; + # Keep handle open until client cancels/closes the socket. + $hdl->on_read(sub { }); + $hdl->on_eof(sub { + $slow_eof_seen++; + delete $active_server_handles{$id}; + $slow_hooks{on_eof}->() if $slow_hooks{on_eof}; + }); + $hdl->on_error(sub { + $slow_eof_seen++; + delete $active_server_handles{$id}; + $slow_hooks{on_eof}->() if $slow_hooks{on_eof}; + }); + } else { + send_http_response( + $hdl, + '404 Not Found', + { 'Content-Type' => 'application/json' }, + to_json({ data => undef }, { utf8 => 1 }), + ); + } +} + +my $server_port; +my $next_conn_id = 1; +my $server_guard = tcp_server( + '127.0.0.1', + 0, + sub { + my ($fh) = @_; + my $id = $next_conn_id++; + my $hdl; + $hdl = AnyEvent::Handle->new( + fh => $fh, + tls => 'accept', + tls_ctx => $server_tls, + on_error => sub { + delete $active_server_handles{$id}; + $hdl->destroy() if $hdl; + }, + on_eof => sub { + delete $active_server_handles{$id}; + $hdl->destroy() if $hdl; + }, + ); + $active_server_handles{$id} = $hdl; + + my $read_next; + $read_next = sub { + return if !$active_server_handles{$id}; + $hdl->push_read( + regex => qr/\r?\n\r?\n/, + sub { + my ($h, $raw_hdr) = @_; + my @lines = split(/\r?\n/, $raw_hdr); + my $req_line = shift @lines // ''; + my ($method, $target) = split(/ /, $req_line); + my %headers; + for my $line (@lines) { + if ($line =~ /^([^:]+):\s*(.*)$/) { + $headers{ lc($1) } = $2; + } + } + my $cl = $headers{'content-length'} // 0; + if ($cl > 0) { + $h->push_read( + chunk => $cl, + sub { + my ($h2, $body) = @_; + dispatch_server_request( + $h2, $id, $method, $target, \%headers, $body, $read_next, + ); + }, + ); + } else { + dispatch_server_request( + $h, $id, $method, $target, \%headers, '', $read_next, + ); + } + }, + ); + }; + $read_next->(); + }, + sub { + my (undef, undef, $port) = @_; + $server_port = $port; + }, +); + +ok(defined($server_port) && $server_port > 0, "loopback TLS server listening on port $server_port"); + +my sub run_with_timeout { + my ($cb, $timeout) = @_; + $timeout //= 5; + my $cv = AE::cv; + my $t = AE::timer($timeout, 0, sub { $cv->croak("test timed out after ${timeout}s") }); + $cb->($cv); + return $cv->recv; +} + +subtest 'TLS SHA-256 fingerprint pinning pass, mismatch, and callback' => sub { + my $ok_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my $res = run_with_timeout(sub { + my ($cv) = @_; + $ok_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($res->{ok}, 'valid SHA-256 pinned fingerprint succeeds'); + is( + $res->{data}->{path}, + '/api2/json/echo-headers', + 'request path resolved under /api2/json/', + ); + + my $bad_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $wrong_fp => 1 }, + ); + + my $bad_res = run_with_timeout(sub { + my ($cv) = @_; + $bad_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$bad_res->{ok}, 'mismatched SHA-256 fingerprint is rejected'); + isa_ok($bad_res->{err}, 'PVE::APIClient::Exception'); + ok( + $bad_res->{err}->{code} >= 590 && $bad_res->{err}->{code} <= 599, + 'TLS mismatch yields 59x code', + ); + + my $verify_calls = 0; + my $cb_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + verify_fingerprint_cb => sub { + my ($cert) = @_; + $verify_calls++; + my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256'); + return uc($fp) eq $cert_fp ? 1 : 0; + }, + ); + + for my $i (1 .. 2) { + my $r = run_with_timeout(sub { + my ($cv) = @_; + $cb_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($r->{ok}, "verify_fingerprint_cb request #$i succeeds"); + } + is($verify_calls, 1, 'verified fingerprint is cached across subsequent requests'); + + my $reject_cb_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + verify_fingerprint_cb => sub { return 0; }, + ); + my $rej = run_with_timeout(sub { + my ($cv) = @_; + $reject_cb_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$rej->{ok}, 'verify_fingerprint_cb returning false rejects connection'); + isa_ok($rej->{err}, 'PVE::APIClient::Exception'); +}; + +subtest 'IPv6 URI host bracketing' => sub { + my @captured_urls; + no warnings 'redefine'; + local *AnyEvent::HTTP::http_request = sub { + my $cb = pop @_; + my ($method, $url, %args) = @_; + push @captured_urls, "$method $url"; + $cb->('{"data":1}', { Status => 200, 'content-type' => 'application/json' }); + return undef; + }; + + my $v6 = PVE::APIClient::AnyEvent->new( + host => '2001:db8::1', + port => 8006, + protocol => 'http', + ); + my $got; + $v6->get( + 'nodes', + { full => 1 }, + on_response => sub { $got = $_[0] }, + on_error => sub { fail("unexpected error: $_[0]") }, + ); + is($got, 1, 'IPv6 request delivered response'); + is( + $captured_urls[0], + 'GET http://[2001:db8::1]:8006/api2/json/nodes?full=1', + 'unbracketed IPv6 host is bracketed in URI', + ); + + my $v6_bracketed = PVE::APIClient::AnyEvent->new( + host => '[::1]', + port => 8006, + protocol => 'http', + ); + $v6_bracketed->get( + '/api2/extjs/version', + undef, + on_response => sub { }, + on_error => sub { fail("unexpected error: $_[0]") }, + ); + is( + $captured_urls[1], + 'GET http://[::1]:8006/api2/extjs/version', + 'pre-bracketed IPv6 host and explicit /api2/ path handled cleanly', + ); +}; + +subtest 'auth headers, custom headers, and POST form encoding' => sub { + my $tok_bare = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + api_token => 'root@pam!tok=secret-val', + headers => { PVEDisableProxy => '1' }, + ); + my $r1 = run_with_timeout(sub { + my ($cv) = @_; + $tok_bare->get( + 'echo-headers', + undef, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is( + $r1->{headers}->{authorization}, + 'PVEAPIToken=root@pam!tok=secret-val', + 'bare api_token gets default PVEAPIToken= prefix', + ); + is($r1->{headers}->{pvedisableproxy}, '1', 'custom default header sent'); + + my $tok_prefixed = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + apitoken => 'PVEAPIToken=root@pam!tok=already-prefixed', + ); + my $r2 = run_with_timeout(sub { + my ($cv) = @_; + $tok_prefixed->get( + 'echo-headers', + undef, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is( + $r2->{headers}->{authorization}, + 'PVEAPIToken=root@pam!tok=already-prefixed', + 'prefixed apitoken is preserved without double prefix', + ); + + my $ticket_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ticket => 'PVE:root@pam:ABC+1/2', + csrftoken => 'csrf-token-xyz', + ); + my $r3 = run_with_timeout(sub { + my ($cv) = @_; + $ticket_client->call( + 'POST', + 'echo-headers', + { key => 'val 1' }, + headers => { 'X-Extra' => 'yes' }, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + like( + $r3->{data}->{headers}->{cookie}, + qr/^PVEAuthCookie=PVE%3Aroot%40pam%3AABC%2B1%2F2;/, + 'ticket sent as URL-encoded cookie', + ); + is( + $r3->{data}->{headers}->{csrfpreventiontoken}, + 'csrf-token-xyz', + 'CSRFPreventionToken header sent', + ); + is($r3->{data}->{headers}->{'x-extra'}, 'yes', 'per-request custom header sent'); + is( + $r3->{data}->{headers}->{'content-type'}, + 'application/x-www-form-urlencoded', + 'POST sets form-urlencoded Content-Type', + ); + is($r3->{data}->{body}, 'key=val+1', 'POST encodes param hashref into body'); +}; + +subtest 'request_raw undecoded gzip wire bytes vs get/call decoding' => sub { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my $raw_res = run_with_timeout(sub { + my ($cv) = @_; + $client->request_raw( + 'GET', + 'gzip-raw', + undef, + headers => { 'Accept-Encoding' => 'gzip' }, + on_response => sub { + my ($status, $body_ref, $hdr) = @_; + $cv->send({ status => $status, body => $$body_ref, hdr => $hdr }); + }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is($raw_res->{status}, 200, 'request_raw receives HTTP 200'); + is($raw_res->{hdr}->{'content-encoding'}, 'gzip', 'request_raw preserves content-encoding'); + is( + substr($raw_res->{body}, 0, 2), + "\x1f\x8b", + 'request_raw returns undecoded gzip wire bytes', + ); + + my $wire_copy = $raw_res->{body}; + my $decoded = PVE::APIClient::AnyEvent::decode_json_body(\$wire_copy, 1); + is_deeply( + $decoded, + { data => { hello => 'world' } }, + 'decode_json_body decodes gzipped JSON', + ); + is($wire_copy, $raw_res->{body}, 'decode_json_body does not mutate caller scalar'); + + my $data = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'gzip-raw', + undef, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is_deeply($data, { hello => 'world' }, 'get() gunzips and returns decoded data field'); +}; + +subtest 'HTTP 500 JSON errors, bad content-type/JSON, and transport errors' => sub { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my $err500 = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'error-500', + undef, + on_response => sub { $cv->croak('expected error') }, + on_error => sub { $cv->send($_[0]) }, + ); + }); + isa_ok($err500, 'PVE::APIClient::Exception'); + is($err500->{code}, 500, 'HTTP 500 exception preserves status code'); + is_deeply( + $err500->{errors}, + { node => 'offline' }, + 'HTTP 500 exception preserves JSON errors', + ); + + my $err_ct = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'plain-text', + undef, + on_response => sub { $cv->croak('expected error') }, + on_error => sub { $cv->send($_[0]) }, + ); + }); + isa_ok($err_ct, 'PVE::APIClient::Exception'); + like("$err_ct", qr/unexpected content type/, 'non-JSON content-type rejected in call()'); + + my $err_json = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'bad-json', + undef, + on_response => sub { $cv->croak('expected error') }, + on_error => sub { $cv->send($_[0]) }, + ); + }); + isa_ok($err_json, 'PVE::APIClient::Exception'); + is($err_json->{code}, 200, 'invalid JSON yields PVE::APIClient::Exception'); + + # Find an unbound port by binding and immediately closing a socket. + my $closed_port; + { + my $tmp_guard = tcp_server( + '127.0.0.1', + 0, + sub { }, + sub { my (undef, undef, $p) = @_; $closed_port = $p; }, + ); + } + my $refused_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $closed_port, + protocol => 'http', + ); + my $err_conn = run_with_timeout(sub { + my ($cv) = @_; + $refused_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->croak('expected connection error') }, + on_error => sub { $cv->send($_[0]) }, + ); + }); + isa_ok($err_conn, 'PVE::APIClient::Exception'); + ok($err_conn->{code} >= 590 && $err_conn->{code} <= 599, 'transport error yields 59x code'); + + my $bad_method_err; + my $deferred_cv = AE::cv; + my $deferred_timeout = + AE::timer(5, 0, sub { $deferred_cv->croak('deferred setup error timed out') }); + $client->request_raw( + 'PATCH', + 'echo-headers', + undef, + on_response => sub { fail('unexpected response') }, + on_error => sub { + $bad_method_err = $_[0]; + $deferred_cv->send(1); + }, + ); + is($bad_method_err, undef, 'setup error is deferred until after request_raw returns'); + $deferred_cv->recv; + undef $deferred_timeout; + isa_ok($bad_method_err, 'PVE::APIClient::Exception'); + like( + "$bad_method_err", + qr/not implemented/, + 'unsupported method yields deferred exception', + ); + + my $suppressed_err = 0; + my $cancel_deferred = $client->request_raw( + 'PATCH', + 'echo-headers', + undef, + on_response => sub { $suppressed_err++ }, + on_error => sub { $suppressed_err++ }, + ); + $cancel_deferred->(); + run_with_timeout(sub { + my ($cv) = @_; + my $t; + $t = AE::timer(0.03, 0, sub { undef $t; $cv->send(1) }); + }); + is($suppressed_err, 0, 'immediate cancel suppresses deferred setup error'); +}; + +subtest 'cancellation aborts in-flight loopback socket cleanly' => sub { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my $terminal_called = 0; + my $cancel; + my $eof_cv = AE::cv; + my $timeout = + AE::timer(5, 0, sub { $eof_cv->croak('server did not see EOF after cancel') }); + + %slow_hooks = ( + on_seen => sub { + $cancel->(); + $cancel->(); # idempotent second call + }, + on_eof => sub { + $eof_cv->send(1); + }, + ); + + $cancel = $client->get( + 'slow', + undef, + on_response => sub { $terminal_called++ }, + on_error => sub { $terminal_called++ }, + ); + + ok($eof_cv->recv, 'server observed EOF after client cancellation'); + %slow_hooks = (); + undef $timeout; + + # Drain one short timer tick to confirm no delayed terminal callback fires. + run_with_timeout(sub { + my ($cv) = @_; + my $t; + $t = AE::timer(0.05, 0, sub { undef $t; $cv->send(1) }); + }); + is($terminal_called, 0, 'cancelled request fires neither on_response nor on_error'); +}; + +subtest 'single terminal outcome and sync/async callback exception isolation' => sub { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my @warnings; + local $SIG{__WARN__} = sub { push @warnings, @_ }; + + my $on_error_calls = 0; + run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'echo-headers', + undef, + on_response => sub { + my $t; + $t = AE::timer(0.02, 0, sub { undef $t; $cv->send(1) }); + die "async response boom\n"; + }, + on_error => sub { $on_error_calls++ }, + ); + }); + is($on_error_calls, 0, 'async on_response exception does not invoke on_error'); + ok(scalar(grep { /async response boom/ } @warnings) == 1, + 'async callback exception warned'); + + @warnings = (); + my $sync_err_calls = 0; + { + no warnings 'redefine'; + local *AnyEvent::HTTP::http_request = sub { + my $cb = pop @_; + $cb->('{"data":42}', { Status => 200, 'content-type' => 'application/json' }); + return undef; + }; + $client->get( + 'echo-headers', + undef, + on_response => sub { die "sync response boom\n" }, + on_error => sub { $sync_err_calls++ }, + ); + } + is($sync_err_calls, 0, 'sync on_response exception does not invoke on_error'); + ok(scalar(grep { /sync response boom/ } @warnings) == 1, 'sync response exception warned'); + + @warnings = (); + my $sync_on_error_calls = 0; + { + no warnings 'redefine'; + local *AnyEvent::HTTP::http_request = sub { + my $cb = pop @_; + $cb->(undef, { Status => 596, Reason => 'sync fail' }); + return undef; + }; + $client->get( + 'echo-headers', + undef, + on_response => sub { fail('unexpected response') }, + on_error => sub { + $sync_on_error_calls++; + die "sync error boom\n"; + }, + ); + } + is($sync_on_error_calls, 1, 'sync on_error exception does not trigger second on_error'); + ok(scalar(grep { /sync error boom/ } @warnings) == 1, 'sync error exception warned'); +}; + +subtest 'weakened-ref destruction (no reference cycles)' => sub { + my ($w_client, $w_cancel, $w_cb_token); + { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + my $cb_token = { sentinel => 1 }; + $w_client = $client; + $w_cb_token = $cb_token; + weaken($w_client); + weaken($w_cb_token); + + my $cancel; + run_with_timeout(sub { + my ($cv) = @_; + $cancel = $client->get( + 'echo-headers', + undef, + on_response => sub { + my $keep = $cb_token; + $cv->send(1); + }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + $w_cancel = $cancel; + weaken($w_cancel); + } + + is($w_client, undef, 'client object freed without reference cycles'); + is($w_cancel, undef, 'cancel coderef freed without reference cycles'); + is($w_cb_token, undef, 'callback captures freed without reference cycles'); +}; + +subtest 'persistent TLS connection cache isolation per client instance' => sub { + my $good_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + persistent => 1, + keepalive => 1, + ); + my $bad_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $wrong_fp => 1 }, + persistent => 1, + keepalive => 1, + ); + + my $r1 = run_with_timeout(sub { + my ($cv) = @_; + $good_client->get( + 'keepalive', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($r1->{ok}, 'persistent valid-pin client request #1 succeeds'); + my $conn1 = $r1->{data}->{conn_id}; + + my $r2 = run_with_timeout(sub { + my ($cv) = @_; + $good_client->get( + 'keepalive', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($r2->{ok}, 'persistent valid-pin client request #2 succeeds'); + is($r2->{data}->{conn_id}, $conn1, 'same persistent client reuses its own TLS connection'); + + my $r_bad = run_with_timeout(sub { + my ($cv) = @_; + $bad_client->get( + 'keepalive', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$r_bad->{ok}, 'persistent wrong-pin client cannot reuse cached TLS connection'); + isa_ok($r_bad->{err}, 'PVE::APIClient::Exception'); + ok( + $r_bad->{err}->{code} >= 590 && $r_bad->{err}->{code} <= 599, + 'wrong-pin client fails TLS verification with 59x error', + ); +}; + +subtest 'protocol normalization and validation' => sub { + eval { + PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + protocol => 'ftp', + ); + }; + like($@, qr/unsupported protocol 'ftp'/, 'unsupported protocol croaks'); + + my $upper_bad = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + protocol => 'HTTPS', + cached_fingerprints => { $wrong_fp => 1 }, + ); + my $bad_res = run_with_timeout(sub { + my ($cv) = @_; + $upper_bad->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$bad_res->{ok}, 'uppercase HTTPS protocol enforces TLS fingerprint pin'); + + my $upper_ok = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + protocol => 'HTTPS', + cached_fingerprints => { $cert_fp => 1 }, + ); + my $ok_res = run_with_timeout(sub { + my ($cv) = @_; + $upper_ok->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($ok_res->{ok}, 'uppercase HTTPS protocol succeeds with valid pin'); +}; + +subtest 'case-insensitive header merging' => sub { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + api_token => 'root@pam!tok=from-ctor', + headers => { authorization => 'PVEAPIToken=should-lose' }, + ); + + my $ctor_res = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is( + $ctor_res->{headers}->{authorization}, + 'PVEAPIToken=root@pam!tok=from-ctor', + 'constructor api_token overrides lowercase authorization in constructor headers', + ); + + my $override_ok = 0; + for my $i (1 .. 10) { + my $r = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'echo-headers', + undef, + headers => { authorization => "PVEAPIToken=override-$i" }, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + $override_ok++ if ($r->{headers}->{authorization} // '') eq "PVEAPIToken=override-$i"; + } + is( + $override_ok, + 10, + 'per-request lowercase authorization override deterministically wins across 10 requests', + ); +}; + +subtest 'fail-closed TLS verification callbacks' => sub { + my @warnings; + local $SIG{__WARN__} = sub { push @warnings, @_ }; + + my $fp_throw_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + verify_fingerprint_cb => sub { die "fp verify boom\n" }, + ); + my $r1 = eval { + run_with_timeout(sub { + my ($cv) = @_; + $fp_throw_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + }; + is($@, '', 'throwing verify_fingerprint_cb does not escape event loop'); + ok($r1 && !$r1->{ok}, 'throwing verify_fingerprint_cb fails closed into on_error'); + isa_ok($r1->{err}, 'PVE::APIClient::Exception'); + ok( + scalar(grep { /fp verify boom/ } @warnings) >= 1, + 'throwing verify_fingerprint_cb warned', + ); + + @warnings = (); + my $custom_cb_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + ssl_opts => { + verify_cb => sub { die "custom verify_cb boom\n" }, + }, + ); + my $r2 = eval { + run_with_timeout(sub { + my ($cv) = @_; + $custom_cb_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + }; + is($@, '', 'throwing custom ssl_opts verify_cb does not escape event loop'); + ok($r2 && !$r2->{ok}, 'throwing custom ssl_opts verify_cb fails closed into on_error'); + isa_ok($r2->{err}, 'PVE::APIClient::Exception'); + ok( + scalar(grep { /custom verify_cb boom/ } @warnings) >= 1, + 'throwing custom ssl_opts verify_cb warned', + ); +}; + +subtest 'call() envelope vs get/post/put/delete helpers and body+param guard' => sub { + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my $envelope = run_with_timeout(sub { + my ($cv) = @_; + $client->call( + 'GET', + 'with-total', + undef, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is_deeply( + $envelope, + { data => { ok => 1 }, total => 42 }, + 'call() delivers full decoded JSON envelope', + ); + + my $get_data = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'with-total', + undef, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is_deeply($get_data, { ok => 1 }, 'get() extracts data field from envelope'); + + my $post_data = run_with_timeout(sub { + my ($cv) = @_; + $client->post( + 'echo-headers', + { a => '1' }, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is($post_data->{method}, 'POST', 'post() sends POST and unwraps data'); + is($post_data->{body}, 'a=1', 'post() encodes form parameters'); + + my $put_data = run_with_timeout(sub { + my ($cv) = @_; + $client->put( + 'echo-headers', + { b => '2' }, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is($put_data->{method}, 'PUT', 'put() sends PUT and unwraps data'); + is($put_data->{body}, 'b=2', 'put() encodes form parameters'); + + my $delete_data = run_with_timeout(sub { + my ($cv) = @_; + $client->delete( + 'echo-headers', + { c => '3' }, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is($delete_data->{method}, 'DELETE', 'delete() sends DELETE and unwraps data'); + is($delete_data->{query}, 'c=3', 'delete() encodes query parameters'); + + my $missing_data_err = run_with_timeout(sub { + my ($cv) = @_; + $client->get( + 'no-data', + undef, + on_response => sub { $cv->croak('expected unexpected response format error') }, + on_error => sub { $cv->send($_[0]) }, + ); + }); + isa_ok($missing_data_err, 'PVE::APIClient::Exception'); + like( + "$missing_data_err", + qr/unexpected response format/, + 'missing data key errors in get()', + ); + + for my $m (qw(POST PUT)) { + eval { + $client->request_raw( + $m, + 'echo-headers', + { a => 1 }, + body => 'raw-payload', + on_response => sub { }, + on_error => sub { }, + ); + }; + like($@, qr/cannot pass both body and param/, "$m with both body and param croaks"); + } + + my $raw_post = run_with_timeout(sub { + my ($cv) = @_; + $client->post( + 'echo-headers', + undef, + body => 'raw-payload', + headers => { 'Content-Type' => 'text/plain' }, + on_response => sub { $cv->send($_[0]) }, + on_error => sub { $cv->croak("err: $_[0]") }, + ); + }); + is($raw_post->{body}, 'raw-payload', 'POST with body and undef param succeeds'); +}; + +subtest 'CA and hostname verification, custom verify_cb, and verify_fingerprint_cb fallback' => + sub { + my $run_openssl = sub { + my (@cmd) = @_; + open(my $saved_err, '>&', \*STDERR) or BAIL_OUT("failed to dup STDERR: $!"); + open(STDERR, '>', '/dev/null') or BAIL_OUT("failed to redirect STDERR: $!"); + my $res = system('openssl', @cmd); + open(STDERR, '>&', $saved_err) or BAIL_OUT("failed to restore STDERR: $!"); + BAIL_OUT("openssl @cmd failed with rc=$res") if $res != 0; + }; + + my $ca_key = "$tmpdir/ca.key"; + my $ca_crt = "$tmpdir/ca.crt"; + $run_openssl->( + 'req', + '-x509', + '-newkey', + 'ec', + '-pkeyopt', + 'ec_paramgen_curve:prime256v1', + '-nodes', + '-keyout', + $ca_key, + '-out', + $ca_crt, + '-days', + '1', + '-subj', + '/CN=PVE-Test-CA', + '-addext', + 'basicConstraints=critical,CA:TRUE', + '-addext', + 'keyUsage=critical,keyCertSign,cRLSign', + ); + + my $sign_leaf = sub { + my ($prefix, $cn, $san) = @_; + my $k = "$tmpdir/$prefix.key"; + my $csr = "$tmpdir/$prefix.csr"; + my $crt = "$tmpdir/$prefix.crt"; + my $ext = "$tmpdir/$prefix.ext"; + open(my $efh, '>', $ext) or BAIL_OUT("failed to write $ext: $!"); + print {$efh} "basicConstraints=CA:FALSE\n"; + print {$efh} "extendedKeyUsage=serverAuth\n"; + print {$efh} "subjectAltName=$san\n"; + close($efh); + + $run_openssl->( + 'req', + '-new', + '-newkey', + 'ec', + '-pkeyopt', + 'ec_paramgen_curve:prime256v1', + '-nodes', + '-keyout', + $k, + '-out', + $csr, + '-subj', + "/CN=$cn", + ); + $run_openssl->( + 'x509', + '-req', + '-in', + $csr, + '-CA', + $ca_crt, + '-CAkey', + $ca_key, + '-CAcreateserial', + '-out', + $crt, + '-days', + '1', + '-extfile', + $ext, + ); + return ($crt, $k); + }; + + my ($good_crt, $good_key) = $sign_leaf->( + 'good_host', 'localhost', 'DNS:localhost,IP:127.0.0.1', + ); + my ($wrong_crt, $wrong_key) = $sign_leaf->( + 'wrong_host', 'other.example.test', 'DNS:other.example.test', + ); + + my $start_leaf_server = sub { + my ($crt, $key) = @_; + my $tls = AnyEvent::TLS->new(cert_file => $crt, key_file => $key); + my %hdls; + my $port; + my $guard = tcp_server( + '127.0.0.1', + 0, + sub { + my ($fh) = @_; + my $id = "$fh"; + my $hdl; + $hdl = AnyEvent::Handle->new( + fh => $fh, + tls => 'accept', + tls_ctx => $tls, + on_error => sub { + delete $hdls{$id}; + $hdl->destroy() if $hdl; + }, + on_eof => sub { + delete $hdls{$id}; + $hdl->destroy() if $hdl; + }, + ); + $hdls{$id} = $hdl; + $hdl->push_read( + regex => qr/\r?\n\r?\n/, + sub { + my ($h) = @_; + send_http_response( + $h, + '200 OK', + { 'Content-Type' => 'application/json' }, + to_json({ data => { ok => 1 } }, { utf8 => 1 }), + ); + }, + ); + }, + sub { + my (undef, undef, $p) = @_; + $port = $p; + }, + ); + return ($guard, $port, \%hdls); + }; + + my ($good_guard, $good_port, $good_hdls) = $start_leaf_server->($good_crt, $good_key); + my ($wrong_guard, $wrong_port, $wrong_hdls) = $start_leaf_server->($wrong_crt, $wrong_key); + + # 1. Trusted CA + matching hostname succeeds; mismatched hostname fails. + my $ca_ok = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $good_port, + ssl_opts => { ca_file => $ca_crt }, + ); + my $r_ca_ok = run_with_timeout(sub { + my ($cv) = @_; + $ca_ok->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1, data => $_[0] }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($r_ca_ok->{ok}, 'trusted CA with matching hostname succeeds'); + + my $ca_mismatch = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $wrong_port, + ssl_opts => { ca_file => $ca_crt }, + ); + my $r_ca_mismatch = run_with_timeout(sub { + my ($cv) = @_; + $ca_mismatch->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$r_ca_mismatch->{ok}, 'trusted CA with mismatched hostname is rejected'); + isa_ok($r_ca_mismatch->{err}, 'PVE::APIClient::Exception'); + + # 2. Custom verify_cb with verify_hostname => 1 enforces hostname verification. + my $custom_ok = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $good_port, + ssl_opts => { + ca_file => $ca_crt, + verify_hostname => 1, + verify_cb => sub { return $_[4] }, + }, + ); + my $r_custom_ok = run_with_timeout(sub { + my ($cv) = @_; + $custom_ok->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok( + $r_custom_ok->{ok}, + 'custom verify_cb with verify_hostname => 1 accepts matching hostname', + ); + + my $custom_mismatch = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $wrong_port, + ssl_opts => { + ca_file => $ca_crt, + verify_hostname => 1, + verify_cb => sub { return $_[4] }, + }, + ); + my $r_custom_mismatch = run_with_timeout(sub { + my ($cv) = @_; + $custom_mismatch->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok( + !$r_custom_mismatch->{ok}, + 'custom verify_cb with verify_hostname => 1 rejects mismatched hostname', + ); + + # 3. verify_fingerprint_cb-only client trusts valid CA+hostname without invoking callback, + # and falls back to verify_fingerprint_cb for untrusted or mismatched certs. + my $fp_cb_ca_calls = 0; + my $fp_ca_client = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $good_port, + ssl_opts => { ca_file => $ca_crt }, + verify_fingerprint_cb => sub { + $fp_cb_ca_calls++; + return 0; + }, + ); + my $r_fp_ca = run_with_timeout(sub { + my ($cv) = @_; + $fp_ca_client->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($r_fp_ca->{ok}, 'verify_fingerprint_cb-only client trusts valid CA+hostname cert'); + is( + $fp_cb_ca_calls, + 0, + 'verify_fingerprint_cb is not called when CA and hostname verification succeed', + ); + + my $fp_cb_mismatch_calls = 0; + my $fp_mismatch_client = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $wrong_port, + ssl_opts => { ca_file => $ca_crt }, + verify_fingerprint_cb => sub { + $fp_cb_mismatch_calls++; + return 0; + }, + ); + my $r_fp_mismatch = run_with_timeout(sub { + my ($cv) = @_; + $fp_mismatch_client->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$r_fp_mismatch->{ok}, 'verify_fingerprint_cb-only client rejects mismatched hostname'); + is( + $fp_cb_mismatch_calls, 1, 'hostname mismatch falls back to verify_fingerprint_cb', + ); + + my $fp_cb_self_calls = 0; + my $fp_self_client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $server_port, + ssl_opts => { ca_file => $ca_crt }, + verify_fingerprint_cb => sub { + my ($cert) = @_; + $fp_cb_self_calls++; + my $fp = Net::SSLeay::X509_get_fingerprint($cert, 'sha256'); + return uc($fp) eq $cert_fp ? 1 : 0; + }, + ); + my $r_fp_self = run_with_timeout(sub { + my ($cv) = @_; + $fp_self_client->get( + 'echo-headers', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok($r_fp_self->{ok}, 'verify_fingerprint_cb-only client falls back for self-signed cert'); + is( + $fp_cb_self_calls, + 1, + 'verify_fingerprint_cb invoked once for untrusted self-signed cert', + ); + + # 4. Disabling verify_hostname without pins or verify_cb fails closed before connecting. + my $unpinned_conns = 0; + my $unpinned_port; + my $unpinned_guard = tcp_server( + '127.0.0.1', + 0, + sub { + my ($fh) = @_; + $unpinned_conns++; + close($fh); + }, + sub { + my (undef, undef, $p) = @_; + $unpinned_port = $p; + }, + ); + my $insecure_client = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $unpinned_port, + api_token => 'root@pam!tok=never-send-me', + ssl_opts => { ca_file => $ca_crt, verify_hostname => 0 }, + ); + my $r_insecure = run_with_timeout(sub { + my ($cv) = @_; + $insecure_client->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok( + !$r_insecure->{ok}, + 'verify_hostname => 0 without pins or verify_cb fails closed via on_error', + ); + isa_ok($r_insecure->{err}, 'PVE::APIClient::Exception'); + like( + "$r_insecure->{err}", + qr/cannot disable verify_hostname/, + 'fail-closed error explains missing pin/callback requirement', + ); + is($unpinned_conns, 0, 'no TCP connection or credentials sent when failing closed'); + + # 5. ssl_opts => { verify => 0 } fails closed even with cached_fingerprints or verify_fingerprint_cb. + my $verify_zero_pinned = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $unpinned_port, + api_token => 'root@pam!tok=never-send-me', + cached_fingerprints => { $cert_fp => 1 }, + ssl_opts => { verify => 0 }, + ); + my $r_v0_pinned = run_with_timeout(sub { + my ($cv) = @_; + $verify_zero_pinned->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok( + !$r_v0_pinned->{ok}, + 'ssl_opts verify => 0 with cached_fingerprints fails closed via on_error', + ); + isa_ok($r_v0_pinned->{err}, 'PVE::APIClient::Exception'); + like( + "$r_v0_pinned->{err}", + qr/verify => 0/, + 'verify => 0 error reports disabled TLS verification', + ); + + my $verify_zero_cb = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $unpinned_port, + api_token => 'root@pam!tok=never-send-me', + verify_fingerprint_cb => sub { return 1 }, + ssl_opts => { verify => 0 }, + ); + my $r_v0_cb = run_with_timeout(sub { + my ($cv) = @_; + $verify_zero_cb->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok( + !$r_v0_cb->{ok}, + 'ssl_opts verify => 0 with verify_fingerprint_cb fails closed via on_error', + ); + isa_ok($r_v0_cb->{err}, 'PVE::APIClient::Exception'); + + # 6. Conflicting verify_hostname => 1 with verify_peername => 'none' fails closed. + my $conflict_client = PVE::APIClient::AnyEvent->new( + host => 'localhost', + port => $unpinned_port, + api_token => 'root@pam!tok=never-send-me', + ssl_opts => { + ca_file => $ca_crt, + verify_hostname => 1, + verify_peername => 'none', + }, + ); + my $r_conflict = run_with_timeout(sub { + my ($cv) = @_; + $conflict_client->get( + 'version', + undef, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok( + !$r_conflict->{ok}, + 'verify_hostname => 1 with verify_peername => none fails closed via on_error', + ); + isa_ok($r_conflict->{err}, 'PVE::APIClient::Exception'); + like( + "$r_conflict->{err}", + qr/conflicting ssl_opts/, + 'conflicting verify_hostname/verify_peername error is explicit', + ); + is($unpinned_conns, 0, 'no TCP connections opened for verify => 0 or conflicting ssl_opts'); + undef $unpinned_guard; + + undef $good_guard; + undef $wrong_guard; + %$good_hdls = (); + %$wrong_hdls = (); + }; + +subtest 'outbound header injection validation' => sub { + my $hdr_conns = 0; + my $hdr_port; + my $hdr_guard = tcp_server( + '127.0.0.1', + 0, + sub { + my ($fh) = @_; + $hdr_conns++; + close($fh); + }, + sub { + my (undef, undef, $p) = @_; + $hdr_port = $p; + }, + ); + + my @bad_ctor_cases = ( + ['default header name with CRLF', { headers => { "X-Bad\r\nInject" => 'v' } }], + ['default header name with space', { headers => { 'X Bad' => 'v' } }], + [ + 'default header value with CRLF', + { headers => { 'X-Test' => "ok\r\nX-Injected: 1" } }, + ], + ['default header value with NUL', { headers => { 'X-Test' => "ok\0bad" } }], + ['api_token with CRLF', { api_token => "root\@pam!t=sec\r\nX-Injected: 1" }], + ['api_token with NUL', { api_token => "root\@pam!t=sec\0bad" }], + ['csrftoken with CRLF', { csrftoken => "tok\r\nX-Injected: 1" }], + ['csrftoken with NUL', { csrftoken => "tok\0bad" }], + [ + 'cookie_name with CRLF', + { cookie_name => "Bad\r\nCookie", ticket => 'PVE:root@pam:abc' }, + ], + [ + 'cookie_name with NUL', + { cookie_name => "Bad\0Cookie", ticket => 'PVE:root@pam:abc' }, + ], + ); + + for my $case (@bad_ctor_cases) { + my ($label, $extra) = @$case; + eval { + PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $hdr_port, + cached_fingerprints => { $cert_fp => 1 }, + %$extra, + ); + }; + like($@, qr/invalid HTTP header/, "new() rejects $label"); + } + + my $client = PVE::APIClient::AnyEvent->new( + host => '127.0.0.1', + port => $hdr_port, + cached_fingerprints => { $cert_fp => 1 }, + ); + + my @bad_req_cases = ( + ['per-request header name with CRLF', { "X-Bad\r\nInject" => 'v' }], + ['per-request header name with NUL', { "X-Bad\0Name" => 'v' }], + ['per-request header value with CRLF', { 'X-Test' => "v\r\nX-Injected: 1" }], + ['per-request header value with LF', { 'X-Test' => "v\nX-Injected: 1" }], + ['per-request header value with NUL', { 'X-Test' => "v\0bad" }], + ); + + for my $case (@bad_req_cases) { + my ($label, $headers) = @$case; + my $res = run_with_timeout(sub { + my ($cv) = @_; + $client->request_raw( + 'GET', + 'version', + undef, + headers => $headers, + on_response => sub { $cv->send({ ok => 1 }) }, + on_error => sub { $cv->send({ ok => 0, err => $_[0] }) }, + ); + }); + ok(!$res->{ok}, "request_raw rejects $label via on_error"); + isa_ok($res->{err}, 'PVE::APIClient::Exception'); + like("$res->{err}", qr/invalid HTTP header/, "error text identifies $label"); + } + + is($hdr_conns, 0, 'no TCP connections opened for rejected per-request headers'); + undef $hdr_guard; +}; + +undef $server_guard; +%active_server_handles = (); + +done_testing(); -- 2.47.3