Class-Shared

 view release on metacpan or  search on metacpan

t/domain.t  view on Meta::CPAN

	dir_mode         => 0700,
	open_mode        => 0755,
	private_mode     => 0700,
	evil_modes       => [ 0777, 0770, 0702 ],
	beyond_limit     => 40_000,
	repeat_limit     => 32_766,
	port_min         => 1,
	port_max         => 65_535,
	zalgo_repeats    => 5,
	utf8_secret      => "Gr\xc3\xbc\xc3\x9fe \xf0\x9f\x98\x80\n",
	err              => {
		no_class        => 'Class::Shared: no class name given',
		bad_class       => q{Class::Shared: '%s' is not a valid class name},
		no_token_file   => 'Class::Shared: no token file given',
		cannot_read     => 'Class::Shared: cannot read %s: ',
		token_too_large => 'Class::Shared: %s is too large to be a secret (more than %d bytes)',
		token_empty     => 'Class::Shared: %s is empty',
		no_fingerprint  => 'Class::Shared: no TLS fingerprint given',
		bad_fingerprint => q{Class::Shared: '%s' is not a SHA-256 certificate fingerprint: }
			. 'give 64 hexadecimal digits, optionally colon-separated',
		nul_dir       => 'Class::Shared: a directory name may not contain a NUL byte',
		no_dir        => 'Class::Shared: no directory given',
		no_socket     => 'Class::Shared: no socket path given',
		socket_long   => q{Class::Shared: socket path '%s' is %d characters, more than the %d allowed; }
			. 'set CLASS_SHARED_DIR or pass dir => to a shorter directory',
		dir_unsafe    => '%s is writable by group or others; refusing to use it',
		create_failed => 'cannot create %s: ',
		fe_odd        => 'Class::Shared::Frontend->new: expected key/value options',
		fe_unknown    => q{Class::Shared::Frontend->new: unknown option '%s'},
		fe_no_class   => 'Class::Shared::Frontend->new: no class name given',
		fe_ctor       => 'Class::Shared::Frontend->new: ctor must be an array ref',
		fe_port       => 'Class::Shared::Frontend->new: port must be a whole number from 1 to 65535',
		fe_unix_token => 'Class::Shared::Frontend->new: a unix socket needs no token: '
			. $Class::Shared::UNIX_TRUST_REASON,
		fe_unix_tls => 'Class::Shared::Frontend->new: a unix socket needs no TLS: '
			. $Class::Shared::UNIX_TRUST_REASON,
		fe_two_tokens => 'Class::Shared::Frontend->new: give token or token_file, not both',
		fe_tcp_both   => 'Class::Shared::Frontend->new: a TCP backend needs both host and port',
		fe_socket_both => 'Class::Shared::Frontend->new: use either socket or host/port, not both',
		fe_tls_pair    => 'Class::Shared::Frontend->new: a TCP backend needs tls_cert and tls_key: '
			. 'the backend will not accept a client it cannot verify',
		fe_tls_trust => 'Class::Shared::Frontend->new: a TCP backend needs tls_ca or tls_fingerprint: '
			. 'without one it cannot verify the backend',
		fe_tls_both => 'Class::Shared::Frontend->new: give tls_ca or tls_fingerprint, not both: '
			. 'a CA and a pin are alternatives',
		frame_limit    => 'frame of %d bytes exceeds the limit of %d',
		short_digest   => 'frame is too short to be authenticated',
		failed_digest  => 'frame failed authentication',
		timeout        => 'timed out waiting for a reply',
		closed         => 'connection closed by peer',
		write_failed   => 'write failed: ',
		serialise      => 'cannot serialise message: ',
		deserialise    => 'cannot deserialise message: ',
	},
);

$config{cwd}          = Cwd::getcwd();
$config{env_dir}      = $ENV{CLASS_SHARED_DIR};
$config{env_xdg}      = $ENV{XDG_RUNTIME_DIR};
# The device and inode of STDOUT, which change if it is redirected.
$config{stdout_id}    = join(':', (stat(STDOUT))[0, 1]);

my $tmp = File::Temp->newdir('class-shared-domain-XXXXXX', TMPDIR => 1, CLEANUP => 1);

# A declared failure: the exact documented text, plus the new line every
# message ends with.
sub dies_with {
	my ($code, $expected, $name) = @_;

	throws_ok { $code->() } qr/\A\Q$expected\E\n\z/, $name;

	return;
}

# A declared failure whose text contains something the system chooses, such
# as the strerror text after a colon.
sub dies_like {
	my ($code, $pattern, $name) = @_;

	throws_ok { $code->() } $pattern, $name;

	return;
}

sub write_bytes {
	my ($name, $content) = @_;
	my $path = File::Spec->catfile("$tmp", $name);

	open(my $fh, '>:raw', $path) or die "cannot write $path: $!";
	print {$fh} $content or die "cannot write $path: $!";
	close($fh) or die "cannot write $path: $!";

	return $path;
}

sub read_mode {
	my ($path) = @_;
	my @stat = stat($path) or return;

	return $stat[2] & 07777;
}

# Run detach_standard_streams in a child, which is the only safe place for a
# call that replaces STDIN, STDOUT and STDERR.  POSIX::_exit skips the END
# blocks, so the child cannot print a second TAP plan.
sub detach_in_child {
	my ($log) = @_;

	my $pid = fork();
	return unless defined $pid;

	if (!$pid) {
		my ($ok) = Class::Shared::detach_standard_streams($log);
		POSIX::_exit($ok ? 0 : 1);
	}

	waitpid($pid, 0);

	return $? >> 8;
}

