blib/lib/SignalWire/Security/WebhookMiddleware.pm untested

filter: Statementstmt 0.0% 0 / 102 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 71 MC/DCmcdc 0.0% 0 / 41 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 272 CC 24 SCAR 40.7
CC
24
Cov
0%
wrap
90.0
_slurp_body
72.0
_reconstruct_url
56.0
CRAP 58.8
1 package SignalWire::Security::WebhookMiddleware;
2  
3 # Plack middleware that gates inbound webhook requests on a valid
4 # X-SignalWire-Signature (or legacy X-Twilio-Signature) header.
5 #
6 # Copyright (c) 2025 SignalWire. Licensed under the MIT License.
7 #
8 # Behavior:
9 # 1. If $signing_key is empty / undef, the middleware is a passthrough.
10 # (AgentBase warns at startup when this happens.)
11 # 2. Reads the entire body from psgi.input, caches it on the env under
12 # ``signalwire.raw_body``, and rewinds psgi.input so downstream
13 # handlers can re-read.
14 # 3. Reconstructs the public URL using:
15 # - X-Forwarded-Proto / X-Forwarded-Host (when trust_proxy is on)
16 # - SWML_PROXY_URL_BASE env var (if set)
17 # - falls back to ``psgi.url_scheme://HTTP_HOST + REQUEST_URI``
18 # 4. Calls validate_webhook_signature; on failure returns
19 # ``[403, [], []]`` and never invokes the wrapped app.
20 #
21 # Usage (PSGI):
22 #
23 # use Plack::Builder;
24 # use SignalWire::Security::WebhookMiddleware;
25 #
26 # builder {
27 # enable sub {
28 # SignalWire::Security::WebhookMiddleware->wrap(
29 # app => $_[0],
30 # signing_key => $ENV{SIGNALWIRE_SIGNING_KEY},
31 # trust_proxy => 1,
32 # );
33 # };
34 # $app;
35 # };
36 #
37 # Or directly:
38 #
39 # my $wrapped = SignalWire::Security::WebhookMiddleware->wrap(
40 # app => $app,
41 # signing_key => $key,
42 # paths => [ '/swaig', '/post_prompt', '/' ], # optional whitelist
43 # methods => [ 'POST' ], # default POST only
44 # );
45  
46 use strict;
47 use warnings;
48  
49 use Carp qw(croak);
50 use SignalWire::Security::WebhookValidator qw(validate_webhook_signature);
51  
52 # ``wrap`` returns a PSGI app that performs validation and forwards
53 # successful requests to the wrapped ``app``. Options:
54 #
55 # app => $psgi_app (required)
56 # signing_key => $string (optional; if empty -> passthrough)
57 # paths => arrayref of paths (optional; if set, only those paths
58 # are gated -- others passthrough)
59 # methods => arrayref of methods (default ['POST'])
60 # trust_proxy => 0|1 (default 1)
61 # public_url_base => string (overrides everything; usually for
62 # tests)
63 sub wrap {
64 my ($class, %opts) = @_;
65 my $app = $opts{app} or croak "wrap: 'app' is required";
66 croak "wrap: 'app' must be a CODE ref" unless ref($app) eq 'CODE';
67  
68 my $signing_key = $opts{signing_key};
69 my $paths = $opts{paths}; # arrayref or undef
70 my $methods = $opts{methods} || ['POST'];
71 my $trust_proxy = exists $opts{trust_proxy} ? $opts{trust_proxy} : 1;
72 my $public_url_base = $opts{public_url_base};
73  
74 my %method_set = map { uc($_) => 1 } @$methods;
75 my %path_set;
76 %path_set = map { $_ => 1 } @$paths if $paths;
77  
78 # If no signing key, this middleware is a no-op. (AgentBase emits the
79 # warning at startup; we don't double-log here.)
80 if (!defined $signing_key || $signing_key eq '') {
81 return $app;
82 }
83  
84 return sub {
85 my $env = shift;
86  
87 # Method gating: only validate POST (or whichever methods caller asked).
88 my $method = uc($env->{REQUEST_METHOD} || 'GET');
89 if (!$method_set{$method}) {
90 return $app->($env);
91 }
92  
93 # Path gating: if a whitelist was configured, only those paths
94 # require a signature; everything else passes through.
95 my $path = $env->{PATH_INFO} || '/';
96 if (%path_set && !$path_set{$path}) {
97 return $app->($env);
98 }
99  
100 # Slurp the body and stash it on the env so downstream handlers
101 # don't have to read it again.
102 my $raw_body = _slurp_body($env);
103 $env->{'signalwire.raw_body'} = $raw_body;
104  
105 # Header lookup: prefer X-SignalWire-Signature, fall back to
106 # X-Twilio-Signature for cXML compat.
107 my $sig = $env->{HTTP_X_SIGNALWIRE_SIGNATURE}
108 // $env->{HTTP_X_TWILIO_SIGNATURE}
109 // '';
110  
111 if ($sig eq '') {
112 return [403, ['Content-Type' => 'text/plain'], ['Forbidden']];
113 }
114  
115 my $url = _reconstruct_url($env, $trust_proxy, $public_url_base);
116  
117 my $ok = eval {
118 validate_webhook_signature($signing_key, $sig, $url, $raw_body);
119 };
120 if ($@ || !$ok) {
121 return [403, ['Content-Type' => 'text/plain'], ['Forbidden']];
122 }
123  
124 return $app->($env);
125 };
126 }
127  
128 # Read all of psgi.input, then rewind so downstream handlers can re-read.
129 # Returns '' when there's no input or it's already empty.
130 sub _slurp_body {
131 my ($env) = @_;
132 my $input = $env->{'psgi.input'};
133 return '' unless $input;
134  
135 my $body = '';
136 my $buf;
137 # Limit to CONTENT_LENGTH if present so we don't hang on a streaming
138 # source, but still allow chunked / unknown-length when not.
139 my $cl = $env->{CONTENT_LENGTH};
140 if (defined $cl && $cl =~ /\A\d+\z/) {
141 my $remaining = $cl;
142 while ($remaining > 0) {
143 my $chunk = $remaining > 8192 ? 8192 : $remaining;
144 my $n = $input->read($buf, $chunk);
145 last unless defined $n && $n > 0;
146 $body .= $buf;
147 $remaining -= $n;
148 }
149 }
150 else {
151 while (my $n = $input->read($buf, 8192)) {
152 $body .= $buf;
153 }
154 }
155  
156 # Rewind so downstream code can re-read. If seek isn't supported,
157 # swap in a string-handle pointing at the buffered body.
158 if ($input->can('seek')) {
159 eval { $input->seek(0, 0) };
160 }
161 if ($@ || !$input->can('seek')) {
162 open my $fh, '<', \$body;
163 $env->{'psgi.input'} = $fh;
164 $env->{CONTENT_LENGTH} = length($body);
165 }
166 elsif (!defined $cl) {
167 $env->{CONTENT_LENGTH} = length($body);
168 }
169  
170 return $body;
171 }
172  
173 # Reconstruct the full public URL SignalWire actually POSTed to.
174 sub _reconstruct_url {
175 my ($env, $trust_proxy, $public_url_base) = @_;
176  
177 # 1) Explicit override (caller / config / tests).
178 if (defined $public_url_base && $public_url_base ne '') {
179 return _join_base_path($public_url_base, $env);
180 }
181  
182 # 2) SWML_PROXY_URL_BASE env var (per spec).
183 if (defined $ENV{SWML_PROXY_URL_BASE} && $ENV{SWML_PROXY_URL_BASE} ne '') {
184 return _join_base_path($ENV{SWML_PROXY_URL_BASE}, $env);
185 }
186  
187 # 3) X-Forwarded-* headers when trust_proxy is on.
188 my ($scheme, $host);
189 if ($trust_proxy) {
190 my $xfp = $env->{HTTP_X_FORWARDED_PROTO};
191 my $xfh = $env->{HTTP_X_FORWARDED_HOST};
192 if ($xfp && $xfh) {
193 ($scheme, $host) = ($xfp, $xfh);
194 }
195 }
196  
197 # 4) Fallback to raw request fields.
198 $scheme //= $env->{'psgi.url_scheme'} // 'http';
199 $host //= $env->{HTTP_HOST}
200 // (($env->{SERVER_NAME} // 'localhost') . ':'
201 . ($env->{SERVER_PORT} // '80'));
202  
203 my $req_uri = defined $env->{REQUEST_URI} && $env->{REQUEST_URI} ne ''
204 ? $env->{REQUEST_URI}
205 : (($env->{PATH_INFO} // '/')
206 . (defined $env->{QUERY_STRING} && $env->{QUERY_STRING} ne ''
207 ? '?' . $env->{QUERY_STRING}
208 : ''));
209  
210 return "$scheme://$host$req_uri";
211 }
212  
213 # Join an external base ("https://foo.ngrok.io") with the path+query
214 # from the request env.
215 sub _join_base_path {
216 my ($base, $env) = @_;
217 $base =~ s{/+\z}{};
218 my $req_uri = defined $env->{REQUEST_URI} && $env->{REQUEST_URI} ne ''
219 ? $env->{REQUEST_URI}
220 : (($env->{PATH_INFO} // '/')
221 . (defined $env->{QUERY_STRING} && $env->{QUERY_STRING} ne ''
222 ? '?' . $env->{QUERY_STRING}
223 : ''));
224 return $base . $req_uri;
225 }
226  
227 1;
228  
229 __END__