API-Docker

 view release on metacpan or  search on metacpan

t/tls_read.t  view on Meta::CPAN

#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Config;
use Path::Tiny;
use Time::HiRes qw( time sleep );
use API::Docker;
use API::Docker::Error::Timeout;

# karr k65. t/tls.t covers option assembly, certificate selection and the
# handshake; nothing in the suite ever reads a byte over TLS. This file is
# that read path, pinned against the three measurements taken by hand
# during the transport rebuild (karr k60), before and after, identical both
# times:
#
#   three writes 0.15s apart      -> 3 on_chunk calls, spaced apart
#   100000 bytes over many records -> every byte arrives, none lost
#   delivered, then silent, read_timeout 1 -> Error::Timeout after ~1s,
#     phase 'read', summary delivered=1, the bytes already with the callback
#
# It matters here specifically because TLS is the one transport where a
# short read is the normal case -- one plaintext record (<= 16384 bytes,
# RFC 8446 5.1) per sysread -- so the "a short read is not an end of
# stream" rule this role depends on (see _pull in
# API::Docker::Role::HTTP) has no margin to be wrong in. And
# IO::Socket::SSL's own read/sysread split -- ssl_read_all on a blocking
# socket for read(), a single Net::SSLeay::read for sysread() -- is exactly
# the distinction karr k60 is built on: get the wrong one and either every
# read blocks until the daemon closes, or a stall never times out.
#
# Certificate: generated fresh per run rather than checked in under t/, the
# same choice t/tls.t already made for the same reason -- a stored
# certificate is deterministic but expires, and CERT_create costs single-
# digit milliseconds. Gated on IO::Socket::SSL the same way t/tls.t gates
# it: a recommended, not a required, dependency, so its absence is
# skip_all rather than a failure.
#
# The server below is a forked, real TCP/TLS listener on 127.0.0.1 -- no
# Docker daemon, no network beyond loopback. Every child this file starts
# is reaped by the subtest that started it and, as a backstop for a test
# that dies before reaching that reap, by the END block at the bottom: a
# leaked server process left sleeping is worse than a missing test.

my $HAVE_SSL   = eval { require IO::Socket::SSL; 1 };
my $HAVE_UTILS = $HAVE_SSL && eval { require IO::Socket::SSL::Utils; 1 };

plan skip_all => 'IO::Socket::SSL is not installed (recommended, not '
  . 'required -- see API::Docker::Role::HTTP)' unless $HAVE_SSL;
plan skip_all => 'IO::Socket::SSL::Utils cannot generate certificates'
  unless $HAVE_UTILS;
plan skip_all => 'no fork on this platform' unless $Config{d_fork};

# ---------------------------------------------------------------------------
# One CA and one server leaf certificate, reused by every subtest below.
# ---------------------------------------------------------------------------

my $dir = Path::Tiny->tempdir;
my ($ca, $cakey) = IO::Socket::SSL::Utils::CERT_create(
  CA => 1, subject => { CN => 'API-Docker TLS-read test CA' });
my ($server_cert, $server_key) = IO::Socket::SSL::Utils::CERT_create(
  issuer          => [$ca, $cakey],
  subject         => { CN => 'localhost' },
  purpose         => 'server',
  subjectAltNames => [ [ DNS => 'localhost' ], [ IP => '127.0.0.1' ] ],
);
IO::Socket::SSL::Utils::PEM_cert2file($ca, $dir->child('ca.pem') . '');
IO::Socket::SSL::Utils::PEM_cert2file($server_cert, $dir->child('server.pem') . '');
IO::Socket::SSL::Utils::PEM_key2file($server_key, $dir->child('server-key.pem') . '');

# ---------------------------------------------------------------------------
# A TLS server that speaks whatever $respond->($conn) tells it to, once per
# connection. Forked so the parent's read is a real client of a real socket
# rather than a mock -- the whole point of this file.
# ---------------------------------------------------------------------------

my @CHILDREN;

sub start_server {

t/tls_read.t  view on Meta::CPAN

  });

  my $docker = client_for($port);
  my @chunks;
  my $summary = $docker->get('/probe',
    on_chunk     => sub { push @chunks, $_[0] },
    read_timeout => 10,
  );
  reap($pid);

  my $total = join '', @chunks;
  is length($total), 100_000, 'every byte arrived';
  is $total, $payload, 'and none were lost, reordered or duplicated';

  cmp_ok scalar(@chunks), '>', 1, 'delivered over more than one on_chunk '
    . 'call -- one 100000-byte write cannot be a single TLS record';
  diag(sprintf 'on_chunk called %d times for 100000 bytes (sizes: %s)',
    scalar(@chunks), join(',', map { length } @chunks));

  # RFC 8446 5.1 (and RFC 5246 6.2.1 before it): a TLS record's plaintext
  # is at most 2**14 bytes. sysread on an IO::Socket::SSL handle is a single
  # Net::SSLeay::read -- one record -- so every call this transport makes
  # must come back at or under that bound; a call larger than it would mean
  # the reader had somehow been handed more than one record's worth of
  # plaintext from a single sysread, which is not what TLS delivers.
  my $max = 0;
  $max = length($_) > $max ? length($_) : $max for @chunks;
  cmp_ok $max, '<=', 16384, 'no single on_chunk call exceeds a TLS record';

  is $summary->{delivered}, scalar(@chunks), 'the summary agrees';
  is $summary->{stopped}, 0, 'the daemon ended the stream, not the callback';
};

# ---------------------------------------------------------------------------
subtest 'read_timeout fires on an idle TLS connection, keeping what arrived' => sub {
  my ($port, $pid) = start_server(sub {
    my ($conn) = @_;
    send_head($conn);
    print $conn "first-chunk\n";
    # Deliberately never closes and never writes again: the connection goes
    # idle rather than ending, which is the case read_timeout exists for.
    sleep 5;
  });

  my $docker = client_for($port);
  my @seen;
  my $t0 = time;
  my $err = do {
    local $@;
    eval {
      $docker->get('/probe',
        on_chunk     => sub { push @seen, $_[0] },
        read_timeout => 1,
      );
    };
    $@;
  };
  my $elapsed = time - $t0;
  reap($pid);

  isa_ok $err, 'API::Docker::Error::Timeout';
  is $err && $err->phase, 'read', 'the read bound fired, not the connect one';
  is $err && $err->timeout, 1, 'naming the read_timeout that expired';

  is scalar(@seen), 1, 'the chunk that arrived before the stall reached the '
    . 'callback -- a short TLS read must not be mistaken for the end of the '
    . 'stream and swallowed';
  is $seen[0], "first-chunk\n", 'and it is the one the server actually sent';

  is $err && $err->summary && $err->summary->{delivered}, 1,
    'the exception\'s own summary agrees with what the callback saw';
  is $err && $err->partial, '',
    'a streamed request keeps no body of its own -- the bytes are with the '
    . 'callback, not duplicated onto the exception';

  cmp_ok $elapsed, '>=', 0.9, 'it waited close to the full second rather '
    . 'than giving up early';
  cmp_ok $elapsed, '<', 5, 'and it did not wait past the bound either -- '
    . 'the timer, not the 5s sleep on the other end, is what ended this '
    . '(' . sprintf('%.2fs', $elapsed) . ')';
};

done_testing;



( run in 1.478 second using v1.01-cache-2.11-cpan-234fa220139 )