my $hex64 = join('', map { sprintf '%02x', $_ } 1 .. $config{sha256_bytes});
my @pairs = $hex64 =~ /(..)/g;
my $colon64 = join($config{colon_separator}, @pairs);
my $normalised = $config{sha256_prefix} . $hex64;

subtest 'validate_class: length boundaries' => sub {
	my $err = $config{err};

	dies_with(sub { Class::Shared::validate_class(undef) },
		$err->{no_class}, 'undef is outside the domain');
	dies_with(sub { Class::Shared::validate_class('') },
		$err->{no_class}, 'the empty string is outside the domain (length 0)');

	is(Class::Shared::validate_class('A'), 'A', 'length 1, the minimum, is accepted');
	is(Class::Shared::validate_class('_'), '_', 'a lone underscore at the minimum is accepted');

	dies_with(sub { Class::Shared::validate_class('1') },
		sprintf($err->{bad_class}, '1'), 'a digit at length 1 is outside the domain');

	my $long = 'A' x $config{beyond_limit};
	my $got = Class::Shared::validate_class($long);
	is(length($got), $config{beyond_limit},
		"a $config{beyond_limit} character name is accepted: the check has no repeat limit");
	cmp_ok($config{beyond_limit}, '>', $config{repeat_limit},
		'the accepted name is longer than perl 5.26\'s repeated group limit');

	my $too_long_with_empty_part = $long . '::';
	dies_like(sub { Class::Shared::validate_class($too_long_with_empty_part) },
		qr/\A\QClass::Shared: \E.*\Qis not a valid class name\E\n\z/,
		'a long name ending in an empty part is still refused');
};

subtest 'validate_class: structural partitions' => sub {
	my $err = $config{err};

	my @valid = (
		[ 'one word',             'Foo' ],

t/domain.t  view on Meta::CPAN

	}, $err->{fe_tls_both}, 'a CA and a pin are alternatives, not both');
};

subtest 'Frontend->new: port domain' => sub {
	my $err = $config{err};

	my @outside = ('', 0, -1, $config{port_max} + 1, 'eighty', '80x', ' 80', '80.0', "\x{fc}");
	for my $port (@outside) {
		my $shown = $port =~ /\A[0-9]+\z/ ? $port : "'$port'";
		dies_with(sub {
			Class::Shared::Frontend->new('Class::Simple', host => 'example.test', port => $port);
		}, $err->{fe_port}, "port $shown is outside 1 .. $config{port_max}");
	}

	is($config{port_max}, 65_535, 'the documented maximum port is 65535');

	for my $port ($config{port_min}, $config{port_max}, '0080') {
		dies_with(sub {
			Class::Shared::Frontend->new('Class::Simple', host => 'example.test', port => $port);
		}, $err->{fe_tls_pair},
			"port $port is inside the domain and passes to the next missing option");
	}

	dies_with(sub { Class::Shared::Frontend->new('Class::Simple', host => 'h', port => 0) },
		$err->{fe_port}, 'a port below the minimum is refused once a host is present');

	dies_with(sub { Class::Shared::Frontend->new('Class::Simple', port => $config{port_max} + 1) },
		$err->{fe_tcp_both}, 'a missing host is reported before the port is checked');
};

subtest 'detach_standard_streams: log domain' => sub {
	my $log = File::Spec->catfile("$tmp", 'backend.log');

	my $status = detach_in_child($log);
	plan skip_all => 'cannot fork on this platform' unless defined $status;
	is($status, 0, 'a writable log returns success');
	ok(-e $log, 'and the log file was created');

	my $absent = File::Spec->catfile("$tmp", 'absent', 'backend.log');
	is(detach_in_child($absent), 0,
		'a log that cannot be opened still succeeds, sending the streams to the null device');
};

subtest 'documented limits and process state' => sub {
	is($Class::Shared::MAX_SOCKET_PATH, $config{max_socket_path},
		'the socket path limit is 100 characters');
	is($Class::Shared::MAX_SECRET, $config{max_secret},
		'the secret limit is 65536 bytes');
	is($Class::Shared::POLL_INTERVAL, $config{poll_interval},
		'the polling interval is 0.02 seconds');
	is($Class::Shared::Protocol::MAX_FRAME, $config{max_frame},
		'the frame limit is 64 MiB');
	is($Class::Shared::Protocol::DIGEST_SIZE, $config{digest_size},
		'the digest is 32 bytes');

	is(Cwd::getcwd(), $config{cwd}, 'the working directory is unchanged by any failure above');
	is($ENV{CLASS_SHARED_DIR}, $config{env_dir}, 'CLASS_SHARED_DIR is restored');
	is($ENV{XDG_RUNTIME_DIR}, $config{env_xdg}, 'XDG_RUNTIME_DIR is restored');

	ok(-d "$tmp", 'no failure removed the temporary directory');
	is(join(':', (stat(STDOUT))[0, 1]), $config{stdout_id},
		'STDOUT still belongs to the test process: only the children detached theirs');
};

done_testing();



( run in 1.321 second using v1.01-cache-2.11-cpan-eb134014566 )