blib/lib/SignalWire/SWML/Service.pm

filter: Statementstmt 87.8% 245 / 279 Branchbran 73.4% 72 / 98 Conditioncond 60.3% 67 / 111 MC/DCmcdc 35.9% 23 / 64 Subroutinesub 84.7% 50 / 59 Podpod 0.0% 0 / 22 totaltotal 72.2% 457 / 633 CC 95 SCAR 23.1
CC
95
Cov
79%
_handle_swaig_request
36.7
validate_basic_auth
20.0
__ANON__
13.8
CRAP 10.1
« blib/lib/SignalWire/Relay/Action.pm ↑ Summary blib/lib/SignalWire/Security/SessionManager.pm »
1 package SignalWire::SWML::Service;
2 44 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 44 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 44 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 44 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 44 ▶use Digest::SHA qw(hmac_sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 44 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 44 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 44 ▶use SignalWire::SWML::Document;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 44 ▶use SignalWire::SWML::Schema;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 44 ▶use SignalWire::Logging;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 has 'name' => (
14 is => 'rw',
15 4 ▶ default => sub { 'service' },
Subroutine __ANON__: called CC=1 SCAR=0.0
16 44 );
17  
18 has 'route' => (
19 is => 'rw',
20 405 ▶ default => sub { '/' },
Subroutine __ANON__: called CC=1 SCAR=0.0
21 44 );
22  
23 has 'host' => (
24 is => 'rw',
25 438 ▶ default => sub { $ENV{SWML_HOST} // '0.0.0.0' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$ENV{"SWML_HOST"} // "0.0.0.0"
l!l
0438
MC/DC0%0/1
$ENV{"SWML_HOST"} // "0.0.0.0"
$ENV{"SWML_HOST"}
Truth table50%1/2
A
A= $ENV{"SWML_HOST"}
Aresult
11
00
26 44 );
27  
28 has 'port' => (
29 is => 'rw',
30 29 ▶ default => sub { $ENV{SWML_PORT} // 3000 },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$ENV{"SWML_PORT"} // 3000
l!l
029
MC/DC0%0/1
$ENV{"SWML_PORT"} // 3000
$ENV{"SWML_PORT"}
Truth table50%1/2
A
A= $ENV{"SWML_PORT"}
Aresult
11
00
31 44 );
32  
33 has 'basic_auth_user' => (
34 is => 'rw',
35 8 ▶ default => sub { $ENV{SWML_BASIC_AUTH_USER} // _random_hex(16) },
Subroutine __ANON__: called CC=2 SCAR=9.2
Condition33%1/3
$ENV{"SWML_BASIC_AUTH_USER"} // _random_hex(16)
l!l&&r!l&&!r
080
MC/DC0%0/2
$ENV{"SWML_BASIC_AUTH_USER"} // _random_hex(16)
$ENV{"SWML_BASIC_AUTH_USER"} _random_hex(16)
Truth table33%1/3
A // B
A= $ENV{"SWML_BASIC_AUTH_USER"}B= _random_hex(16)
ABresult
1X1
011
000
36 44 );
37  
38 has 'basic_auth_password' => (
39 is => 'rw',
40 8 ▶ default => sub { $ENV{SWML_BASIC_AUTH_PASSWORD} // _random_hex(32) },
Subroutine __ANON__: called CC=2 SCAR=9.2
Condition33%1/3
$ENV{"SWML_BASIC_AUTH_PASSWORD"} // _random_hex(32)
l!l&&r!l&&!r
080
MC/DC0%0/2
$ENV{"SWML_BASIC_AUTH_PASSWORD"} // _random_hex(32)
$ENV{"SWML_BASIC_AUTH_PASSWORD"} _random_hex(32)
Truth table33%1/3
A // B
A= $ENV{"SWML_BASIC_AUTH_PASSWORD"}B= _random_hex(32)
ABresult
1X1
011
000
41 44 );
42  
43 has 'document' => (
44 is => 'rw',
45 444 ▶ default => sub { SignalWire::SWML::Document->new() },
Subroutine __ANON__: called CC=1 SCAR=0.0
46 44 );
47  
48 # SWAIG tool registry — lifted from AgentBase so any Service (sidecar,
49 # non-agent verb host) can register and dispatch SWAIG functions.
50 has 'tools' => (
51 is => 'rw',
52 441 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
53 44 );
54  
55 has 'tool_order' => (
56 is => 'rw',
57 441 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
58 44 );
59  
60 has 'routing_callbacks' => (
61 is => 'rw',
62 444 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
63 44 );
64  
65 has '_logger' => (
66 is => 'ro',
67 444 ▶ default => sub { SignalWire::Logging->get_logger('signalwire.swml_service') },
Subroutine __ANON__: called CC=1 SCAR=0.0
68 44 );
69  
70 # Python parity: schema_utils / verb_registry / security accessors.
71 # In Python these are instance attributes set in __init__; cross-language
72 # audit treats them as zero-arg getters. The Perl singletons / lazy-built
73 # objects expose the same accessor surface.
74 has 'schema_utils' => (
75 is => 'lazy',
76 1 ▶ default => sub { SignalWire::SWML::Schema->instance },
Subroutine __ANON__: called CC=1 SCAR=0.0
77 44 );
78  
79 has 'verb_registry' => (
80 is => 'lazy',
81 1 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
82 # Tiny stand-in registry for verb-handler dispatch. The Perl SDK
83 # uses AUTOLOAD against the schema for verb lookup; this hashref
84 # mirrors Python's VerbHandlerRegistry surface (handlers indexed
85 # by verb name) so callers can introspect / extend it.
86 1 return { handlers => {} };
87 },
88 44 );
89  
90 has 'security' => (
91 is => 'lazy',
92 1 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
93 1 my ($self) = @_;
94 # Python's SWMLService.security is a SecurityConfig instance that
95 # bundles SSL + basic-auth + CORS knobs. Perl SWMLService models
96 # those as direct ``has`` attributes (basic_auth_user, etc.); the
97 # ``security`` accessor returns a hashref view of the same data so
98 # cross-port code that reaches into ``$svc->security->{...}`` keeps
99 # working. Wrap in a blessed Moo-ish object so introspection still
100 # sees it as an object (Python parity).
101 1 require SignalWire::Security::SessionManager;
102 return $self->{_session_manager}
103 1 ▶ //= SignalWire::Security::SessionManager->new();
Condition33%1/3
$self->{"_session_manager"} //= "SignalWire::Security::SessionManager"->new
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->{"_session_manager"} //= "SignalWire::Security::SessionManager"->new
$self->{"_session_manager"} "SignalWire::Security::SessionManager"->new
Truth table33%1/3
A //= B
A= $self->{"_session_manager"}B= "SignalWire::Security::SessionManager"->new
ABresult
1X1
011
000
104 },
105 44 );
106  
107 # Function-name validation pattern matches the other ports.
108 44 my $SWAIG_FN_NAME = qr/\A[a-zA-Z_][a-zA-Z0-9_]*\z/;
109  
110 # Schema-driven verb auto-vivification via AUTOLOAD
111 44 our $AUTOLOAD;
112 44 my $_schema;
113  
114 149 ▶sub _get_schema {
Subroutine _get_schema: called CC=2 SCAR=7.1
115 149 ▶ $_schema //= SignalWire::SWML::Schema->instance();
Condition66%2/3
$_schema //= "SignalWire::SWML::Schema"->instance
l!l&&r!l&&!r
106430
MC/DC0%0/2
$_schema //= "SignalWire::SWML::Schema"->instance
$_schema "SignalWire::SWML::Schema"->instance
Truth table66%2/3
A //= B
A= $_schemaB= "SignalWire::SWML::Schema"->instance
ABresult
1X1
011
000
116 149 return $_schema;
117 }
118  
119 439 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=7 SCAR=19.5
120 439 my $self = shift;
121 439 my $method = $AUTOLOAD;
122 439 $method =~ s/.*:://; # strip package name
123  
124 439 ▶ return if $method eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 433 6 439
125  
126 6 my $schema = _get_schema();
127 6 ▶ if ($schema->has_verb($method)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->has_verb($method)) 5 1 6
128 # For 'sleep' verb: takes an integer (milliseconds), not a hashref
129 5 ▶ my $section = shift // 'main';
Condition100%2/2
shift() // "main"
l!l
41
MC/DC100%1/1
shift() // "main"
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
130 5 my $data;
131 5 ▶ if ($method eq 'sleep') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq 'sleep') { } 1 4 5
132 1 ▶ $data = shift // 0;
Condition50%1/2
shift() // 0
l!l
10
MC/DC0%0/1
shift() // 0
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
133 # Ensure it is a numeric value
134 1 $data = int($data);
135 } else {
136 4 ▶ $data = shift // {};
Condition100%2/2
shift() // {}
l!l
31
MC/DC100%1/1
shift() // {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
137 }
138 5 $self->document->add_verb($section, $method, $data);
139 5 return $self;
140 }
141  
142 1 die "Can't locate method \"$method\" via package \"" . ref($self) . "\"";
143 }
144  
145 # Provide can() that knows about schema verbs
146 2056 ▶sub can {
Subroutine can: called CC=4 SCAR=15.2
Pod undocumented
147 2056 my ($self, $method) = @_;
148 # Check if it is a regular method first
149 2056 my $code = $self->SUPER::can($method);
150 2056 ▶ return $code if $code;
Branch: 1 branch
BranchTrueFalseTotal
if $code 1913 143 2056
151 # Check schema verbs
152 143 my $schema = _get_schema();
153 143 ▶ if ($schema && $schema->has_verb($method)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema and $schema->has_verb($method)) 0 143 143
Condition33%1/3
$schema and $schema->has_verb($method)
!ll&&!rl&&r
01430
MC/DC0%0/2
$schema and $schema->has_verb($method)
$schema $schema->has_verb($method)
Truth table33%1/3
A and B
A= $schemaB= $schema->has_verb($method)
ABresult
0X0
100
111
154 0 ▶ return sub { $self->$method(@_) };
Subroutine __ANON__: not called CC=1 SCAR=6.9
155 }
156 143 return undef;
157 }
158  
159 16 ▶sub _random_hex {
Subroutine _random_hex: called CC=4 SCAR=15.2
160 16 my ($len) = @_;
161 # Use /dev/urandom for cryptographically secure random bytes.
162 # Die on failure rather than falling back to weak randomness.
163 16 ▶ if (open my $fh, '<:raw', '/dev/urandom') {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<:raw", "/dev/urandom") 16 0 16
164 16 my $bytes;
165 16 my $read = read($fh, $bytes, $len);
166 16 close $fh;
167 16 ▶ if (defined $read && $read == $len) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $read and $read == $len) 16 0 16
Condition33%1/3
defined $read and $read == $len
!ll&&!rl&&r
0016
MC/DC0%0/2
defined $read and $read == $len
defined $read $read == $len
Truth table33%1/3
A and B
A= defined $readB= $read == $len
ABresult
0X0
100
111
168 16 return unpack('H*', $bytes);
169 }
170 }
171 0 die "FATAL: Cannot generate secure random bytes - /dev/urandom unavailable or read failed. "
172 . "Set SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD environment variables instead.\n";
173 }
174  
175 18 ▶sub _timing_safe_compare {
Subroutine _timing_safe_compare: called CC=1 SCAR=0.0
176 18 my ($a, $b) = @_;
177 # Compare HMAC of both values with a fixed key for constant-time comparison
178 18 my $key = 'timing-safe-comparison-key';
179 18 my $hmac_a = hmac_sha256_hex($a, $key);
180 18 my $hmac_b = hmac_sha256_hex($b, $key);
181 18 return $hmac_a eq $hmac_b;
182 }
183  
184 # Validate provided basic-auth credentials. (Python parity:
185 # AuthMixin.validate_basic_auth(username, password).)
186 0 ▶sub validate_basic_auth {
Subroutine validate_basic_auth: not called CC=4 SCAR=30.0
Pod undocumented
187 0 my ($self, $username, $password) = @_;
188 0 my $u = $self->basic_auth_user;
189 0 my $p = $self->basic_auth_password;
190 0 ▶ return 0 unless defined $u && defined $p;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $u and defined $p 0 0 0
Condition0%0/3
defined $u and defined $p
!ll&&!rl&&r
000
MC/DC0%0/2
defined $u and defined $p
defined $u defined $p
Truth table0%0/3
A and B
A= defined $uB= defined $p
ABresult
0X0
100
111
191 0 ▶ return _timing_safe_compare($username, $u)
Condition0%0/3
_timing_safe_compare($username, $u) && _timing_safe_compare($password, $p)
!ll&&!rl&&r
000
MC/DC0%0/2
_timing_safe_compare($username, $u) && _timing_safe_compare($password, $p)
_timing_safe_compare($username, $u) _timing_safe_compare($password, $p)
Truth table0%0/3
A && B
A= _timing_safe_compare($username, $u)B= _timing_safe_compare($password, $p)
ABresult
0X0
100
111
192 && _timing_safe_compare($password, $p);
193 }
194  
195 # Returns ($user, $password) by default; if $include_source is truthy,
196 # returns ($user, $password, $source) where $source is "provided",
197 # "environment", or "generated". (Python parity:
198 # AuthMixin.get_basic_auth_credentials(include_source=False).)
199 7 ▶sub get_basic_auth_credentials {
Subroutine get_basic_auth_credentials: called CC=12 SCAR=25.3
Pod undocumented
200 7 my ($self, $include_source) = @_;
201 7 ▶ my $user = $self->basic_auth_user // '';
Condition50%1/2
$self->basic_auth_user // ""
l!l
70
MC/DC0%0/1
$self->basic_auth_user // ""
$self->basic_auth_user
Truth table50%1/2
A
A= $self->basic_auth_user
Aresult
11
00
202 7 ▶ my $pass = $self->basic_auth_password // '';
Condition50%1/2
$self->basic_auth_password // ""
l!l
70
MC/DC0%0/1
$self->basic_auth_password // ""
$self->basic_auth_password
Truth table50%1/2
A
A= $self->basic_auth_password
Aresult
11
00
203 7 ▶ return ($user, $pass) unless $include_source;
Branch: 1 branch
BranchTrueFalseTotal
unless $include_source 3 4 7
204 4 ▶ my $env_user = $ENV{SWML_BASIC_AUTH_USER} // '';
Condition100%2/2
$ENV{"SWML_BASIC_AUTH_USER"} // ""
l!l
13
MC/DC100%1/1
$ENV{"SWML_BASIC_AUTH_USER"} // ""
$ENV{"SWML_BASIC_AUTH_USER"}
Truth table100%2/2
A
A= $ENV{"SWML_BASIC_AUTH_USER"}
Aresult
11
00
205 4 ▶ my $env_pass = $ENV{SWML_BASIC_AUTH_PASSWORD} // '';
Condition100%2/2
$ENV{"SWML_BASIC_AUTH_PASSWORD"} // ""
l!l
13
MC/DC100%1/1
$ENV{"SWML_BASIC_AUTH_PASSWORD"} // ""
$ENV{"SWML_BASIC_AUTH_PASSWORD"}
Truth table100%2/2
A
A= $ENV{"SWML_BASIC_AUTH_PASSWORD"}
Aresult
11
00
206 4 my $source;
207 4 ▶ if ($env_user ne '' && $env_pass ne '' && $user eq $env_user && $pass eq $env_pass) {
Branch: 2 branches
BranchTrueFalseTotal
if ($env_user ne '' and $env_pass ne '' and $user eq $env_user and $pass eq $env_pass) { } 1 3 4
elsif ($user =~ /^user_/ and length $pass > 20) { } 1 2 3
Condition66%6/9
$env_user ne "" and $env_pass ne "" and $user eq $env_user and $pass eq $env_pass
!ll&&!rl&&r
301
$env_user ne "" and $env_pass ne "" and $user eq $env_user
!ll&&!rl&&r
301
$env_user ne "" and $env_pass ne ""
!ll&&!rl&&r
301
MC/DC25%1/4
$env_user ne "" and $env_pass ne "" and $user eq $env_user and $pass eq $env_pass
$env_user ne "" $env_pass ne "" $user eq $env_user $pass eq $env_pass
Truth table40%2/5
A and B and C and D
A= $env_user ne ""B= $env_pass ne ""C= $user eq $env_userD= $pass eq $env_pass
ABCDresult
0XXX0
10XX0
110X0
11100
11111
208 1 $source = 'environment';
209 ▶ } elsif ($user =~ /^user_/ && length($pass) > 20) {
Condition66%2/3
$user =~ /^user_/ and length $pass > 20
!ll&&!rl&&r
201
MC/DC50%1/2
$user =~ /^user_/ and length $pass > 20
$user =~ /^user_/ length $pass > 20
Truth table66%2/3
A and B
A= $user =~ /^user_/B= length $pass > 20
ABresult
0X0
100
111
210 1 $source = 'generated';
211 } else {
212 2 $source = 'provided';
213 }
214 4 return ($user, $pass, $source);
215 }
216  
217 # Backward-compat alias for Perl callers that used the named-helper form.
218 # Equivalent to ``$self->get_basic_auth_credentials(1)``.
219 0 ▶sub get_basic_auth_credentials_with_source {
Subroutine get_basic_auth_credentials_with_source: not called CC=1 SCAR=6.9
Pod undocumented
220 0 my ($self) = @_;
221 0 return $self->get_basic_auth_credentials(1);
222 }
223  
224 # extract_sip_username($request_body)
225 #
226 # Python parity: SWMLService.extract_sip_username(request_body) is a
227 # @staticmethod that pulls the username out of a SignalWire/SWML
228 # request body's call.to field. Handles SIP URIs (``sip:user@host``),
229 # TEL URIs (``tel:+15551234567``), and plain destination strings.
230 # Returns undef when the body shape doesn't match.
231 #
232 # Callable as either a class method or instance method (Perl idiom for
233 # what Python expresses with @staticmethod). The class_or_self receiver
234 # is mirrored from FunctionResult and other static-method-shaped helpers.
235 14 ▶sub extract_sip_username {
Subroutine extract_sip_username: called CC=9 SCAR=22.0
Pod undocumented
236 14 my ($class_or_self, $request_body) = @_;
237 # Allow being called as a free function (single-arg form): if the
238 # first arg is itself the request_body hashref, shift it forward.
239 14 ▶ if (!defined $request_body && ref $class_or_self eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $request_body and ref $class_or_self eq "HASH") 1 13 14
Condition100%3/3
not defined $request_body and ref $class_or_self eq "HASH"
!ll&&!rl&&r
1211
MC/DC100%2/2
not defined $request_body and ref $class_or_self eq "HASH"
not defined $request_body ref $class_or_self eq "HASH"
Truth table100%3/3
not(A) and B
A= not defined $request_bodyB= ref $class_or_self eq "HASH"
ABresult
0X0
100
111
240 1 $request_body = $class_or_self;
241 }
242 14 ▶ return undef unless ref $request_body eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $request_body eq "HASH" 3 11 14
243 11 my $call = $request_body->{call};
244 11 ▶ return undef unless ref $call eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $call eq "HASH" 2 9 11
245 9 my $to = $call->{to};
246 # Python's implementation calls ``to_field.startswith(...)`` which
247 # raises AttributeError for non-string values (None / int / list)
248 # and returns None via the except path. Mirror that policy: any
249 # non-defined or ref value short-circuits to undef.
250 9 ▶ return undef unless defined $to && !ref $to;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $to and not ref $to 3 6 9
Condition100%3/3
defined $to and not ref $to
!ll&&!rl&&r
126
MC/DC100%2/2
defined $to and not ref $to
defined $to not ref $to
Truth table100%3/3
A and not(B)
A= defined $toB= not ref $to
ABresult
0X0
100
111
251  
252 6 ▶ if ($to =~ m{^sip:([^@]+)\@}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to =~ /^sip:([^\@]+)\@/i) 3 3 6
253 3 return $1;
254 }
255 3 ▶ if ($to =~ m{^tel:(.+)$}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($to =~ /^tel:(.+)$/i) 1 2 3
256 1 return $1;
257 }
258 2 return $to;
259 }
260  
261 9 ▶sub _check_basic_auth {
Subroutine _check_basic_auth: called CC=6 SCAR=18.5
262 9 my ($self, $env) = @_;
263 9 ▶ my $auth = $env->{HTTP_AUTHORIZATION} // '';
Condition100%2/2
$env->{"HTTP_AUTHORIZATION"} // ""
l!l
72
MC/DC100%1/1
$env->{"HTTP_AUTHORIZATION"} // ""
$env->{"HTTP_AUTHORIZATION"}
Truth table100%2/2
A
A= $env->{"HTTP_AUTHORIZATION"}
Aresult
11
00
264 9 ▶ return 0 unless $auth =~ /^Basic\s+(.+)$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $auth =~ /^Basic\s+(.+)$/i 2 7 9
265 7 my $decoded = MIME::Base64::decode_base64($1);
266 7 my ($user, $pass) = split(/:/, $decoded, 2);
267 7 ▶ return 0 unless defined $user && defined $pass;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and defined $pass 0 7 7
Condition33%1/3
defined $user and defined $pass
!ll&&!rl&&r
007
MC/DC0%0/2
defined $user and defined $pass
defined $user defined $pass
Truth table33%1/3
A and B
A= defined $userB= defined $pass
ABresult
0X0
100
111
268 7 ▶ return _timing_safe_compare($user, $self->basic_auth_user)
Condition66%2/3
_timing_safe_compare($user, $self->basic_auth_user) && _timing_safe_compare($pass, $self->basic_auth_password)
!ll&&!rl&&r
016
MC/DC50%1/2
_timing_safe_compare($user, $self->basic_auth_user) && _timing_safe_compare($pass, $self->basic_auth_password)
_timing_safe_compare($user, $self->basic_auth_user) _timing_safe_compare($pass, $self->basic_auth_password)
Truth table66%2/3
A && B
A= _timing_safe_compare($user, $self->basic_auth_user)B= _timing_safe_compare($pass, $self->basic_auth_password)
ABresult
0X0
100
111
269 && _timing_safe_compare($pass, $self->basic_auth_password);
270 }
271  
272 9 ▶sub _security_headers {
Subroutine _security_headers: called CC=1 SCAR=0.0
273 return (
274 9 'X-Content-Type-Options' => 'nosniff',
275 'X-Frame-Options' => 'DENY',
276 'X-XSS-Protection' => '1; mode=block',
277 'Cache-Control' => 'no-store, no-cache, must-revalidate',
278 'Pragma' => 'no-cache',
279 'Content-Type' => 'application/json',
280 );
281 }
282  
283 9 ▶sub _json_response {
Subroutine _json_response: called CC=1 SCAR=0.0
284 9 my ($status, $data) = @_;
285 9 my @headers = _security_headers();
286 9 my $body = JSON::encode_json($data);
287 9 return [$status, \@headers, [$body]];
288 }
289  
290 4 ▶sub _read_body {
Subroutine _read_body: called CC=3 SCAR=11.2
291 4 my ($env) = @_;
292 4 my $input = $env->{'psgi.input'};
293 4 ▶ return '' unless $input;
Branch: 1 branch
BranchTrueFalseTotal
unless $input 0 4 4
294 4 local $/;
295 4 my $body = <$input>;
296 4 ▶ return $body // '';
Condition50%1/2
$body // ""
l!l
40
MC/DC0%0/1
$body // ""
$body
Truth table50%1/2
A
A= $body
Aresult
11
00
297 }
298  
299 7 ▶sub to_psgi_app {
Subroutine to_psgi_app: called CC=1 SCAR=0.0
Pod undocumented
300 7 my ($self) = @_;
301  
302 12 ▶ return sub {
Subroutine __ANON__: called CC=13 SCAR=26.2
303 12 my ($env) = @_;
304 12 my $method = $env->{REQUEST_METHOD};
305 12 ▶ my $path = $env->{PATH_INFO} // '/';
Condition50%1/2
$env->{"PATH_INFO"} // "/"
l!l
120
MC/DC0%0/1
$env->{"PATH_INFO"} // "/"
$env->{"PATH_INFO"}
Truth table50%1/2
A
A= $env->{"PATH_INFO"}
Aresult
11
00
306  
307 # Health/ready endpoints (no auth)
308 12 ▶ if ($path eq '/health' || $path eq '/ready') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/health" or $path eq "/ready") 2 10 12
Condition100%3/3
$path eq "/health" or $path eq "/ready"
l!l&&r!l&&!r
1110
MC/DC100%2/2
$path eq "/health" or $path eq "/ready"
$path eq "/health" $path eq "/ready"
Truth table100%3/3
A or B
A= $path eq "/health"B= $path eq "/ready"
ABresult
1X1
011
000
309 2 return _json_response(200, { status => 'ok' });
310 }
311  
312 # Normalize route for matching
313 10 my $route = $self->route;
314 10 $route =~ s{/$}{}; # strip trailing slash
315 10 $path =~ s{/$}{}; # strip trailing slash
316 10 ▶ $route = '' if $route eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $route eq "/" 0 10 10
317 10 ▶ $path = '' if $path eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $path eq "/" 0 10 10
318  
319 # Check if this request matches our routes
320 10 my $is_swml_route = ($path eq $route);
321 10 my $is_swaig_route = ($path eq "$route/swaig");
322 10 my $is_post_prompt = ($path eq "$route/post_prompt");
323  
324 10 ▶ if ($is_swml_route || $is_swaig_route || $is_post_prompt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_swml_route or $is_swaig_route or $is_post_prompt) 9 1 10
Condition83%5/6
$is_swml_route or $is_swaig_route or $is_post_prompt
l!l&&r!l&&!r
901
$is_swml_route or $is_swaig_route
l!l&&r!l&&!r
361
MC/DC66%2/3
$is_swml_route or $is_swaig_route or $is_post_prompt
$is_swml_route $is_swaig_route $is_post_prompt
Truth table75%3/4
A or B or C
A= $is_swml_routeB= $is_swaig_routeC= $is_post_prompt
ABCresult
1XX1
01X1
0011
0000
325 # Require basic auth for protected routes
326 9 ▶ unless ($self->_check_basic_auth($env)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_check_basic_auth($env)) 3 6 9
327 return [
328 3 401,
329 ['Content-Type' => 'text/plain', 'WWW-Authenticate' => 'Basic realm="SignalWire"'],
330 ['Authentication required'],
331 ];
332 }
333  
334 6 ▶ if ($is_swml_route) {
Branch: 3 branches
BranchTrueFalseTotal
if ($is_swml_route) { } 1 5 6
elsif ($is_swaig_route) { } 5 0 5
elsif ($is_post_prompt) { } 0 0 0
335 1 return $self->_handle_swml_request($env);
336 } elsif ($is_swaig_route) {
337 5 return $self->_handle_swaig_request($env);
338 } elsif ($is_post_prompt) {
339 0 return $self->_handle_post_prompt($env);
340 }
341 }
342  
343 1 return _json_response(404, { error => 'Not found' });
344 7 };
345 }
346  
347 1 ▶sub _handle_swml_request {
Subroutine _handle_swml_request: called CC=1 SCAR=0.0
348 1 my ($self, $env) = @_;
349 1 my $doc = $self->render_main_swml($env);
350 1 return _json_response(200, $doc);
351 }
352  
353 # Extension point: render the SWML document for the main path or for
354 # GET /swaig. Default returns the currently-built Document. AgentBase
355 # overrides to emit prompt + AI verb at request time.
356 2 ▶sub render_main_swml {
Subroutine render_main_swml: called CC=1 SCAR=0.0
Pod undocumented
357 2 my ($self, $env) = @_;
358 2 return $self->document->to_hash;
359 }
360  
361 # Backwards-compatible alias kept for subclasses that override render_swml.
362 0 ▶sub render_swml {
Subroutine render_swml: not called CC=1 SCAR=6.9
Pod undocumented
363 0 my ($self, $env) = @_;
364 0 return $self->render_main_swml($env);
365 }
366  
367 # Customization hook called when SWML is requested. Default delegates to
368 # on_swml_request and returns its result. Subclasses typically override
369 # on_swml_request rather than this method.
370 #
371 # Return undef to use the default SWML rendering, or a hashref of
372 # modifications to merge into the rendered document.
373 #
374 # Python parity: WebMixin.on_request(request_data, callback_path).
375 # The Python third `request` argument is FastAPI-specific and
376 # intentionally not mirrored.
377 3 ▶sub on_request {
Subroutine on_request: called CC=1 SCAR=0.0
Pod undocumented
378 3 my ($self, $request_data, $callback_path) = @_;
379 3 return $self->on_swml_request($request_data, $callback_path);
380 }
381  
382 # Customization point for subclasses to modify SWML based on request
383 # data. The default implementation returns undef (no modification).
384 #
385 # Python parity: WebMixin.on_swml_request(request_data, callback_path, request).
386 # The third ``$request`` parameter mirrors Python's optional FastAPI
387 # Request object; in Perl this is the PSGI ``$env`` hashref (or a
388 # wrapper produced by the calling code). Subclasses that don't need
389 # direct request access can ignore it.
390 3 ▶sub on_swml_request {
Subroutine on_swml_request: called CC=1 SCAR=0.0
Pod undocumented
391 3 my ($self, $request_data, $callback_path, $request) = @_;
392 3 return undef;
393 }
394  
395 # ------------------------------------------------------------------
396 # SWAIG tool registry (lifted from AgentBase)
397 # ------------------------------------------------------------------
398  
399 # Define a SWAIG function the AI can call. Tool descriptions and
400 # parameter descriptions are LLM-facing prompt engineering — see
401 # PORTING_GUIDE for guidance.
402 178 ▶sub define_tool {
Subroutine define_tool: called CC=8 SCAR=20.8
Pod undocumented
403 178 my ($self, %opts) = @_;
404 my $name = $opts{name}
405 178 ▶ // die("define_tool requires 'name'");
Condition100%2/2
$opts{"name"} // die("define_tool requires 'name'")
l!l
1771
MC/DC100%1/1
$opts{"name"} // die("define_tool requires 'name'")
$opts{"name"}
Truth table100%2/2
A
A= $opts{"name"}
Aresult
11
00
406 177 ▶ my $description = $opts{description} // '';
Condition100%2/2
$opts{"description"} // ""
l!l
1752
MC/DC100%1/1
$opts{"description"} // ""
$opts{"description"}
Truth table100%2/2
A
A= $opts{"description"}
Aresult
11
00
407 177 ▶ my $parameters = $opts{parameters} // { type => 'object', properties => {} };
Condition100%2/2
$opts{"parameters"} // {"type", "object", "properties", {}}
l!l
15522
MC/DC100%1/1
$opts{"parameters"} // {"type", "object", "properties", {}}
$opts{"parameters"}
Truth table100%2/2
A
A= $opts{"parameters"}
Aresult
11
00
408 177 my $handler = $opts{handler};
409  
410 177 ▶ my $tool_def = {
Branch: 1 branch
BranchTrueFalseTotal
defined $handler ? : 165 12 177
411 function => $name,
412 description => $description,
413 parameters => $parameters,
414 (defined $handler ? (_handler => $handler) : ()),
415 };
416 177 for my $k (keys %opts) {
417 677 ▶ next if $k =~ /^(name|description|parameters|handler)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $k =~ /^(name|description|parameters|handler)$/ 672 5 677
418 5 $tool_def->{$k} = $opts{$k};
419 }
420 177 $self->tools->{$name} = $tool_def;
421 176 push @{ $self->tool_order }, $name
422 177 ▶ unless grep { $_ eq $name } @{ $self->tool_order };
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $name;} @{$self->tool_order;} 176 1 177
423 177 return $self;
424 }
425  
426 # Register a raw SWAIG function definition (e.g. from DataMap).
427 28 ▶sub register_swaig_function {
Subroutine register_swaig_function: called CC=3 SCAR=11.0
Pod undocumented
428 28 my ($self, $func_def) = @_;
429 28 ▶ my $name = $func_def->{function} // die("register_swaig_function needs 'function' key");
Condition100%2/2
$func_def->{"function"} // die("register_swaig_function needs 'function' key")
l!l
271
MC/DC100%1/1
$func_def->{"function"} // die("register_swaig_function needs 'function' key")
$func_def->{"function"}
Truth table100%2/2
A
A= $func_def->{"function"}
Aresult
11
00
430 27 $self->tools->{$name} = $func_def;
431 27 push @{ $self->tool_order }, $name
432 27 ▶ unless grep { $_ eq $name } @{ $self->tool_order };
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $name;} @{$self->tool_order;} 27 0 27
433 27 return $self;
434 }
435  
436 # Whether a SWAIG function with the given name is registered.
437 # (Python parity: ToolRegistry.has_function.)
438 4 ▶sub has_function {
Subroutine has_function: called CC=2 SCAR=6.9
Pod undocumented
439 4 my ($self, $name) = @_;
440 4 ▶ return exists $self->tools->{$name} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
exists $self->tools->{$name} ? : 3 1 4
441 }
442  
443 # Get a registered SWAIG function by name, or undef when absent.
444 # (Python parity: ToolRegistry.get_function.)
445 0 ▶sub get_function {
Subroutine get_function: not called CC=1 SCAR=6.9
Pod undocumented
446 0 my ($self, $name) = @_;
447 0 return $self->tools->{$name};
448 }
449  
450 # Snapshot of all registered SWAIG functions keyed by name.
451 # (Python parity: ToolRegistry.get_all_functions.)
452 0 ▶sub get_all_functions {
Subroutine get_all_functions: not called CC=1 SCAR=6.9
Pod undocumented
453 0 my ($self) = @_;
454 0 return { %{ $self->tools } };
455 }
456  
457 # Remove a registered SWAIG function. Returns 1 on success, 0 if absent.
458 # (Python parity: ToolRegistry.remove_function.)
459 0 ▶sub remove_function {
Subroutine remove_function: not called CC=2 SCAR=17.9
Pod undocumented
460 0 my ($self, $name) = @_;
461 0 ▶ return 0 unless exists $self->tools->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->tools->{$name} 0 0 0
462 0 delete $self->tools->{$name};
463 0 @{ $self->tool_order } = grep { $_ ne $name } @{ $self->tool_order };
464 0 return 1;
465 }
466  
467 # Register multiple tool definitions at once.
468 2 ▶sub define_tools {
Subroutine define_tools: called CC=4 SCAR=13.9
Pod undocumented
469 2 my ($self, @tool_defs) = @_;
470 2 for my $t (@tool_defs) {
471 4 ▶ if (ref $t eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $t eq "HASH") 4 0 4
472 4 ▶ if (exists $t->{function}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $t->{'function'}) { } 2 2 4
473 2 $self->register_swaig_function($t);
474 } else {
475 2 $self->define_tool(%$t);
476 }
477 }
478 }
479 2 return $self;
480 }
481  
482 # Dispatch a function call to the registered handler. Default plain
483 # implementation. AgentBase may override to add token validation.
484 30 ▶sub on_function_call {
Subroutine on_function_call: called CC=3 SCAR=11.0
Pod undocumented
485 30 my ($self, $name, $args, $raw_data) = @_;
486 30 my $tool = $self->tools->{$name};
487 30 ▶ return undef unless $tool && $tool->{_handler};
Branch: 1 branch
BranchTrueFalseTotal
unless $tool and $tool->{"_handler"} 5 25 30
Condition100%3/3
$tool and $tool->{"_handler"}
!ll&&!rl&&r
4125
MC/DC100%2/2
$tool and $tool->{"_handler"}
$tool $tool->{"_handler"}
Truth table100%3/3
A and B
A= $toolB= $tool->{"_handler"}
ABresult
0X0
100
111
488 25 return $tool->{_handler}->($args, $raw_data);
489 }
490  
491 # List registered SWAIG tool names in registration order.
492 3 ▶sub list_tool_names {
Subroutine list_tool_names: called CC=1 SCAR=0.0
Pod undocumented
493 3 my ($self) = @_;
494 3 return @{ $self->tool_order };
495 }
496  
497 # Extension point: invoked between argument parsing and function dispatch
498 # on POST /swaig. Returns ($target, $short_circuit). If $short_circuit is
499 # defined, it's encoded as the SWAIG response without calling
500 # on_function_call. AgentBase may override to add session-token validation.
501 2 ▶sub swaig_pre_dispatch {
Subroutine swaig_pre_dispatch: called CC=1 SCAR=0.0
Pod undocumented
502 2 my ($self, $request_data, $func_name, $env) = @_;
503 2 return ($self, undef);
504 }
505  
506 # Extension point: subclasses may override to add /post_prompt, /mcp etc.
507 # Receives the relative sub-path (after the route prefix) and parsed body.
508 # Returns a PSGI response triple, or undef if not handled.
509 0 ▶sub handle_additional_route {
Subroutine handle_additional_route: not called CC=1 SCAR=6.9
Pod undocumented
510 0 my ($self, $sub_path, $request_data, $env) = @_;
511 0 return undef;
512 }
513  
514 # Register a routing callback at a given sub-path under the service route.
515 1 ▶sub register_routing_callback {
Subroutine register_routing_callback: called CC=1 SCAR=0.0
Pod undocumented
516 1 my ($self, $path, $cb) = @_;
517 1 $self->routing_callbacks->{$path} = $cb;
518 1 return $self;
519 }
520  
521 5 ▶sub _handle_swaig_request {
Subroutine _handle_swaig_request: called CC=20 SCAR=36.0
522 5 my ($self, $env) = @_;
523 5 ▶ my $method = $env->{REQUEST_METHOD} // 'GET';
Condition50%1/2
$env->{"REQUEST_METHOD"} // "GET"
l!l
50
MC/DC0%0/1
$env->{"REQUEST_METHOD"} // "GET"
$env->{"REQUEST_METHOD"}
Truth table50%1/2
A
A= $env->{"REQUEST_METHOD"}
Aresult
11
00
524  
525 5 ▶ if ($method eq 'GET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET") 1 4 5
526 1 my $doc = $self->render_main_swml($env);
527 1 return _json_response(200, $doc);
528 }
529  
530 4 my $body = _read_body($env);
531 4 my $payload;
532 4 ▶ eval { $payload = JSON::decode_json($body) if length($body) };
Branch: 1 branch
BranchTrueFalseTotal
if length $body 4 0 4
533 4 ▶ if ($@ || !$payload || ref $payload ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $payload or ref $payload ne "HASH") 0 4 4
Condition33%2/6
$@ or not $payload or ref $payload ne "HASH"
l!l&&r!l&&!r
004
$@ or not $payload
l!l&&r!l&&!r
004
MC/DC0%0/3
$@ or not $payload or ref $payload ne "HASH"
$@ not $payload ref $payload ne "HASH"
Truth table25%1/4
A or not(B) or C
A= $@B= not $payloadC= ref $payload ne "HASH"
ABCresult
1XX1
01X1
0011
0000
534 0 return _json_response(400, { error => 'Invalid JSON' });
535 }
536  
537 4 my $func_name = $payload->{function};
538 4 ▶ if (!defined $func_name || $func_name eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $func_name or $func_name eq "") 1 3 4
Condition66%2/3
not defined $func_name or $func_name eq ""
l!l&&r!l&&!r
103
MC/DC50%1/2
not defined $func_name or $func_name eq ""
not defined $func_name $func_name eq ""
Truth table66%2/3
not(A) or B
A= not defined $func_nameB= $func_name eq ""
ABresult
1X1
011
000
539 1 return _json_response(400, { error => 'Missing function name' });
540 }
541 3 ▶ if ($func_name !~ $SWAIG_FN_NAME) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($func_name =~ /$SWAIG_FN_NAME/) 1 2 3
542 1 return _json_response(400, { error => "Invalid function name format: '$func_name'" });
543 }
544  
545 # Argument extraction: nested {argument:{parsed:[...]}} OR flat {arguments}
546 2 my $args = {};
547 2 ▶ if (ref $payload->{argument} eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $payload->{'argument'} eq 'HASH') { } 2 0 2
elsif (ref $payload->{'arguments'} eq 'HASH') { } 0 0 0
548 2 my $parsed = $payload->{argument}{parsed};
549 2 ▶ $args = $parsed->[0] if ref $parsed eq 'ARRAY' && @$parsed;
Branch: 1 branch
BranchTrueFalseTotal
if ref $parsed eq "ARRAY" and @$parsed 2 0 2
Condition33%1/3
ref $parsed eq "ARRAY" and @$parsed
!ll&&!rl&&r
002
MC/DC0%0/2
ref $parsed eq "ARRAY" and @$parsed
ref $parsed eq "ARRAY" @$parsed
Truth table33%1/3
A and B
A= ref $parsed eq "ARRAY"B= @$parsed
ABresult
0X0
100
111
550 } elsif (ref $payload->{arguments} eq 'HASH') {
551 0 $args = $payload->{arguments};
552 }
553 2 ▶ $args //= {};
Condition50%1/2
$args //= {}
l!l
20
MC/DC0%0/1
$args //= {}
$args
Truth table50%1/2
A
A= $args
Aresult
11
00
554  
555 2 my ($target, $short_circuit) = $self->swaig_pre_dispatch($payload, $func_name, $env);
556 2 ▶ return _json_response(200, $short_circuit) if defined $short_circuit;
Branch: 1 branch
BranchTrueFalseTotal
if defined $short_circuit 0 2 2
557  
558 2 my $result = $target->on_function_call($func_name, $args, $payload);
559 2 ▶ return _json_response(404, { error => "Unknown function: $func_name" })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result 1 1 2
560 unless defined $result;
561  
562 # FunctionResult-like objects respond to to_hash; handlers may also
563 # return plain hashrefs.
564 1 my $result_hash;
565 1 ▶ if (ref $result eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $result eq 'HASH') { } 1 0 1
elsif (builtin::blessed($result) and $result->can('to_hash')) { } 0 0 0
566 1 $result_hash = $result;
567 ▶ } elsif (Scalar::Util::blessed($result) && $result->can('to_hash')) {
Condition0%0/3
builtin::blessed($result) and $result->can("to_hash")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($result) and $result->can("to_hash")
builtin::blessed($result) $result->can("to_hash")
Truth table0%0/3
A and B
A= builtin::blessed($result)B= $result->can("to_hash")
ABresult
0X0
100
111
568 0 $result_hash = $result->to_hash;
569 } else {
570 0 $result_hash = { response => "$result" };
571 }
572 1 return _json_response(200, $result_hash);
573 }
574  
575 0 ▶sub _handle_post_prompt {
Subroutine _handle_post_prompt: not called CC=1 SCAR=6.9
576 0 my ($self, $env) = @_;
577 0 return _json_response(200, { response => 'Post prompt endpoint' });
578 }
579  
580 44 1;
« blib/lib/SignalWire/Relay/Action.pm ↑ Summary blib/lib/SignalWire/Security/SessionManager.pm »