From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH apiclient v2 4/9] add non-blocking AnyEvent API client
Date: Tue, 1 Dec 2026 11:18:59 +0100 [thread overview]
Message-ID: <20261201101913.1885484-5-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com>
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 <t.lamprecht@proxmox.com>
---
Changes in v2:
- Derive one effective TLS peername policy in build_tls_ctx(), validate
verify_peername against %AnyEvent::TLS::CN_SCHEME (normalizing case),
reject verify => 0, and reject combining verify_cb with fingerprint
pinning; clarify fingerprint fallback comment (verify_fingerprint_cb).
- Reject CR, LF, and NUL and encode bare api_token credentials
(preserving literal TOKENID: and percent-encoding only the secret for
PBSAPIToken/PDMAPIToken, and URI-escaping bare PVE tokens including
user IDs with '=', ';', or '%') while leaving explicit scheme headers
untouched.
- Anchor HTTP method validation with \A...\z in request_raw() so
trailing newlines are rejected.
- Route HTTP 200 ExtJS failures (success: 0) to on_error in
get()/post()/put()/delete() with their status, message, and errors
hash while keeping call() delivering the full envelope to on_response.
- Defer invalid per-request header errors from call() to on_error and
expand unit tests (including issuer-depth TLS failure, trailing-
newline methods, and PBS/PDM bare token parsing).
Makefile | 4 +
debian/control | 12 +-
src/Makefile | 7 +-
src/PVE/APIClient/AnyEvent.pm | 574 ++++++++++
src/test/anyevent_client.t | 1974 +++++++++++++++++++++++++++++++++
5 files changed, 2569 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 <support@proxmox.com>
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..3d99d98
--- /dev/null
+++ b/src/PVE/APIClient/AnyEvent.pm
@@ -0,0 +1,574 @@
+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. With cached_fingerprints, peer-name verification defaults to off
+# (leaf fingerprint check only); when peer-name verification is active, a valid chain and
+# matching name suffice, with cached_fingerprints and verify_fingerprint_cb used as fallbacks.
+# - 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 is_peername_disabled($verify_peername) {
+ return 1 if !defined($verify_peername);
+ return 0 if ref($verify_peername);
+ return $verify_peername eq '' || lc($verify_peername) eq 'none' ? 1 : 0;
+}
+
+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 $has_explicit_vh = exists($ssl_opts{verify_hostname});
+ my $explicit_vh = $has_explicit_vh ? ($ssl_opts{verify_hostname} ? 1 : 0) : undef;
+ delete $ssl_opts{verify_hostname};
+
+ my $has_explicit_vp = exists($ssl_opts{verify_peername});
+ if ($has_explicit_vp) {
+ my $vp = $ssl_opts{verify_peername};
+ my $vp_ref = ref($vp);
+ if (
+ !defined($vp)
+ || ($vp_ref && $vp_ref ne 'CODE' && $vp_ref ne 'ARRAY')
+ || ($vp_ref eq 'ARRAY' && scalar(@$vp) < 3)
+ ) {
+ die PVE::APIClient::Exception->new("invalid ssl_opts->{verify_peername}\n");
+ }
+ if (!$vp_ref) {
+ # AnyEvent::TLS::verify_hostname silently returns 1 for any string not in %CN_SCHEME.
+ my $scheme = lc($vp);
+ if (!exists($AnyEvent::TLS::CN_SCHEME{$scheme})) {
+ die PVE::APIClient::Exception->new("invalid ssl_opts->{verify_peername}\n");
+ }
+ $ssl_opts{verify_peername} = $scheme;
+ }
+ my $vp_disabled = is_peername_disabled($ssl_opts{verify_peername});
+ if ($has_explicit_vh && $explicit_vh && $vp_disabled) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: verify_hostname => 1 with verify_peername => 'none'\n");
+ }
+ if ($has_explicit_vh && !$explicit_vh && !$vp_disabled) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: verify_hostname => 0 with active verify_peername\n");
+ }
+ }
+
+ if (defined($ssl_opts{verify_cb})) {
+ if (ref($ssl_opts{verify_cb}) ne 'CODE') {
+ die PVE::APIClient::Exception->new("ssl_opts->{verify_cb} must be a CODE ref\n");
+ }
+ if ($has_fp_pinning) {
+ die PVE::APIClient::Exception->new(
+ "conflicting ssl_opts: cannot combine verify_cb with cached_fingerprints or verify_fingerprint_cb\n"
+ );
+ }
+ }
+
+ my %tls_args = (
+ method => 'any',
+ sslv2 => 0,
+ sslv3 => 0,
+ dh => undef,
+ %ssl_opts,
+ verify => 1,
+ );
+
+ 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';
+ }
+
+ if (!$has_explicit_vp) {
+ # Match LWP.pm: purely trust configured cached fingerprints by default, otherwise enforce
+ # hostname verification (falling back to verify_fingerprint_cb for untrusted certs).
+ my $want_hostname = $explicit_vh // ($has_cached_fp ? 0 : 1);
+ $tls_args{verify_peername} = $want_hostname ? 'https' : 'none';
+ }
+
+ # Single effective peername policy matching AnyEvent::TLS::_verify_hostname (lc ne 'none').
+ my $verify_peername = is_peername_disabled($tls_args{verify_peername}) ? 0 : 1;
+
+ if (!$verify_peername && !$has_fp_pinning && !$tls_args{verify_cb}) {
+ 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_peername && !$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_peername && $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 ? 1 : 0 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});
+ # Reject CR, LF, and NUL before URI-escaping a bare token.
+ validate_header('authorization', $api_token);
+ my $auth_header = $api_token;
+ # Treat only explicit scheme headers (configured scheme, known Proxmox API token schemes,
+ # or space-delimited auth schemes) as preformatted so bare user IDs containing '=' (e.g.
+ # LDAP cn=alice@realm!tok=secret) are prefixed and URI-escaped.
+ if (
+ $auth_header !~ /^\Q$api_token_name\E(?:=| )/
+ && $auth_header !~ /^(?:PVE|PBS|PMG|PDM)APIToken(?:=| )/
+ && $auth_header !~ /^[A-Za-z][A-Za-z0-9_-]* /
+ ) {
+ if ($api_token_name =~ /^(?:PBS|PDM)APIToken\z/ && $api_token =~ /\A([^:]+):(.*)\z/s) {
+ # PBS/PDM authenticators split on the literal ':' before percent-decoding only the
+ # secret, parsing the token ID verbatim as an Authid.
+ $auth_header = "${api_token_name}=$1:" . uri_escape($2);
+ } else {
+ $auth_header = "${api_token_name}=" . uri_escape($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 at most one terminal callback (calling $cancel->() suppresses any later on_response or
+# on_error invocation, including deferred setup errors):
+# - 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.
+# Setup exceptions reach on_error on a later event-loop turn via AE::postpone. The transport may
+# invoke a terminal callback synchronously before request_raw() returns. Invalid callback
+# arguments or conflicting body and 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 !~ /\A(?:GET|POST|PUT|DELETE|HEAD)\z/) {
+ 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';
+
+ if (
+ (!defined($opts{headers}) || ref($opts{headers}) eq 'HASH')
+ && !exists($self->{headers}->{'accept-encoding'})
+ ) {
+ my %hdrs = %{ $opts{headers} // {} };
+ if (!grep { defined($_) && !ref($_) && lc($_) eq 'accept-encoding' } keys %hdrs) {
+ $hdrs{'accept-encoding'} = 'gzip';
+ $opts{headers} = \%hdrs;
+ }
+ }
+
+ 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') {
+ $on_error->(PVE::APIClient::Exception->new("unexpected response format\n"));
+ return;
+ }
+ if (defined($res->{success}) && !$res->{success}) {
+ my $msg = $res->{message} || 'API error';
+ $msg .= "\n" if $msg !~ /\n\z/;
+ $on_error->(
+ PVE::APIClient::Exception->new(
+ $msg,
+ code => $res->{status} || 500,
+ errors => $res->{errors},
+ ),
+ );
+ return;
+ }
+ if (!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..8dc5bee
--- /dev/null
+++ b/src/test/anyevent_client.t
@@ -0,0 +1,1974 @@
+#!/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/extjs/fail-502') {
+ send_http_response(
+ $hdl,
+ '200 OK',
+ { 'Content-Type' => 'application/json' },
+ to_json(
+ {
+ success => 0,
+ status => 502,
+ message => 'peer fetch failed',
+ errors => { peer => 'unreachable' },
+ data => undef,
+ },
+ { 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%40pam%21tok%3Dsecret-val',
+ 'bare api_token gets default PVEAPIToken= prefix and URI escaping',
+ );
+ is($r1->{headers}->{pvedisableproxy}, '1', 'custom default header sent');
+
+ my $tok_special = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ api_token => 'cn=alice;bob%20@pam!tok=sec-ret',
+ );
+ my $r_special = run_with_timeout(sub {
+ my ($cv) = @_;
+ $tok_special->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send($_[0]) },
+ on_error => sub { $cv->croak("err: $_[0]") },
+ );
+ });
+ is(
+ $r_special->{headers}->{authorization},
+ 'PVEAPIToken=cn%3Dalice%3Bbob%2520%40pam%21tok%3Dsec-ret',
+ 'bare api_token escapes =, ;, and % in user ID without mistaking it for a scheme header',
+ );
+
+ my $extjs_err = run_with_timeout(sub {
+ my ($cv) = @_;
+ $tok_bare->get(
+ 'api2/extjs/fail-502',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$extjs_err->{ok}, 'get() routes HTTP 200 ExtJS success:0 failure to on_error');
+ isa_ok($extjs_err->{err}, 'PVE::APIClient::Exception');
+ is($extjs_err->{err}->{code}, 502, 'ExtJS failure status code preserved');
+ like($extjs_err->{err}->{msg}, qr/peer fetch failed/, 'ExtJS failure message preserved');
+ is_deeply(
+ $extjs_err->{err}->{errors},
+ { peer => 'unreachable' },
+ 'ExtJS failure errors hash preserved',
+ );
+
+ 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%40pam%21tok%3Dfrom-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',
+ );
+
+ # Reverse conflict (verify_hostname => 0 with active verify_peername) and uppercase 'NONE'
+ # without pinning must both fail closed before opening any socket.
+ for my $bad_tls (
+ [
+ 'verify_hostname => 0 with verify_peername => https',
+ { verify_hostname => 0, verify_peername => 'https' },
+ qr/conflicting ssl_opts/,
+ ],
+ [
+ 'uppercase verify_peername => NONE without pins',
+ { verify_peername => 'NONE' },
+ qr/cannot disable verify_hostname/,
+ ],
+ [
+ 'empty verify_peername',
+ { verify_peername => '' },
+ qr/invalid ssl_opts->\{verify_peername\}/,
+ ],
+ [
+ 'unknown verify_peername scheme',
+ { verify_peername => 'strict' },
+ qr/invalid ssl_opts->\{verify_peername\}/,
+ ],
+ [
+ 'numeric verify_peername',
+ { verify_peername => 1 },
+ qr/invalid ssl_opts->\{verify_peername\}/,
+ ],
+ [
+ 'non-CODE verify_cb',
+ { verify_cb => 'not-a-sub' },
+ qr/verify_cb\} must be a CODE ref/,
+ ],
+ ) {
+ my ($label, $opts, $re) = @$bad_tls;
+ my $c_bad = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $unpinned_port,
+ ssl_opts => $opts,
+ );
+ my $r_bad = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_bad->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_bad->{ok}, "$label fails closed via on_error");
+ like("$r_bad->{err}", $re, "$label returns explicit error");
+ }
+
+ for my $combo (
+ ['cached_fingerprints + verify_cb', { cached_fingerprints => { '00:11' => 1 } }],
+ ['verify_fingerprint_cb + verify_cb', { verify_fingerprint_cb => sub { 1 } }],
+ ) {
+ my ($label, $extra) = @$combo;
+ my $c_combo = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $unpinned_port,
+ %$extra,
+ ssl_opts => { ca_file => $ca_crt, verify_cb => sub { 1 } },
+ );
+ my $r_combo = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_combo->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_combo->{ok}, "$label fails closed via on_error");
+ like("$r_combo->{err}", qr/conflicting ssl_opts/, "$label error is explicit");
+ }
+
+ is(
+ $unpinned_conns,
+ 0,
+ 'no TCP connections opened for verify => 0 or conflicting/invalid ssl_opts',
+ );
+ undef $unpinned_guard;
+
+ # Uppercase verify_peername => 'HTTPS' must normalize to 'https' and reject wrong-host cert.
+ my $c_upper_https = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $wrong_port,
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_peername => 'HTTPS',
+ },
+ );
+ my $r_upper_https = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_upper_https->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_upper_https->{ok},
+ 'uppercase verify_peername => HTTPS normalizes and rejects wrong-host CA cert',
+ );
+
+ # verify_fingerprint_cb with verify_peername => 'none' (or 'NONE') and no explicit
+ # verify_hostname MUST NOT take the CA-chain shortcut on a wrong-host CA-signed cert.
+ for my $vp_none ('none', 'NONE') {
+ my $fp_cb_called = 0;
+ my $c_fp_vp_none = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $wrong_port,
+ verify_fingerprint_cb => sub {
+ $fp_cb_called++;
+ return 0;
+ },
+ ssl_opts => {
+ ca_file => $ca_crt,
+ verify_peername => $vp_none,
+ },
+ );
+ my $r_fp_vp_none = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_fp_vp_none->request_raw(
+ 'GET',
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_fp_vp_none->{ok},
+ "verify_fingerprint_cb + verify_peername => '$vp_none' rejects wrong-host CA cert when cb denies",
+ );
+ is(
+ $fp_cb_called,
+ 1,
+ "verify_fingerprint_cb invoked (no CA shortcut) with verify_peername => '$vp_none'",
+ );
+ }
+
+ # Issuer verification error at depth > 0 followed by a valid matching-host leaf must
+ # still fail the chain (via %chain_failed) and consult verify_fingerprint_cb.
+ my $chain_crt = "$tmpdir/chain.crt";
+ {
+ open(my $in_leaf, '<', $good_crt) or die "open $good_crt: $!";
+ open(my $in_ca, '<', $ca_crt) or die "open $ca_crt: $!";
+ open(my $out_chain, '>', $chain_crt) or die "open $chain_crt: $!";
+ local $/;
+ my $leaf_pem = <$in_leaf>;
+ my $ca_pem = <$in_ca>;
+ print {$out_chain} $leaf_pem, $ca_pem;
+ close($out_chain);
+ }
+ my ($chain_guard, $chain_port, $chain_hdls) = $start_leaf_server->($chain_crt, $good_key);
+ my $issuer_cb_calls = 0;
+ my $c_issuer_fail = PVE::APIClient::AnyEvent->new(
+ host => 'localhost',
+ port => $chain_port,
+ verify_fingerprint_cb => sub {
+ $issuer_cb_calls++;
+ return 0;
+ },
+ );
+ my $r_issuer_fail = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_issuer_fail->get(
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_issuer_fail->{ok},
+ 'issuer failure at nonzero depth with matching-host leaf is rejected when cb denies',
+ );
+ is(
+ $issuer_cb_calls,
+ 1,
+ 'issuer failure at nonzero depth consulted verify_fingerprint_cb instead of trusting leaf',
+ );
+ undef $chain_guard;
+ %$chain_hdls = ();
+
+ 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");
+ }
+
+ my $r_call_bad_hdr = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->call(
+ 'GET',
+ 'version',
+ undef,
+ headers => { 'X-Test' => "v\r\nX-Injected: 1" },
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(
+ !$r_call_bad_hdr->{ok},
+ 'call() defers invalid per-request header to on_error without croaking',
+ );
+ isa_ok($r_call_bad_hdr->{err}, 'PVE::APIClient::Exception');
+ like(
+ "$r_call_bad_hdr->{err}",
+ qr/invalid HTTP header/,
+ 'call() error identifies invalid header',
+ );
+
+ is($hdr_conns, 0, 'no TCP connections opened for rejected per-request headers');
+
+ # Method validation must reject trailing newline (\z, not $).
+ my $r_bad_method = run_with_timeout(sub {
+ my ($cv) = @_;
+ $client->request_raw(
+ "GET\n",
+ 'version',
+ undef,
+ on_response => sub { $cv->send({ ok => 1 }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok(!$r_bad_method->{ok}, 'request_raw rejects method with trailing newline');
+ isa_ok($r_bad_method->{err}, 'PVE::APIClient::Exception');
+ like("$r_bad_method->{err}", qr/not implemented/, 'trailing-newline method reports error');
+
+ # Bare PBSAPIToken and PDMAPIToken keep literal tokenid: and percent-encode only the secret.
+ for my $scheme ('PBSAPIToken', 'PDMAPIToken') {
+ my $bare_id = 'user@pbs!tok';
+ my $bare_secret = 'sec+ret%20=1:2';
+ my $c_tok = PVE::APIClient::AnyEvent->new(
+ host => '127.0.0.1',
+ port => $server_port,
+ cached_fingerprints => { $cert_fp => 1 },
+ api_token_name => $scheme,
+ api_token => "${bare_id}:${bare_secret}",
+ );
+ my $r_tok = run_with_timeout(sub {
+ my ($cv) = @_;
+ $c_tok->get(
+ 'echo-headers',
+ undef,
+ on_response => sub { $cv->send({ ok => 1, data => $_[0] }) },
+ on_error => sub { $cv->send({ ok => 0, err => $_[0] }) },
+ );
+ });
+ ok($r_tok->{ok}, "$scheme bare token request succeeded");
+ my $auth_hdr = $r_tok->{data}->{headers}->{authorization} // '';
+ like(
+ $auth_hdr,
+ qr/\A\Q$scheme\E=\Q$bare_id\E:/,
+ "$scheme preserved literal tokenid and ':' delimiter",
+ );
+ my ($after_prefix) = $auth_hdr =~ /\A\Q$scheme\E=(.*)\z/s;
+ my ($parsed_id, $parsed_sec_enc) = split(/:/, $after_prefix // '', 2);
+ is($parsed_id, $bare_id, "$scheme split-on-colon recovered exact Authid");
+ require URI::Escape;
+ is(
+ URI::Escape::uri_unescape($parsed_sec_enc),
+ $bare_secret,
+ "$scheme percent-decoding secret recovered exact secret",
+ );
+ }
+
+ undef $hdr_guard;
+};
+
+undef $server_guard;
+%active_server_handles = ();
+
+done_testing();
--
2.47.3
next prev parent reply other threads:[~2026-12-01 10:45 UTC|newest]
Thread overview: 10+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-01 10:18 [PATCH http-server,apiclient,manager v2 0/9] async and streaming pull metric export Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 1/9] response: support deferred async API2 responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 2/9] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
2026-12-01 10:18 ` [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Thomas Lamprecht
2026-12-01 10:18 ` Thomas Lamprecht [this message]
2026-12-01 10:19 ` [PATCH apiclient v2 5/9] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 6/9] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 7/9] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 8/9] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-12-01 10:19 ` [PATCH manager v2 9/9] test: add pull metric export test suite Thomas Lamprecht
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261201101913.1885484-5-t.lamprecht@proxmox.com \
--to=t.lamprecht@proxmox.com \
--cc=pve-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox