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

filter: Statementstmt 0.0% 0 / 167 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 56 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 398 CC 56 SCAR 41.1
CC
56
Cov
0%
_sorted_concat_params
132.0
validate_webhook_signature
90.0
validate_request
72.0
CRAP 61.0
1 package SignalWire::Security::WebhookValidator;
2  
3 # Webhook signature validation for SignalWire-signed HTTP requests.
4 #
5 # Copyright (c) 2025 SignalWire. Licensed under the MIT License.
6 # See LICENSE file in the project root for full license information.
7 #
8 # Implements both schemes from porting-sdk/webhooks.md:
9 #
10 # - Scheme A (RELAY/SWML/JSON): hex(HMAC-SHA1(key, url + raw_body))
11 # - Scheme B (Compat/cXML form): base64(HMAC-SHA1(key, url + sortedFormParams))
12 # with URL port-normalization fallback and an optional bodySHA256
13 # query-param fallback for JSON-on-compat-surface.
14 #
15 # Public API:
16 # validate_webhook_signature($signing_key, $signature, $url, $raw_body) -> 0|1
17 # validate_request($signing_key, $signature, $url, $params_or_raw_body) -> 0|1
18 #
19 # All comparisons use a constant-time compare so the secret is not leaked
20 # across repeated requests. The compare routine is intentionally
21 # hand-rolled (no dep on Crypt::Util) so the validator works on a stock
22 # Perl install.
23  
24 use strict;
25 use warnings;
26  
27 use Carp qw(croak);
28 use Digest::SHA qw(hmac_sha1 hmac_sha1_hex sha256_hex);
29 use MIME::Base64 qw(encode_base64);
30 use Scalar::Util qw(blessed reftype);
31 use URI ();
32  
33 use Exporter qw(import);
34 our @EXPORT_OK = qw(validate_webhook_signature validate_request);
35  
36 # ---------------------------------------------------------------------------
37 # Internal helpers
38 # ---------------------------------------------------------------------------
39  
40 sub _hex_hmac_sha1 {
41 my ($key, $message) = @_;
42 return hmac_sha1_hex($message, $key);
43 }
44  
45 sub _b64_hmac_sha1 {
46 my ($key, $message) = @_;
47 return encode_base64(hmac_sha1($message, $key), '');
48 }
49  
50 # Constant-time string comparison. Both args are stringified. Returns
51 # 1 when bytes are identical, 0 otherwise. Hand-rolled to avoid the
52 # Crypt::Util dependency. The XOR-or loop runs over the full string
53 # length so timing does not leak the position of the first mismatch.
54 # Length mismatch returns 0 immediately, which matches what
55 # ``hmac.compare_digest`` does in Python (it also requires equal length).
56 sub _safe_eq {
57 my ($a, $b) = @_;
58 return 0 unless defined $a && defined $b;
59 $a = "$a";
60 $b = "$b";
61 return 0 if length($a) != length($b);
62 my $diff = 0;
63 for my $i (0 .. length($a) - 1) {
64 $diff |= ord(substr($a, $i, 1)) ^ ord(substr($b, $i, 1));
65 }
66 return $diff == 0 ? 1 : 0;
67 }
68  
69 # Parse an x-www-form-urlencoded body into an arrayref of [key, value]
70 # pairs. Returns [] for an empty body or anything that does not look
71 # parseable. Preserves submission order for repeated keys.
72 sub _parse_form_body {
73 my ($raw_body) = @_;
74 return [] unless defined $raw_body && length $raw_body;
75 # Reject anything with control bytes or things that obviously aren't
76 # form data (e.g. JSON starting with { or [) — Scheme B falls back
77 # to empty params in that case.
78 return [] if $raw_body =~ /\A\s*[\{\[]/;
79  
80 my @pairs;
81 for my $chunk (split /&/, $raw_body) {
82 next if $chunk eq '';
83 my ($k, $v) = split(/=/, $chunk, 2);
84 $v = '' unless defined $v;
85 # Percent-decode plus '+' -> ' ' per application/x-www-form-urlencoded.
86 for my $s ($k, $v) {
87 $s =~ tr/+/ /;
88 $s =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
89 }
90 # Disqualify the body as form data if any decoded byte is binary
91 # garbage; the canonical Scheme A bodies are JSON and shouldn't
92 # produce a meaningful pair list anyway.
93 push @pairs, [$k, $v];
94 }
95 return \@pairs;
96 }
97  
98 # Concatenate form params per Scheme B rules.
99 #
100 # - Sort by key, ASCII ascending (stable sort preserves submission
101 # order for repeated keys).
102 # - For repeated keys: emit ``key+value`` once per occurrence.
103 # - Hash inputs: arrayref values expand to one (key, value) per element.
104 # - Undef values stringify to ''.
105 sub _sorted_concat_params {
106 my ($params) = @_;
107 return '' unless defined $params;
108  
109 my @items;
110 my $ref = ref($params);
111 if ($ref eq 'HASH') {
112 for my $k (keys %$params) {
113 my $v = $params->{$k};
114 if (ref($v) eq 'ARRAY') {
115 push @items, [$k, defined($_) ? "$_" : ''] for @$v;
116 }
117 else {
118 push @items, [$k, defined($v) ? "$v" : ''];
119 }
120 }
121 }
122 elsif ($ref eq 'ARRAY') {
123 for my $pair (@$params) {
124 if (ref($pair) eq 'ARRAY' && @$pair >= 2) {
125 push @items, [$pair->[0], defined($pair->[1]) ? "$pair->[1]" : ''];
126 }
127 elsif (ref($pair) eq 'ARRAY' && @$pair == 1) {
128 push @items, [$pair->[0], ''];
129 }
130 }
131 }
132 else {
133 return '';
134 }
135  
136 return '' unless @items;
137  
138 # Stable sort by key only — preserves original order within
139 # repeated keys (Perl's sort is stable since 5.8 with the default
140 # mergesort). Compare with cmp.
141 @items = sort { $a->[0] cmp $b->[0] } @items;
142  
143 my $out = '';
144 for my $kv (@items) {
145 $out .= $kv->[0] . $kv->[1];
146 }
147 return $out;
148 }
149  
150 # Split URL into a hashref with the fields we need. Uses URI for parsing.
151 sub _split_url {
152 my ($url) = @_;
153 my $u = URI->new($url);
154 my $scheme = $u->scheme // '';
155 my $host = '';
156 my $port = '';
157 if ($u->can('host')) {
158 $host = $u->host // '';
159 }
160 # URI::http / URI::https sets default_port — distinguish "no explicit
161 # port" from "explicit standard port" by checking the raw authority.
162 my $authority = $u->can('authority') ? ($u->authority // '') : '';
163 if ($authority =~ /:(\d+)\z/) {
164 $port = $1;
165 }
166 my $path = $u->can('path') ? ($u->path // '') : '';
167 my $query = $u->can('query') ? ($u->query // '') : '';
168 my $fragment = $u->can('fragment') ? ($u->fragment // '') : '';
169 return {
170 scheme => $scheme,
171 host => $host,
172 port => $port,
173 path => $path,
174 query => $query,
175 fragment => $fragment,
176 };
177 }
178  
179 # Reassemble a URL with the given (possibly empty) port. IPv6 hosts
180 # get bracketed.
181 sub _build_url {
182 my (%p) = @_;
183 my $host = $p{host} // '';
184 if ($host =~ /:/ && $host !~ /^\[/) {
185 $host = "[$host]";
186 }
187 my $netloc = $host;
188 $netloc .= ':' . $p{port} if defined $p{port} && $p{port} ne '';
189  
190 my $url = '';
191 $url .= $p{scheme} . '://' if $p{scheme} ne '';
192 $url .= $netloc;
193 $url .= $p{path} if defined $p{path};
194 $url .= '?' . $p{query} if defined $p{query} && $p{query} ne '';
195 $url .= '#' . $p{fragment} if defined $p{fragment} && $p{fragment} ne '';
196 return $url;
197 }
198  
199 # Return URL variants to try for Scheme B port normalization.
200 #
201 # - https + no port -> [as-is, with :443]
202 # - https + :443 -> [as-is, without port]
203 # - http + no port -> [as-is, with :80]
204 # - http + :80 -> [as-is, without port]
205 # - any non-standard explicit port -> [as-is]
206 sub _candidate_urls {
207 my ($url) = @_;
208 my $parts = _split_url($url);
209 return [$url] unless $parts->{host};
210  
211 my %standard = (http => '80', https => '443');
212 my $std = $standard{ lc($parts->{scheme}) };
213 my @cands = ($url);
214  
215 if (defined $std) {
216 if ($parts->{port} eq '') {
217 my $with = _build_url(%$parts, port => $std);
218 push @cands, $with if $with ne $url;
219 }
220 elsif ($parts->{port} eq $std) {
221 my $without = _build_url(%$parts, port => '');
222 push @cands, $without if $without ne $url;
223 }
224 }
225 return \@cands;
226 }
227  
228 # If URL has ``?bodySHA256=<hex>``, verify sha256_hex(raw_body) matches.
229 # Returns 1 when the param is absent or matches; 0 only when present
230 # and mismatches.
231 sub _check_body_sha256 {
232 my ($url, $raw_body) = @_;
233 my $parts = _split_url($url);
234 return 1 if $parts->{query} eq '';
235 my $expected;
236 for my $pair (split /&/, $parts->{query}) {
237 my ($k, $v) = split(/=/, $pair, 2);
238 next unless defined $k && $k eq 'bodySHA256';
239 $expected = defined $v ? $v : '';
240 last;
241 }
242 return 1 unless defined $expected;
243 my $actual = sha256_hex(defined $raw_body ? $raw_body : '');
244 return _safe_eq($actual, $expected);
245 }
246  
247 # ---------------------------------------------------------------------------
248 # Public API
249 # ---------------------------------------------------------------------------
250  
251 # validate_webhook_signature($signing_key, $signature, $url, $raw_body)
252 #
253 # Returns 1 if the signature matches either Scheme A (hex JSON) or
254 # Scheme B (base64 form, with port-normalization variants and optional
255 # bodySHA256 fallback). Returns 0 otherwise.
256 #
257 # Croaks when ``$signing_key`` is missing (programming error).
258 # Croaks when ``$raw_body`` is a reference (e.g. parsed dict by mistake).
259 # Returns 0 when ``$signature`` is missing/empty (never throws).
260 sub validate_webhook_signature {
261 my ($signing_key, $signature, $url, $raw_body) = @_;
262 croak "signing_key is required"
263 unless defined $signing_key && length $signing_key;
264 croak "raw_body must be a string -- did you pass a parsed reference by mistake?"
265 if ref($raw_body);
266 return 0 unless defined $signature && length $signature;
267  
268 $url = '' unless defined $url;
269 $raw_body = '' unless defined $raw_body;
270  
271 # ------------------------------------------------------------------
272 # Scheme A — RELAY/SWML/JSON: hex(HMAC-SHA1(key, url + raw_body))
273 # ------------------------------------------------------------------
274 my $expected_a = _hex_hmac_sha1($signing_key, $url . $raw_body);
275 return 1 if _safe_eq($expected_a, $signature);
276  
277 # ------------------------------------------------------------------
278 # Scheme B — Compat/cXML form: base64(HMAC-SHA1(key, url + sorted_concat_params))
279 # Try with parsed form params; fall back to empty params for JSON-on-compat.
280 # Try both with-port and without-port URL variants.
281 # ------------------------------------------------------------------
282 my $parsed = _parse_form_body($raw_body);
283 my @shapes = ($parsed, []);
284  
285 for my $candidate_url (@{ _candidate_urls($url) }) {
286 for my $shape (@shapes) {
287 my $concat = _sorted_concat_params($shape);
288 my $expected = _b64_hmac_sha1($signing_key, $candidate_url . $concat);
289 if (_safe_eq($expected, $signature)) {
290 # If URL carries bodySHA256, body hash must also match.
291 return 1 if _check_body_sha256($candidate_url, $raw_body);
292 # bodySHA256 mismatched; keep trying.
293 }
294 }
295 }
296  
297 return 0;
298 }
299  
300 # validate_request($signing_key, $signature, $url, $params_or_raw_body)
301 #
302 # Legacy ``compatibility-api`` drop-in entry point.
303 #
304 # - If $params_or_raw_body is a plain (non-ref) string: delegates to
305 # validate_webhook_signature (Scheme A then Scheme B with parsed form).
306 # - If it's a hashref or arrayref: treats it as pre-parsed form params
307 # and runs Scheme B directly (with URL port normalization).
308 # - Anything else (other ref types): croaks with a clear message.
309 sub validate_request {
310 my ($signing_key, $signature, $url, $params_or_raw_body) = @_;
311 croak "signing_key is required"
312 unless defined $signing_key && length $signing_key;
313 return 0 unless defined $signature && length $signature;
314  
315 $url = '' unless defined $url;
316  
317 if (!defined $params_or_raw_body) {
318 $params_or_raw_body = [];
319 }
320  
321 my $ref = ref($params_or_raw_body);
322  
323 if (!$ref) {
324 # Plain scalar string -> delegate to combined validator.
325 return validate_webhook_signature($signing_key, $signature, $url,
326 $params_or_raw_body);
327 }
328  
329 if ($ref ne 'HASH' && $ref ne 'ARRAY') {
330 croak "params_or_raw_body must be a string (raw body) or a "
331 . "hashref/arrayref of form params";
332 }
333  
334 # Pre-parsed form params -> Scheme B only, all candidate URLs.
335 my $concat = _sorted_concat_params($params_or_raw_body);
336 for my $candidate_url (@{ _candidate_urls($url) }) {
337 my $expected = _b64_hmac_sha1($signing_key, $candidate_url . $concat);
338 return 1 if _safe_eq($expected, $signature);
339 }
340 return 0;
341 }
342  
343 1;
344  
345 __END__