JSONUnix.pm

filter: Statementstmt 59.1% 249 / 421 Branchbran 34.2% 74 / 216 Conditioncond 32.5% 28 / 86 MC/DCmcdc 17.6% 9 / 51 Subroutinesub 80.0% 48 / 60 Podpod 100% 4 / 4 totaltotal 49.1% 412 / 838 SCAR 81.1
CC
153
Cov
49%
_permission_verdict
1122.0
_resolve_user_groups
90.0
_normalize_permission_spec
59.5
CRAP 3341.6
↑ Summary JSONUnix/Client.pm »
1 package POE::Component::Server::JSONUnix;
2  
3 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use mro;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 9 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 9 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 9 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 9 ▶use Socket qw(PF_UNIX SOCK_STREAM);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use IO::Socket::UNIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 9 use POE qw(
16 Wheel::SocketFactory
17 Wheel::ReadWrite
18 Filter::Line
19 Driver::SysRW
20 9 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 9 our $VERSION = '0.1.0';
23  
24 =head1 NAME
25  
26 POE::Component::Server::JSONUnix - pluggable JSON-over-Unix-socket server for POE
27  
28 =head1 SYNOPSIS
29  
30 use POE;
31 use POE::Component::Server::JSONUnix;
32  
33 my $server = POE::Component::Server::JSONUnix->spawn(
34 socket_path => '/tmp/app.sock',
35 socket_mode => 0600,
36 commands => {
37 echo => sub {
38 my ($server, $request, $ctx) = @_;
39 return { echoed => $request->{args} };
40 },
41 },
42 );
43  
44 # Add more commands at any time.
45 $server->register(
46 add => sub {
47 my ($server, $request, $ctx) = @_;
48 my $sum = 0;
49 $sum += $_ for @{ $request->{args}{numbers} // [] };
50 return { sum => $sum };
51 },
52 );
53  
54 $poe_kernel->run;
55  
56 =head1 DESCRIPTION
57  
58 This module is a small, event-driven server that listens on a Unix domain
59 socket and speaks a simple JSON request/response protocol. It is built on
60 L<POE> and is designed to be extended: the set of commands it understands is a
61 plain dispatch table you can add to at construction time, at run time, or by
62 subclassing.
63  
64 It is suitable as a local control or RPC endpoint for a daemon -- the sort of
65 thing you talk to from a command-line tool, a cron job, or another process on
66 the same host.
67  
68 =head1 PROTOCOL
69  
70 The framing is newline-delimited JSON: each message is a single JSON object on
71 its own line, terminated by C<\n>.
72  
73 A request looks like:
74  
75 {"command":"add","args":{"numbers":[1,2,3]},"id":7}
76  
77 =over 4
78  
79 =item *
80  
81 C<command> (required) -- the name of the command to run. C<cmd> is accepted as
82 an alias.
83  
84 =item *
85  
86 C<args> (optional) -- an arbitrary payload passed straight through to the
87 handler.
88  
89 =item *
90  
91 C<id> (optional) -- an opaque value echoed back in the response so asynchronous
92 clients can correlate replies with requests.
93  
94 =back
95  
96 A successful response:
97  
98 {"id":7,"status":"ok","result":{"sum":6}}
99  
100 An error response:
101  
102 {"id":7,"status":"error","error":"unknown command: subtract"}
103  
104 Malformed JSON, a non-object request, a missing command, an unknown command, or
105 a handler that dies all produce an C<error> response rather than disturbing the
106 server or other clients.
107  
108 =head1 CONSTRUCTOR
109  
110 =head2 spawn
111  
112 my $server = POE::Component::Server::JSONUnix->spawn(%args);
113  
114 Creates the server's POE session and returns the server object. Recognised
115 arguments:
116  
117 =head3 socket_path
118  
119 Required. Filesystem path of the Unix domain socket to listen on. If a stale
120 socket file is present it is removed; if another process is actively
121 listening there, C<spawn> dies rather than clobber it.
122  
123 =head3 commands
124  
125 Hash reference of C<< name => \&handler >> pairs to register. See
126 L</"COMMAND HANDLERS">.
127  
128 =head3 socket_mode
129  
130 If set (e.g. C<0600>), C<chmod> the socket to these permissions after
131 binding. Unix socket permissions govern who may connect, so setting this is
132 recommended.
133  
134 =head3 alias
135  
136 POE session alias. Defaults to C<json_unix_server>. Set this if you run more
137 than one server in a single process.
138  
139 =head3 unlink_existing
140  
141 Whether to remove a stale (not-in-use) socket file on startup. Defaults to
142 true.
143  
144 =head3 on_error
145  
146 Code reference called as
147 C<< $cb->($operation, $errnum, $errstr [, $wheel_id]) >> on listen and
148 connection I/O errors. Normal client disconnects are not reported.
149  
150 =head3 auth_temp_dir
151  
152 Directory used for the cookie-file ownership challenge. Defaults to
153 C<File::Spec-E<gt>tmpdir> (usually C</tmp>).
154  
155 =head3 auth_required
156  
157 If set to a true value, all commands except C<auth_start> and C<auth_verify>
158 return an error until the client has successfully completed the ownership
159 challenge. Defaults to false.
160  
161 =head3 permissions
162  
163 Optional user/group permission policy, a hash reference of the form
164 C<< {default => 'allow'|'deny', commands => {name => $spec, ...}} >>. When
165 this argument is not given the server behaves exactly as it does without the
166 feature. See L</"PERMISSIONS">.
167  
168 =cut
169  
170 sub spawn {
171 10 ▶ my ( $class, %args ) = @_;
Subroutine spawn: called CC=9 SCAR=22.2
Pod documented
172  
173 my $path = delete $args{socket_path}
174 10 ▶ or croak "spawn() requires a 'socket_path' argument";
Branch: 1 branch
BranchTrueFalseTotal
my $path = delete $args{"socket_path"} or croak("spawn() requires a 'socket_path' argument") 0 10 10
175  
176 my $self = bless {
177 socket_path => $path,
178 alias => ( delete $args{alias} ) // 'json_unix_server',
179 socket_mode => delete $args{socket_mode}, # e.g. 0600
180 unlink_existing => ( delete $args{unlink_existing} ) // 1,
181 on_error => delete $args{on_error}, # coderef (optional)
182 auth_temp_dir => ( delete $args{auth_temp_dir} ) // File::Spec->tmpdir,
183 10 ▶ auth_required => ( delete $args{auth_required} ) // 0,
Condition77%7/9
delete $args{"alias"} // "json_unix_server"
l!l
28
delete $args{"unlink_existing"} // 1
l!l
010
delete $args{"auth_temp_dir"} // "File::Spec"->tmpdir
l!l&&r!l&&!r
190
delete $args{"auth_required"} // 0
l!l
19
MC/DC100%1/1
delete $args{"alias"} // "json_unix_server"
delete $args{"alias"}
MC/DC0%0/1
delete $args{"unlink_existing"} // 1
delete $args{"unlink_existing"}
MC/DC0%0/2
delete $args{"auth_temp_dir"} // "File::Spec"->tmpdir
delete $args{"auth_temp_dir"} "File::Spec"->tmpdir
MC/DC100%1/1
delete $args{"auth_required"} // 0
delete $args{"auth_required"}
Truth table100%2/2
A
A= delete $args{"alias"}
Aresult
11
00
Truth table50%1/2
A
A= delete $args{"unlink_existing"}
Aresult
11
00
Truth table66%2/3
A // B
A= delete $args{"auth_temp_dir"}B= "File::Spec"->tmpdir
ABresult
1X1
011
000
Truth table100%2/2
A
A= delete $args{"auth_required"}
Aresult
11
00
184 permissions => undef, # stays undef unless a policy is passed to spawn
185 commands => {},
186 clients => {},
187 json => JSON::MaybeXS->new(
188 utf8 => 1,
189 canonical => 1,
190 allow_nonref => 0,
191 ),
192 }, $class;
193  
194 # Precedence (later overrides earlier): built-ins < cmd_* methods < arg.
195 10 $self->_register_builtins;
196 10 $self->_register_cmd_methods;
197  
198 10 ▶ if ( defined( my $cmds = delete $args{commands} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $cmds = delete $args{"commands"})) 2 8 10
199 2 ▶ croak "'commands' must be a hash reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cmds eq "HASH" 0 2 2
200 unless ref $cmds eq 'HASH';
201 2 $self->register(%$cmds);
202 }
203  
204 # Optional user/group permission policy. Validated here so a bad policy
205 # fails spawn() synchronously; when the argument is absent the server
206 # behaves exactly as it did without the feature.
207 10 ▶ if ( defined( my $perms = delete $args{permissions} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $perms = delete $args{"permissions"})) 8 2 10
208 8 $self->{permissions} = _build_permissions($perms);
209 }
210  
211 # Fail fast and synchronously on a busy or unusable socket path, so the
212 # caller of spawn() gets the error rather than a dead session later.
213 2 $self->_prepare_socket_path;
214  
215 2 POE::Session->create(
216 object_states => [
217 $self => {
218 _start => '_poe_start',
219 _stop => '_poe_stop',
220 shutdown => '_poe_shutdown',
221 register_command => '_poe_register_command',
222 got_connection => '_poe_got_connection',
223 listen_error => '_poe_listen_error',
224 client_input => '_poe_client_input',
225 client_error => '_poe_client_error',
226 client_flushed => '_poe_client_flushed',
227 },
228 ],
229 );
230  
231 2 return $self;
232 } ## end sub spawn
233  
234 #--- command registration --------------------------------------------------
235  
236 =head1 METHODS
237  
238 =head2 register
239  
240 $server->register(name => \&handler, ...);
241  
242 Add or replace commands. Returns the server object. Croaks if a handler is not a
243 code reference.
244  
245 =cut
246  
247 # register(name => \&handler, ...) — add or replace commands at any time.
248 sub register {
249 26 ▶ my ( $self, %cmds ) = @_;
Subroutine register: called CC=3 SCAR=11.0
Pod documented
250 26 for my $name ( sort keys %cmds ) {
251 49 my $code = $cmds{$name};
252 49 ▶ croak "Handler for command '$name' must be a code reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 1 48 49
253 unless ref $code eq 'CODE';
254 48 $self->{commands}{$name} = $code;
255 }
256 25 return $self;
257 } ## end sub register
258  
259 =head2 command_names
260  
261 my $names = $server->command_names; # array reference, sorted
262  
263 The names of all currently registered commands. (Also available to clients as
264 the built-in C<commands> command.)
265  
266 =cut
267  
268 2 ▶sub command_names { return [ sort keys %{ $_[0]->{commands} } ] }
Subroutine command_names: called CC=1 SCAR=0.0
Pod documented
269  
270 sub _register_builtins {
271 10 ▶ my ($self) = @_;
Subroutine _register_builtins: called CC=1 SCAR=1.5
272 $self->register(
273 ping => sub {
274 2 ▶ my ( $server, $req, $ctx ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
275 2 return { pong => 1, time => time() };
276 },
277 commands => sub {
278 0 ▶ my ( $server, $req, $ctx ) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
279 0 my $names = $server->command_names;
280 0 $names = [ grep { $ctx->may($_) } @$names ]
281 0 ▶ if $server->{permissions};
Branch: 1 branch
BranchTrueFalseTotal
if $server->{"permissions"} 0 0 0
282 0 return { commands => $names };
283 },
284 10 );
285 10 $self->_register_auth_builtins;
286 10 return;
287 } ## end sub _register_builtins
288  
289 # Discover cmd_<name> methods anywhere in the class hierarchy so a server can
290 # be built simply by subclassing this module and adding methods.
291 sub _register_cmd_methods {
292 11 ▶ my ($self) = @_;
Subroutine _register_cmd_methods: called CC=6 SCAR=17.9
293 11 my %names;
294 9 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
295 11 for my $pkg ( @{ mro::get_linear_isa( ref $self ) } ) {
296 12 for my $sym ( keys %{"${pkg}::"} ) {
297 663 ▶ $names{$1} = 1 if $sym =~ /\Acmd_(.+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $sym =~ /\Acmd_(.+)\z/ 2 661 663
298 }
299 }
300 11 for my $name ( keys %names ) {
301 2 my $method = "cmd_$name";
302 2 ▶ next unless $self->can($method);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can($method) 0 2 2
303 $self->{commands}{$name} = sub {
304 1 ▶ my ( $server, $req, $ctx ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
305 1 return $server->$method( $req, $ctx );
306 2 };
307 }
308 11 return;
309 } ## end sub _register_cmd_methods
310  
311 sub _register_auth_builtins {
312 10 ▶ my ($self) = @_;
Subroutine _register_auth_builtins: called CC=1 SCAR=0.7
313  
314 $self->register(
315 auth_start => sub {
316 2 ▶ my ( $server, $req, $ctx ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
317 2 my $id = $ctx->{wheel_id};
318 2 my $client = $server->{clients}{$id};
319 2 my $cookie = _random_cookie();
320 2 $client->{auth_cookie} = $cookie;
321 2 $client->{auth_time} = time();
322 return {
323 cookie => $cookie,
324 temp_dir => $server->{auth_temp_dir},
325 2 };
326 },
327  
328 auth_verify => sub {
329 2 ▶ my ( $server, $req, $ctx ) = @_;
Subroutine __ANON__: called CC=14 SCAR=35.0
330 2 my $id = $ctx->{wheel_id};
331 2 my $client = $server->{clients}{$id};
332  
333 2 ▶ unless ( defined $client->{auth_cookie} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $client->{"auth_cookie"}) 0 2 2
334 0 $ctx->error('no pending auth challenge: call auth_start first');
335 0 return;
336 }
337  
338 2 ▶ my $path = $req->{args}{path} // '';
Condition50%1/2
$req->{"args"}{"path"} // ""
l!l
20
MC/DC0%0/1
$req->{"args"}{"path"} // ""
$req->{"args"}{"path"}
Truth table50%1/2
A
A= $req->{"args"}{"path"}
Aresult
11
00
339 2 ▶ unless ( $path && File::Spec->file_name_is_absolute($path) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($path and "File::Spec"->file_name_is_absolute($path)) 0 2 2
Condition33%1/3
$path and "File::Spec"->file_name_is_absolute($path)
!ll&&!rl&&r
002
MC/DC0%0/2
$path and "File::Spec"->file_name_is_absolute($path)
$path "File::Spec"->file_name_is_absolute($path)
Truth table33%1/3
A and B
A= $pathB= "File::Spec"->file_name_is_absolute($path)
ABresult
0X0
100
111
340 0 $ctx->error('args.path must be an absolute file path');
341 0 return;
342 }
343  
344 # Must be directly inside auth_temp_dir — no subdirectories.
345 2 my $temp_dir = $server->{auth_temp_dir};
346 2 my $dirname = File::Basename::dirname($path);
347 2 ▶ unless ( $dirname eq $temp_dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dirname eq $temp_dir) 0 2 2
348 0 $ctx->error("path must be a file directly inside $temp_dir");
349 0 return;
350 }
351  
352 # lstat so we never follow symlinks.
353 2 my @st = lstat($path);
354 2 ▶ unless (@st) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@st) 0 2 2
355 0 delete $client->{auth_cookie};
356 0 $ctx->error('verification file not found');
357 0 return;
358 }
359  
360 2 ▶ if ( -l _ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-l _) 0 2 2
361 0 unlink $path;
362 0 delete $client->{auth_cookie};
363 0 $ctx->error('verification file must not be a symbolic link');
364 0 return;
365 }
366  
367 2 ▶ unless ( -f _ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f _) 0 2 2
368 0 delete $client->{auth_cookie};
369 0 $ctx->error('verification file must be a regular file');
370 0 return;
371 }
372  
373 # Read the file contents (limit to avoid reading huge files).
374 2 my $content = '';
375 2 ▶ if ( open( my $fh, '<:raw', $path ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<:raw", $path) 2 0 2
376 2 read( $fh, $content, 256 );
377 2 close($fh);
378 }
379 2 unlink($path); # clean up regardless of outcome
380 2 $content =~ s/\s+\z//; # strip trailing whitespace the client may have added
381  
382 2 my $expected = $client->{auth_cookie};
383 2 delete $client->{auth_cookie};
384 2 delete $client->{auth_time};
385  
386 2 ▶ unless ( $content eq $expected ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($content eq $expected) 0 2 2
387 0 $ctx->error('cookie mismatch: verification failed');
388 0 return;
389 }
390  
391 2 my $uid = $st[4];
392 2 ▶ my $username = ( getpwuid($uid) )[0] // '';
Condition50%1/2
(getpwuid $uid)[0] // ""
l!l
20
MC/DC0%0/1
(getpwuid $uid)[0] // ""
(getpwuid $uid)[0]
Truth table50%1/2
A
A= (getpwuid $uid)[0]
Aresult
11
00
393  
394 2 $client->{auth_uid} = $uid;
395 2 $client->{auth_username} = $username;
396  
397 # With a permission policy in force, resolve and cache the user's
398 # groups now so the first gated request does not pay for it, and
399 # report them back. Without one, the response is exactly what it
400 # always was.
401 2 ▶ if ( $server->{permissions} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($server->{"permissions"}) 0 2 2
402 0 my $groups = $server->_client_groups( $ctx->{wheel_id} );
403 return {
404 uid => $uid + 0,
405 username => $username,
406 0 ▶ groups => $groups ? $groups->{list} : [],
Branch: 1 branch
BranchTrueFalseTotal
$groups ? : 0 0 0
407 };
408 }
409  
410 2 return { uid => $uid + 0, username => $username };
411 },
412 10 );
413 10 return;
414 } ## end sub _register_auth_builtins
415  
416 #--- permissions -------------------------------------------------------------
417  
418 # Validate and normalise the 'permissions' spawn argument into the internal
419 # form used by _permission_verdict.
420 sub _build_permissions {
421 8 ▶ my ($perms) = @_;
Subroutine _build_permissions: called CC=9 SCAR=23.3
422  
423 8 ▶ croak "'permissions' must be a hash reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $perms eq "HASH" 1 7 8
424 unless ref $perms eq 'HASH';
425  
426 7 my %in = %$perms;
427 7 my %out = ( default => 'allow', commands => {} );
428  
429 7 ▶ if ( defined( my $default = delete $in{default} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $default = delete $in{"default"})) 1 6 7
430 1 ▶ croak "permissions 'default' must be 'allow' or 'deny'"
Branch: 1 branch
BranchTrueFalseTotal
unless $default eq "allow" or $default eq "deny" 1 0 1
Condition33%1/3
$default eq "allow" or $default eq "deny"
l!l&&r!l&&!r
001
MC/DC0%0/2
$default eq "allow" or $default eq "deny"
$default eq "allow" $default eq "deny"
Truth table33%1/3
A or B
A= $default eq "allow"B= $default eq "deny"
ABresult
1X1
011
000
431 unless $default eq 'allow' || $default eq 'deny';
432 0 $out{default} = $default;
433 }
434  
435 6 ▶ if ( defined( my $cmds = delete $in{commands} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $cmds = delete $in{"commands"})) 5 1 6
436 5 ▶ croak "permissions 'commands' must be a hash reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cmds eq "HASH" 0 5 5
437 unless ref $cmds eq 'HASH';
438 5 for my $name ( sort keys %$cmds ) {
439 5 $out{commands}{$name} = _normalize_permission_spec( $name, $cmds->{$name} );
440 }
441 }
442  
443 1 ▶ croak "unknown permissions key(s): " . join( ', ', sort keys %in )
Branch: 1 branch
BranchTrueFalseTotal
if %in 1 0 1
444 if %in;
445  
446 0 return \%out;
447 } ## end sub _build_permissions
448  
449 # A spec is 'allow', 'deny', or a hash of rule lists. Entries that look like
450 # a number are treated as uids/gids; everything else as user/group names.
451 # Lists are turned into lookup hashes once, here, so per-request checks are
452 # cheap.
453 sub _normalize_permission_spec {
454 5 ▶ my ( $name, $spec ) = @_;
Subroutine _normalize_permission_spec: called CC=19 SCAR=40.9
455  
456 5 ▶ unless ( ref $spec ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $spec) 1 4 5
457 1 ▶ croak "permission for '$name' must be 'allow', 'deny', or a hash reference"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and $spec eq "allow" || $spec eq "deny" 1 0 1
Condition33%2/6
defined $spec and $spec eq "allow" || $spec eq "deny"
!ll&&!rl&&r
010
$spec eq "allow" or $spec eq "deny"
l!l&&r!l&&!r
001
MC/DC0%0/3
defined $spec and $spec eq "allow" || $spec eq "deny"
defined $spec $spec eq "allow" $spec eq "deny"
Truth table25%1/4
A and B or C
A= defined $specB= $spec eq "allow"C= $spec eq "deny"
ABCresult
0XX0
1000
11X1
1011
458 unless defined $spec && ( $spec eq 'allow' || $spec eq 'deny' );
459 0 return $spec;
460 }
461 4 ▶ croak "permission for '$name' must be 'allow', 'deny', or a hash reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 1 3 4
462 unless ref $spec eq 'HASH';
463  
464 3 my %in = %$spec;
465 3 my %norm;
466  
467 3 for my $key (qw(users deny_users)) {
468 5 ▶ next unless defined( my $list = delete $in{$key} );
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $list = delete $in{$key}) 4 1 5
469 1 ▶ croak "'$key' for '$name' must be an array reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 1 0 1
470 unless ref $list eq 'ARRAY';
471 0 for my $entry (@$list) {
472 0 ▶ if ( $entry =~ /\A[0-9]+\z/ ) { $norm{$key}{uids}{$entry} = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($entry =~ /\A[0-9]+\z/) { } 0 0 0
473 0 else { $norm{$key}{names}{$entry} = 1 }
474 }
475 }
476  
477 2 for my $key (qw(groups deny_groups)) {
478 4 ▶ next unless defined( my $list = delete $in{$key} );
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $list = delete $in{$key}) 4 0 4
479 0 ▶ croak "'$key' for '$name' must be an array reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 0 0 0
480 unless ref $list eq 'ARRAY';
481 0 for my $entry (@$list) {
482 0 ▶ if ( $entry =~ /\A[0-9]+\z/ ) { $norm{$key}{gids}{$entry} = 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($entry =~ /\A[0-9]+\z/) { } 0 0 0
483 0 else { $norm{$key}{names}{$entry} = 1 }
484 }
485 }
486  
487 2 ▶ if ( defined( my $check = delete $in{check} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $check = delete $in{"check"})) 1 1 2
488 1 ▶ croak "'check' for '$name' must be a code reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $check eq "CODE" 1 0 1
489 unless ref $check eq 'CODE';
490 0 $norm{check} = $check;
491 }
492  
493 1 ▶ croak "unknown permission key(s) for '$name': " . join( ', ', sort keys %in )
Branch: 1 branch
BranchTrueFalseTotal
if %in 1 0 1
494 if %in;
495  
496 0 return \%norm;
497 } ## end sub _normalize_permission_spec
498  
499 # Full group membership for a user, via the same getpw*/getgr* calls perl
500 # provides everywhere: they route through the platform's NSS (or its local
501 # equivalent), so files, LDAP, sssd, and friends all just work. Includes the
502 # primary group from the passwd entry and every secondary group whose member
503 # list names the user.
504 sub _resolve_user_groups {
505 0 ▶ my ( $uid, $username ) = @_;
Subroutine _resolve_user_groups: not called CC=9 SCAR=45.0
506  
507 0 my %names;
508 my %gids;
509  
510 0 eval {
511 0 my @pw = getpwuid($uid);
512 0 ▶ if (@pw) {
Branch: 1 branch
BranchTrueFalseTotal
if (@pw) 0 0 0
513 0 my $primary_gid = $pw[3];
514 0 $gids{$primary_gid} = 1;
515 0 my $primary_name = getgrgid($primary_gid);
516 0 ▶ $names{$primary_name} = 1 if defined $primary_name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $primary_name 0 0 0
517 }
518  
519 0 ▶ if ( defined $username && length $username ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $username and length $username) 0 0 0
Condition0%0/3
defined $username and length $username
!ll&&!rl&&r
000
MC/DC0%0/2
defined $username and length $username
defined $username length $username
Truth table0%0/3
A and B
A= defined $usernameB= length $username
ABresult
0X0
100
111
520 0 setgrent();
521 0 ▶ while ( my @gr = getgrent() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@gr) = getgrent) 0 0 0
522 0 my ( $group_name, $gid, $members ) = @gr[ 0, 2, 3 ];
523 next
524 unless defined $members
525 0 ▶ && grep { $_ eq $username } split ' ', $members;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $members and grep {$_ eq $username;} split(' ', $members, 0) 0 0 0
Condition0%0/3
defined $members and grep {$_ eq $username;} split(' ', $members, 0)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $members and grep {$_ eq $username;} split(' ', $members, 0)
defined $members grep {$_ eq $username;} split(' ', $members, 0)
Truth table0%0/3
A and B
A= defined $membersB= grep {$_ eq $username;} split(' ', $members, 0)
ABresult
0X0
100
111
526 0 $gids{$gid} = 1;
527 0 ▶ $names{$group_name} = 1 if defined $group_name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $group_name 0 0 0
528 }
529 0 endgrent();
530 } ## end if ( defined $username && length $username)
531 };
532  
533 return {
534 0 names => \%names,
535 gids => \%gids,
536 list => [ sort keys %names ],
537 };
538 } ## end sub _resolve_user_groups
539  
540 # Group info for an authenticated connection, resolved at most once per
541 # connection and cached on the client record -- group database lookups can be
542 # expensive (LDAP, NIS, ...) and must not be paid per request.
543 sub _client_groups {
544 0 ▶ my ( $self, $id ) = @_;
Subroutine _client_groups: not called CC=4 SCAR=30.0
545 0 ▶ my $client = $self->{clients}{$id} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $client = $self->{"clients"}{$id} or return undef 0 0 0
546 0 ▶ return undef unless defined $client->{auth_uid};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $client->{"auth_uid"} 0 0 0
547 0 ▶ $client->{auth_group_info} //= _resolve_user_groups( $client->{auth_uid}, $client->{auth_username} );
Condition0%0/3
$client->{"auth_group_info"} //= _resolve_user_groups($client->{"auth_uid"}, $client->{"auth_username"})
l!l&&r!l&&!r
000
MC/DC0%0/2
$client->{"auth_group_info"} //= _resolve_user_groups($client->{"auth_uid"}, $client->{"auth_username"})
$client->{"auth_group_info"} _resolve_user_groups($client->{"auth_uid"}, $client->{"auth_username"})
Truth table0%0/3
A //= B
A= $client->{"auth_group_info"}B= _resolve_user_groups($client->{"auth_uid"}, $client->{"auth_username"})
ABresult
1X1
011
000
548 0 return $client->{auth_group_info};
549 }
550  
551 # Decide whether the client behind wheel $id may run $cmd_name under the
552 # configured policy. Returns 1 to allow, or (0, $code, $message) to deny.
553 # Only called when a policy is configured.
554 sub _permission_verdict {
555 0 ▶ my ( $self, $id, $cmd_name, $ctx ) = @_;
Subroutine _permission_verdict: not called CC=33 SCAR=70.2
556  
557 # The handshake itself must always be reachable, or nobody could ever
558 # gain the identity the policy is written in terms of.
559 0 ▶ return 1 if $cmd_name eq 'auth_start' || $cmd_name eq 'auth_verify';
Branch: 1 branch
BranchTrueFalseTotal
if $cmd_name eq "auth_start" or $cmd_name eq "auth_verify" 0 0 0
Condition0%0/3
$cmd_name eq "auth_start" or $cmd_name eq "auth_verify"
l!l&&r!l&&!r
000
MC/DC0%0/2
$cmd_name eq "auth_start" or $cmd_name eq "auth_verify"
$cmd_name eq "auth_start" $cmd_name eq "auth_verify"
Truth table0%0/3
A or B
A= $cmd_name eq "auth_start"B= $cmd_name eq "auth_verify"
ABresult
1X1
011
000
560  
561 # A command's own rule wins; the special '%DEFAULT%' entry covers any
562 # command (known or not) without one; the 'default' string is last.
563 0 my $perms = $self->{permissions};
564 my $spec =
565 $perms->{commands}{$cmd_name}
566 // $perms->{commands}{'%DEFAULT%'}
567 0 ▶ // $perms->{default};
Condition0%0/6
($perms->{"commands"}{$cmd_name} // $perms->{"commands"}{"%DEFAULT%"}) // $perms->{"default"}
l!l&&r!l&&!r
000
$perms->{"commands"}{$cmd_name} // $perms->{"commands"}{"%DEFAULT%"}
l!l&&r!l&&!r
000
MC/DC0%0/3
($perms->{"commands"}{$cmd_name} // $perms->{"commands"}{"%DEFAULT%"}) // $perms->{"default"}
$perms->{"commands"}{$cmd_name} $perms->{"commands"}{"%DEFAULT%"} $perms->{"default"}
Truth table0%0/4
A // B // C
A= $perms->{"commands"}{$cmd_name}B= $perms->{"commands"}{"%DEFAULT%"}C= $perms->{"default"}
ABCresult
1XX1
01X1
0011
0000
568  
569 0 ▶ unless ( ref $spec ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $spec) 0 0 0
570 0 ▶ return 1 if $spec eq 'allow';
Branch: 1 branch
BranchTrueFalseTotal
if $spec eq "allow" 0 0 0
571 0 return ( 0, 'permission_denied', "permission denied: $cmd_name" );
572 }
573  
574 0 ▶ my $client = $self->{clients}{$id}
Branch: 1 branch
BranchTrueFalseTotal
my $client = $self->{"clients"}{$id} or return 0, "permission_denied", "permission denied: $cmd_name" 0 0 0
575 or return ( 0, 'permission_denied', "permission denied: $cmd_name" );
576  
577 # A rule written in terms of users or groups implies the connection must
578 # be authenticated, even when auth_required is off globally.
579 0 ▶ unless ( defined $client->{auth_uid} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $client->{"auth_uid"}) 0 0 0
580 0 return ( 0, 'auth_required', 'authentication required: call auth_start then auth_verify first' );
581 }
582  
583 0 my $uid = $client->{auth_uid};
584 0 ▶ my $username = $client->{auth_username} // '';
Condition0%0/2
$client->{"auth_username"} // ""
l!l
00
MC/DC0%0/1
$client->{"auth_username"} // ""
$client->{"auth_username"}
Truth table0%0/2
A
A= $client->{"auth_username"}
Aresult
11
00
585 0 my $groups = $self->_client_groups($id);
586 0 my $denial = "permission denied: user '$username' may not run '$cmd_name'";
587  
588 # Explicit denies win over everything.
589 0 ▶ if ( my $deny = $spec->{deny_users} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $deny = $spec->{"deny_users"}) 0 0 0
590 return ( 0, 'permission_denied', $denial )
591 0 ▶ if $deny->{names}{$username} || $deny->{uids}{$uid};
Branch: 1 branch
BranchTrueFalseTotal
if $deny->{"names"}{$username} or $deny->{"uids"}{$uid} 0 0 0
Condition0%0/3
$deny->{"names"}{$username} or $deny->{"uids"}{$uid}
l!l&&r!l&&!r
000
MC/DC0%0/2
$deny->{"names"}{$username} or $deny->{"uids"}{$uid}
$deny->{"names"}{$username} $deny->{"uids"}{$uid}
Truth table0%0/3
A or B
A= $deny->{"names"}{$username}B= $deny->{"uids"}{$uid}
ABresult
1X1
011
000
592 }
593 0 ▶ if ( my $deny = $spec->{deny_groups} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $deny = $spec->{"deny_groups"}) 0 0 0
594 0 for my $group_name ( keys %{ $groups->{names} } ) {
595 0 ▶ return ( 0, 'permission_denied', $denial ) if $deny->{names}{$group_name};
Branch: 1 branch
BranchTrueFalseTotal
if $deny->{"names"}{$group_name} 0 0 0
596 }
597 0 for my $gid ( keys %{ $groups->{gids} } ) {
598 0 ▶ return ( 0, 'permission_denied', $denial ) if $deny->{gids}{$gid};
Branch: 1 branch
BranchTrueFalseTotal
if $deny->{"gids"}{$gid} 0 0 0
599 }
600 }
601  
602 # With no allow criteria at all (a deny-list-only spec, or an empty
603 # hash), whoever survived the denies falls through to the default.
604 0 ▶ unless ( $spec->{users} || $spec->{groups} || $spec->{check} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spec->{"users"} or $spec->{"groups"} or $spec->{"check"}) 0 0 0
Condition0%0/6
$spec->{"users"} or $spec->{"groups"} or $spec->{"check"}
l!l&&r!l&&!r
000
$spec->{"users"} or $spec->{"groups"}
l!l&&r!l&&!r
000
MC/DC0%0/3
$spec->{"users"} or $spec->{"groups"} or $spec->{"check"}
$spec->{"users"} $spec->{"groups"} $spec->{"check"}
Truth table0%0/4
A or B or C
A= $spec->{"users"}B= $spec->{"groups"}C= $spec->{"check"}
ABCresult
1XX1
01X1
0011
0000
605 0 ▶ return 1 if $perms->{default} eq 'allow';
Branch: 1 branch
BranchTrueFalseTotal
if $perms->{"default"} eq "allow" 0 0 0
606 0 return ( 0, 'permission_denied', $denial );
607 }
608  
609 # Any matching allow criterion is enough.
610 0 ▶ if ( my $allow = $spec->{users} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $allow = $spec->{"users"}) 0 0 0
611 0 ▶ return 1 if $allow->{names}{$username} || $allow->{uids}{$uid};
Branch: 1 branch
BranchTrueFalseTotal
if $allow->{"names"}{$username} or $allow->{"uids"}{$uid} 0 0 0
Condition0%0/3
$allow->{"names"}{$username} or $allow->{"uids"}{$uid}
l!l&&r!l&&!r
000
MC/DC0%0/2
$allow->{"names"}{$username} or $allow->{"uids"}{$uid}
$allow->{"names"}{$username} $allow->{"uids"}{$uid}
Truth table0%0/3
A or B
A= $allow->{"names"}{$username}B= $allow->{"uids"}{$uid}
ABresult
1X1
011
000
612 }
613 0 ▶ if ( my $allow = $spec->{groups} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $allow = $spec->{"groups"}) 0 0 0
614 0 for my $group_name ( keys %{ $groups->{names} } ) {
615 0 ▶ return 1 if $allow->{names}{$group_name};
Branch: 1 branch
BranchTrueFalseTotal
if $allow->{"names"}{$group_name} 0 0 0
616 }
617 0 for my $gid ( keys %{ $groups->{gids} } ) {
618 0 ▶ return 1 if $allow->{gids}{$gid};
Branch: 1 branch
BranchTrueFalseTotal
if $allow->{"gids"}{$gid} 0 0 0
619 }
620 }
621 0 ▶ if ( my $check = $spec->{check} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $check = $spec->{"check"}) 0 0 0
622 0 my $ok = eval { $check->( $self, $ctx, $cmd_name ) };
623 0 ▶ if ($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 0 0 0
elsif ($ok) { } 0 0 0
624 0 carp "permission check for '$cmd_name' died: $@"; # fail closed
625 } elsif ($ok) {
626 0 return 1;
627 }
628 }
629  
630 0 return ( 0, 'permission_denied', $denial );
631 } ## end sub _permission_verdict
632  
633 sub _random_cookie {
634 2 ▶ my $bytes = '';
Subroutine _random_cookie: called CC=3 SCAR=12.0
635 2 ▶ if ( open( my $fh, '<:raw', '/dev/urandom' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<:raw", "/dev/urandom") 2 0 2
636 2 read( $fh, $bytes, 16 );
637 2 close($fh);
638 }
639 # Fallback: should never happen on a Unix system.
640 2 ▶ unless ( length($bytes) == 16 ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $bytes == 16) 0 2 2
641 0 $bytes = pack( 'N4', map { int( rand(2**32) ) } 1 .. 4 );
642 }
643 2 return unpack( 'H*', $bytes ); # 32 lowercase hex chars
644 }
645  
646 =head2 shutdown
647  
648 $server->shutdown;
649  
650 Stop accepting connections, close all clients, remove the socket file, and let
651 the session end.
652  
653 =cut
654  
655 sub shutdown {
656 2 ▶ my ($self) = @_;
Subroutine shutdown: called CC=1 SCAR=0.0
Pod documented
657 2 $poe_kernel->post( $self->{alias}, 'shutdown' );
658 2 return;
659 }
660  
661 #--- socket setup ----------------------------------------------------------
662  
663 sub _prepare_socket_path {
664 2 ▶ my ($self) = @_;
Subroutine _prepare_socket_path: called CC=6 SCAR=32.2
665 2 my $path = $self->{socket_path};
666  
667 2 ▶ return unless -e $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 2 0 2
668  
669 0 ▶ croak "socket_path '$path' exists and is not a socket"
Branch: 1 branch
BranchTrueFalseTotal
unless -S $path 0 0 0
670 unless -S $path;
671  
672 # If something is actively listening there, refuse rather than clobber it.
673 0 my $probe = IO::Socket::UNIX->new( Type => SOCK_STREAM, Peer => $path );
674 0 ▶ if ($probe) {
Branch: 1 branch
BranchTrueFalseTotal
if ($probe) 0 0 0
675 0 close $probe;
676 0 croak "Another server is already listening on '$path'";
677 }
678  
679 croak "Stale socket '$path' present but unlink_existing is disabled"
680 0 ▶ unless $self->{unlink_existing};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"unlink_existing"} 0 0 0
681  
682 0 ▶ unlink $path
Branch: 1 branch
BranchTrueFalseTotal
unlink $path or croak("Could not remove stale socket '${path}': $!") 0 0 0
683 or croak "Could not remove stale socket '$path': $!";
684 0 return;
685 } ## end sub _prepare_socket_path
686  
687 #--- POE: session lifecycle ------------------------------------------------
688  
689 sub _poe_start {
690 2 ▶ my ( $self, $kernel ) = @_[ OBJECT, KERNEL ];
Subroutine _poe_start: called CC=3 SCAR=12.7
691  
692 2 $kernel->alias_set( $self->{alias} );
693  
694 $self->{listener} = POE::Wheel::SocketFactory->new(
695 SocketDomain => PF_UNIX,
696 SocketType => SOCK_STREAM,
697 BindAddress => $self->{socket_path},
698 2 SuccessEvent => 'got_connection',
699 FailureEvent => 'listen_error',
700 );
701  
702 2 ▶ if ( defined $self->{socket_mode} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"socket_mode"}) 0 2 2
703 chmod $self->{socket_mode}, $self->{socket_path}
704 0 ▶ or carp "chmod on '$self->{socket_path}' failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
chmod $self->{"socket_mode"}, $self->{"socket_path"} or carp(qq[chmod on '$self->{"socket_path"}' failed: $!]) 0 0 0
705 }
706 2 return;
707 } ## end sub _poe_start
708  
709 sub _poe_stop {
710 2 ▶ my ($self) = $_[OBJECT];
Subroutine _poe_stop: called CC=1 SCAR=0.0
711 2 $self->_remove_socket_file;
712 2 return;
713 }
714  
715 sub _poe_shutdown {
716 2 ▶ my ( $self, $kernel ) = @_[ OBJECT, KERNEL ];
Subroutine _poe_shutdown: called CC=1 SCAR=0.0
717 2 delete $self->{listener}; # stop accepting new connections
718 2 %{ $self->{clients} } = (); # drop wheels -> close client sockets
719 2 $kernel->alias_remove( $self->{alias} );
720 2 $self->_remove_socket_file;
721 2 return;
722 }
723  
724 sub _poe_register_command {
725 0 ▶ my ( $self, $name, $code ) = @_[ OBJECT, ARG0, ARG1 ];
Subroutine _poe_register_command: not called CC=2 SCAR=17.9
726 0 eval { $self->register( $name => $code ) };
727 0 ▶ carp "register_command failed: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
728 0 return;
729 }
730  
731 sub _remove_socket_file {
732 4 ▶ my ($self) = @_;
Subroutine _remove_socket_file: called CC=3 SCAR=11.0
733 4 my $path = $self->{socket_path};
734 4 ▶ unlink $path if defined $path && -S $path;
Branch: 1 branch
BranchTrueFalseTotal
if defined $path and -S $path 2 2 4
Condition66%2/3
defined $path and -S $path
!ll&&!rl&&r
022
MC/DC50%1/2
defined $path and -S $path
defined $path -S $path
Truth table66%2/3
A and B
A= defined $pathB= -S $path
ABresult
0X0
100
111
735 4 return;
736 }
737  
738 #--- POE: listener events --------------------------------------------------
739  
740 sub _poe_listen_error {
741 0 ▶ my ( $self, $op, $errnum, $errstr ) = @_[ OBJECT, ARG0, ARG1, ARG2 ];
Subroutine _poe_listen_error: not called CC=2 SCAR=17.9
742 0 carp "listen error during $op: $errstr ($errnum)";
743 0 ▶ $self->{on_error}->( "listen:$op", $errnum, $errstr ) if $self->{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"on_error"} 0 0 0
744 0 delete $self->{listener};
745 0 return;
746 }
747  
748 sub _poe_got_connection {
749 4 ▶ my ( $self, $socket ) = @_[ OBJECT, ARG0 ];
Subroutine _poe_got_connection: called CC=1 SCAR=0.0
750  
751 4 my $wheel = POE::Wheel::ReadWrite->new(
752 Handle => $socket,
753 Driver => POE::Driver::SysRW->new,
754 Filter => POE::Filter::Line->new( Literal => "\n" ),
755 InputEvent => 'client_input',
756 ErrorEvent => 'client_error',
757 FlushedEvent => 'client_flushed',
758 );
759  
760 4 $self->{clients}{ $wheel->ID } = {
761 wheel => $wheel,
762 close_after_flush => 0,
763 auth_cookie => undef,
764 auth_uid => undef,
765 auth_username => undef,
766 auth_group_info => undef, # filled once by _client_groups
767 };
768 4 return;
769 } ## end sub _poe_got_connection
770  
771 #--- POE: per-client events ------------------------------------------------
772  
773 sub _poe_client_input {
774 15 ▶ my ( $self, $line, $id ) = @_[ OBJECT, ARG0, ARG1 ];
Subroutine _poe_client_input: called CC=20 SCAR=37.7
775  
776 15 ▶ return unless $self->{clients}{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"clients"}{$id} 0 15 15
777 15 ▶ return unless defined $line && $line =~ /\S/; # ignore blank keepalives
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line and $line =~ /\S/ 0 15 15
Condition33%1/3
defined $line and $line =~ /\S/
!ll&&!rl&&r
0015
MC/DC0%0/2
defined $line and $line =~ /\S/
defined $line $line =~ /\S/
Truth table33%1/3
A and B
A= defined $lineB= $line =~ /\S/
ABresult
0X0
100
111
778  
779 15 my $request;
780 15 ▶ unless ( eval { $request = $self->{json}->decode($line); 1 } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $request = $self->{"json"}->decode($line); 1 } }) 0 15 15
781 0 $self->_send(
782 $id,
783 {
784 status => 'error',
785 error => 'invalid JSON: ' . _clean_err($@),
786 }
787 );
788 0 return;
789 } ## end unless ( eval { $request = $self->{json}->decode...})
790  
791 15 ▶ unless ( ref $request eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $request eq "HASH") 0 15 15
792 0 $self->_send(
793 $id,
794 {
795 status => 'error',
796 error => 'request must be a JSON object',
797 }
798 );
799 0 return;
800 } ## end unless ( ref $request eq 'HASH' )
801  
802 15 my $req_id = $request->{id};
803 15 ▶ my $cmd_name = $request->{command} // $request->{cmd};
Condition33%1/3
$request->{"command"} // $request->{"cmd"}
l!l&&r!l&&!r
1500
MC/DC0%0/2
$request->{"command"} // $request->{"cmd"}
$request->{"command"} $request->{"cmd"}
Truth table33%1/3
A // B
A= $request->{"command"}B= $request->{"cmd"}
ABresult
1X1
011
000
804  
805 15 my $ctx = POE::Component::Server::JSONUnix::Context->_new(
806 server => $self,
807 wheel_id => $id,
808 req_id => $req_id,
809 command => $cmd_name,
810 request => $request,
811 );
812  
813 15 ▶ unless ( defined $cmd_name ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cmd_name) 0 15 15
814 0 $ctx->error("missing 'command' field");
815 0 return;
816 }
817  
818 # Enforce auth_required: only auth_start and auth_verify bypass the gate.
819 15 ▶ if ( $self->{auth_required} && !defined( $self->{clients}{$id}{auth_uid} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"auth_required"} and not defined $self->{"clients"}{$id}{"auth_uid"}) 5 10 15
Condition100%3/3
$self->{"auth_required"} and not defined $self->{"clients"}{$id}{"auth_uid"}
!ll&&!rl&&r
915
MC/DC100%2/2
$self->{"auth_required"} and not defined $self->{"clients"}{$id}{"auth_uid"}
$self->{"auth_required"} not defined $self->{"clients"}{$id}{"auth_uid"}
Truth table100%3/3
A and not(B)
A= $self->{"auth_required"}B= not defined $self->{"clients"}{$id}{"auth_uid"}
ABresult
0X0
100
111
820 5 ▶ unless ( $cmd_name eq 'auth_start' || $cmd_name eq 'auth_verify' ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cmd_name eq "auth_start" or $cmd_name eq "auth_verify") 1 4 5
Condition100%3/3
$cmd_name eq "auth_start" or $cmd_name eq "auth_verify"
l!l&&r!l&&!r
221
MC/DC100%2/2
$cmd_name eq "auth_start" or $cmd_name eq "auth_verify"
$cmd_name eq "auth_start" $cmd_name eq "auth_verify"
Truth table100%3/3
A or B
A= $cmd_name eq "auth_start"B= $cmd_name eq "auth_verify"
ABresult
1X1
011
000
821 1 $ctx->error('authentication required: call auth_start then auth_verify first');
822 1 return;
823 }
824 }
825  
826 # Enforce the optional permission policy. Runs before the unknown-command
827 # check so a default-deny server does not reveal which commands exist.
828 14 ▶ if ( $self->{permissions} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"permissions"}) 0 14 14
829 0 my ( $allowed, $code, $denial ) = $self->_permission_verdict( $id, $cmd_name, $ctx );
830 0 ▶ unless ($allowed) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($allowed) 0 0 0
831 0 $ctx->error( $denial, code => $code );
832 0 return;
833 }
834 }
835  
836 14 my $handler = $self->{commands}{$cmd_name};
837 14 ▶ unless ($handler) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($handler) 1 13 14
838 1 $ctx->error("unknown command: $cmd_name");
839 1 return;
840 }
841  
842 13 my @ret = eval { $handler->( $self, $request, $ctx ) };
843 13 ▶ if ( my $err = $@ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 13 13
844 0 ▶ unless ( $ctx->responded ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ctx->responded) 0 0 0
845 0 ▶ if ( ref $err eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $err eq 'HASH') { } 0 0 0
846 0 $ctx->respond( { status => 'error', %$err } );
847 } else {
848 0 $ctx->error( _clean_err($err) );
849 }
850 }
851 0 return;
852 } ## end if ( my $err = $@ )
853  
854 13 ▶ return if $ctx->responded; # handler already answered (any path)
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->responded 0 13 13
855 13 ▶ return unless defined $ret[0]; # undef return => async; answers later
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ret[0] 2 11 13
856 11 $ctx->respond_result( $ret[0] ); # sync return => wrap as {ok, result}
857 11 return;
858 } ## end sub _poe_client_input
859  
860 sub _poe_client_error {
861 2 ▶ my ( $self, $op, $errnum, $errstr, $id ) = @_[ OBJECT, ARG0, ARG1, ARG2, ARG3 ];
Subroutine _poe_client_error: called CC=4 SCAR=19.4
862  
863 # operation 'read' with errnum 0 is a normal EOF (client hung up).
864 2 ▶ if ( $self->{on_error} && !( $op eq 'read' && $errnum == 0 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"on_error"} and not $op eq "read" && $errnum == 0) 0 2 2
Condition16%1/6
$self->{"on_error"} and not $op eq "read" && $errnum == 0
!ll&&!rl&&r
200
$op eq 'read' && $errnum == 0
!ll&&!rl&&r
000
MC/DC0%0/3
$self->{"on_error"} and not $op eq "read" && $errnum == 0
$self->{"on_error"} $op eq 'read' $errnum == 0
Truth table25%1/4
A and not(B && C)
A= $self->{"on_error"}B= $op eq 'read'C= $errnum == 0
ABCresult
0XX0
1110
10X1
1101
865 0 eval { $self->{on_error}->( $op, $errnum, $errstr, $id ) };
866 }
867 2 $self->_close_client($id);
868 2 return;
869 } ## end sub _poe_client_error
870  
871 sub _poe_client_flushed {
872 11 ▶ my ( $self, $id ) = @_[ OBJECT, ARG0 ];
Subroutine _poe_client_flushed: called CC=3 SCAR=11.4
873 11 ▶ my $client = $self->{clients}{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $client = $self->{"clients"}{$id} or return 0 11 11
874 11 ▶ $self->_close_client($id) if $client->{close_after_flush};
Branch: 1 branch
BranchTrueFalseTotal
if $client->{"close_after_flush"} 0 11 11
875 11 return;
876 }
877  
878 #--- sending / closing -----------------------------------------------------
879  
880 sub _send {
881 14 ▶ my ( $self, $id, $data ) = @_;
Subroutine _send: called CC=4 SCAR=14.6
882 14 ▶ my $client = $self->{clients}{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $client = $self->{"clients"}{$id} or return 0 14 14
883 14 ▶ my $wheel = $client->{wheel} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $wheel = $client->{"wheel"} or return 0 14 14
884  
885 14 my $json = eval { $self->{json}->encode($data) };
886 14 ▶ unless ( defined $json ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $json) 0 14 14
887 $json = $self->{json}->encode(
888 {
889 0 status => 'error',
890 error => 'internal error: response could not be serialised',
891 }
892 );
893 }
894 14 $wheel->put($json); # Filter::Line appends the trailing newline
895 14 return;
896 } ## end sub _send
897  
898 sub _close_client {
899 2 ▶ my ( $self, $id ) = @_;
Subroutine _close_client: called CC=1 SCAR=0.0
900 2 delete $self->{clients}{$id}; # destroying the wheel closes the socket
901 2 return;
902 }
903  
904 sub _close_client_after_flush {
905 0 ▶ my ( $self, $id ) = @_;
Subroutine _close_client_after_flush: not called CC=4 SCAR=30.0
906 0 ▶ my $client = $self->{clients}{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $client = $self->{"clients"}{$id} or return 0 0 0
907 0 my $wheel = $client->{wheel};
908 0 ▶ if ( $wheel && $wheel->get_driver_out_octets ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wheel and $wheel->get_driver_out_octets) { } 0 0 0
Condition0%0/3
$wheel and $wheel->get_driver_out_octets
!ll&&!rl&&r
000
MC/DC0%0/2
$wheel and $wheel->get_driver_out_octets
$wheel $wheel->get_driver_out_octets
Truth table0%0/3
A and B
A= $wheelB= $wheel->get_driver_out_octets
ABresult
0X0
100
111
909 0 $client->{close_after_flush} = 1;
910 } else {
911 0 $self->_close_client($id);
912 }
913 0 return;
914 } ## end sub _close_client_after_flush
915  
916 sub _clean_err {
917 0 ▶ my ($msg) = @_;
Subroutine _clean_err: not called CC=1 SCAR=6.9
918 0 $msg = "$msg";
919 0 $msg =~ s/\s+at \S+ line \d+\.?.*//s; # strip "at file line N ..."
920 0 $msg =~ s/\s+\z//;
921 0 return $msg;
922 }
923  
924 #===========================================================================
925 package POE::Component::Server::JSONUnix::Context;
926 #===========================================================================
927 # Handed to every command handler. A handler can answer synchronously by
928 # returning a value, or asynchronously by stashing $ctx and calling one of
929 # these methods later (e.g. after a timer fires or a backend request returns).
930  
931 9 our $VERSION = '0.01';
932  
933 sub _new {
934 25 ▶ my ( $class, %a ) = @_;
Subroutine _new: called CC=1 SCAR=0.0
935 return bless {
936 server => $a{server},
937 wheel_id => $a{wheel_id},
938 req_id => $a{req_id},
939 command => $a{command},
940 request => $a{request},
941 25 responded => 0,
942 }, $class;
943 } ## end sub _new
944  
945 1 ▶sub request { $_[0]{request} }
Subroutine request: called CC=1 SCAR=0.0
946 1 ▶sub command { $_[0]{command} }
Subroutine command: called CC=1 SCAR=0.0
947 1 ▶sub id { $_[0]{req_id} }
Subroutine id: called CC=1 SCAR=0.0
948 14 ▶sub responded { $_[0]{responded} }
Subroutine responded: called CC=1 SCAR=0.0
949  
950 # Auth accessors — defined after a successful auth_verify.
951 sub authenticated {
952 5 ▶ my ($self) = @_;
Subroutine authenticated: called CC=1 SCAR=0.0
953 5 return defined $self->{server}{clients}{ $self->{wheel_id} }{auth_uid};
954 }
955  
956 sub uid {
957 6 ▶ my ($self) = @_;
Subroutine uid: called CC=1 SCAR=0.0
958 6 return $self->{server}{clients}{ $self->{wheel_id} }{auth_uid};
959 }
960  
961 sub username {
962 4 ▶ my ($self) = @_;
Subroutine username: called CC=1 SCAR=0.0
963 4 return $self->{server}{clients}{ $self->{wheel_id} }{auth_username};
964 }
965  
966 # Group names of the authenticated user (empty before authentication).
967 # Resolved via NSS at most once per connection, then served from the cache.
968 sub groups {
969 0 ▶ my ($self) = @_;
Subroutine groups: not called CC=2 SCAR=17.9
970 0 my $groups = $self->{server}->_client_groups( $self->{wheel_id} );
971 0 ▶ return $groups ? [ @{ $groups->{list} } ] : [];
Branch: 1 branch
BranchTrueFalseTotal
$groups ? : 0 0 0
972 }
973  
974 # Membership test by group name or numeric gid.
975 sub in_group {
976 0 ▶ my ( $self, $group ) = @_;
Subroutine in_group: not called CC=5 SCAR=34.0
977 0 ▶ return 0 unless defined $group;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $group 0 0 0
978 my $groups = $self->{server}->_client_groups( $self->{wheel_id} )
979 0 ▶ or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $groups = $self->{"server"}->_client_groups($self->{"wheel_id"}) or return 0 0 0 0
980 0 ▶ my $set = $group =~ /\A[0-9]+\z/ ? $groups->{gids} : $groups->{names};
Branch: 1 branch
BranchTrueFalseTotal
$group =~ /\A[0-9]+\z/ ? : 0 0 0
981 0 ▶ return $set->{$group} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$set->{$group} ? : 0 0 0
982 }
983  
984 # Would this connection be allowed to run $command_name right now? Always
985 # true when no permission policy is configured.
986 sub may {
987 0 ▶ my ( $self, $command_name ) = @_;
Subroutine may: not called CC=3 SCAR=24.8
988 0 ▶ return 1 unless $self->{server}{permissions};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"}{"permissions"} 0 0 0
989 0 my ($allowed) = $self->{server}->_permission_verdict( $self->{wheel_id}, $command_name, $self );
990 0 ▶ return $allowed ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$allowed ? : 0 0 0
991 }
992  
993 # Send a full response envelope. status defaults to 'ok'; the request id, if
994 # present, is echoed back automatically. Only the first call has any effect.
995 sub respond {
996 19 ▶ my ( $self, $envelope ) = @_;
Subroutine respond: called CC=5 SCAR=16.1
997 19 ▶ return if $self->{responded};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"responded"} 1 18 19
998 18 $self->{responded} = 1;
999  
1000 18 my %out = %$envelope;
1001 18 ▶ $out{status} //= 'ok';
Condition100%2/2
$out{"status"} //= "ok"
l!l
162
MC/DC100%1/1
$out{"status"} //= "ok"
$out{"status"}
Truth table100%2/2
A
A= $out{"status"}
Aresult
11
00
1002 $out{id} = $self->{req_id}
1003 18 ▶ if defined $self->{req_id} && !exists $out{id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"req_id"} and not exists $out{"id"} 17 1 18
Condition66%2/3
defined $self->{"req_id"} and not exists $out{"id"}
!ll&&!rl&&r
1017
MC/DC50%1/2
defined $self->{"req_id"} and not exists $out{"id"}
defined $self->{"req_id"} not exists $out{"id"}
Truth table66%2/3
A and not(B)
A= defined $self->{"req_id"}B= not exists $out{"id"}
ABresult
0X0
100
111
1004  
1005 18 $self->{server}->_send( $self->{wheel_id}, \%out );
1006 18 return;
1007 } ## end sub respond
1008  
1009 # Convenience: respond with {status:ok, result:<data>}.
1010 sub respond_result {
1011 13 ▶ my ( $self, $result ) = @_;
Subroutine respond_result: called CC=1 SCAR=0.0
1012 13 return $self->respond( { status => 'ok', result => $result } );
1013 }
1014  
1015 # Convenience: respond with {status:error, error:<message>, ...extra}.
1016 sub error {
1017 3 ▶ my ( $self, $message, %extra ) = @_;
Subroutine error: called CC=1 SCAR=0.0
1018 3 return $self->respond( { status => 'error', error => $message, %extra } );
1019 }
1020  
1021 # Close this client's connection once any queued output has been flushed.
1022 sub close {
1023 0 ▶ my ($self) = @_;
Subroutine close: not called CC=1 SCAR=6.9
1024 0 $self->{server}->_close_client_after_flush( $self->{wheel_id} );
1025 0 return;
1026 }
1027  
1028 9 1;
1029  
1030 __END__
↑ Summary JSONUnix/Client.pm »