script/mock_onfido.pl untested

filter: Statementstmt 0.0% 0 / 327 Branchbran 0.0% 0 / 86 Conditioncond 0.0% 0 / 17 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 470 CC 29 SCAR 59.2
CC
29
Cov
0%
multipart_data
702.0
clone_and_remove_private
12.0
create_report
6.0
CRAP 374.2
1 ## no critic (RequireExplicitPackage RequireEndWithOne)
2  
3 use strict;
4 use warnings;
5  
6 use Clone 'clone';
7 use Date::Utility;
8 use Data::UUID;
9 use File::Basename;
10 use Path::Tiny;
11 use JSON::MaybeUTF8 qw(:v1);
12 use MIME::Base64;
13  
14 # New HTTP server implementation
15 use Net::Async::HTTP::Server;
16 use IO::Async::Loop;
17 use HTTP::Response;
18  
19 # This is the server in-memory storage
20 my %applicants;
21 my %deleted_applicants;
22 my %documents;
23 my %photos;
24 my %files;
25 my %reports;
26 my %checks;
27 my @sdk_tokens;
28  
29 # this is damn small pdf
30 use constant DAMN_SMALL_PDF => 'JVBERi0xLg10cmFpbGVyPDwvUm9vdDw8L1BhZ2VzPDwvS2lkc1s8PC9NZWRpYUJveFswIDAgMyAzXT4+XT4+Pj4+Pg==';
31  
32 # storage utilities
33  
34 sub create_report {
35 my ($params, $check_id, $applicant_id) = @_;
36 my @reports;
37 my @document_ids =
38 map { $_->{id} }
39 grep { $_->{_applicant_id} eq $applicant_id } values %documents;
40 for my $req ($params->{report_names}->@*) {
41 my $report_id = Data::UUID->new->create_str();
42 my $report = {
43 id => $report_id,
44 _check_id => $check_id,
45 created_at => Date::Utility->new()->datetime_iso8601,
46 name => $req,
47 status => 'complete',
48 result => 'clear',
49 breakdown => {},
50 properties => {document_type => 'passport'},
51 $req eq 'document'
52 ? (documents => [map { {id => $_} } @document_ids])
53 : (),
54 };
55 $reports{$report_id} = $report;
56 push @reports, $report_id;
57 }
58 return [map { clone_and_remove_private($_) } @reports];
59 }
60  
61 sub clone_and_remove_private {
62 my $result = shift;
63  
64 return $result unless $result && ref($result) eq 'HASH';
65 $result = clone($result);
66 for my $k (keys %$result) {
67 if ($k =~ /^_/) {
68 delete $result->{$k};
69 }
70 }
71  
72 return $result;
73 }
74  
75 # Router for the HTTP server
76 # nested hashref: http method -> path -> controller
77  
78 my $router = {
79 post => {
80 '/v3.4/applicants' => sub {
81 my $req = shift;
82 my $data = decode_json_utf8($req->body);
83 my $id = Data::UUID->new->create_str();
84 my $applicant = {
85 id => $id,
86 created_at => Date::Utility->new()->datetime_iso8601,
87 href => "v3.4/applicants/$id",
88 };
89 for my $k (keys %$data) {
90 $applicant->{$k} = $data->{$k};
91 }
92 $applicants{$id} = $applicant;
93  
94 return json_response($req, $applicant);
95 },
96 '/v3.4/documents' => sub {
97 my $req = shift;
98 my $data = multipart_data($req);
99 my $applicant_id = $data->{applicant_id}->{value};
100 my $document_id = Data::UUID->new->create_str();
101 my $file = $data->{file};
102 my $document = {
103 id => $document_id,
104 created_at => Date::Utility->new()->datetime_iso8601,
105 href => "/v3.4/documents/$document_id",
106 download_href => "/v3.4/documents/$document_id/download",
107 _applicant_id => $applicant_id,
108 file_name => basename($data->{file}->{filename}),
109 file_size => length $data->{file}->{value},
110 file_type => $data->{file}->{headers}->{'Content-Type'},
111 };
112 for my $param (qw(type side issuing_country)) {
113 $document->{$param} = $data->{$param}->{value};
114 }
115  
116 $files{$document_id} = Path::Tiny->tempfile;
117 $files{$document_id}->spew_raw($data->{file}->{value});
118 $documents{$document_id} = $document;
119 return json_response($req, clone_and_remove_private($document));
120 },
121 '/v3.4/live_photos' => sub {
122 my $req = shift;
123 my $data = multipart_data($req);
124 my $applicant_id = $data->{applicant_id}->{value};
125  
126 # don't know how to used yet
127 #my $advanced_validation = $c->param('advanced_validation');
128 my $photo_id = Data::UUID->new->create_str();
129 my $photo = {
130 id => $photo_id,
131 created_at => Date::Utility->new()->datetime_iso8601,
132 href => "/v3.4/live_photos/$photo_id",
133 download_href => "/v3.4/live_photos/$photo_id/download",
134 };
135 my $file = $data->{file};
136 $photo->{file_name} = basename($data->{file}->{filename});
137 $photo->{file_size} = length $data->{file}->{value};
138 $photo->{file_type} = $data->{file}->{headers}->{'Content-Type'};
139 $files{$photo_id} = Path::Tiny->tempfile;
140 $files{$photo_id}->spew_raw($data->{file}->{value});
141 $photo->{_applicant_id} = $applicant_id;
142 $photos{$photo_id} = $photo;
143  
144 return json_response($req, clone_and_remove_private($photo));
145 },
146 '/v3.4/checks' => sub {
147 my $req = shift;
148 my $data = decode_json_utf8($req->body);
149 my $applicant_id = $data->{applicant_id};
150 my $check_id = Data::UUID->new->create_str();
151 my $check = {
152 id => $check_id,
153 created_at => Date::Utility->new()->datetime_iso8601,
154 href => "/v3.4/checks/$check_id",
155 status => 'in_progress',
156 result => 'clear',
157 redirect_uri => 'https://somewhere.else',
158 results_uri => "https://onfido.com/dashboard/information_requests/<REQUEST_ID>",
159 reports_ids => create_report($data, $check_id, $applicant_id),
160 tags => $data->{tags},
161 applicant_id => $applicant_id,
162 };
163 $checks{$check_id} = $check;
164  
165 return json_response($req, clone_and_remove_private($check));
166 },
167 '/v3.4/sdk_token' => sub {
168 my $req = shift;
169 my $data = decode_json_utf8($req->body);
170 my $applicant_id = $data->{applicant_id};
171 my $referrer = $data->{referrer};
172 unless (exists($applicants{$applicant_id}) && $referrer) {
173 return json_response($req, {status => 'Not Found'});
174 }
175 my $sdk_token = {
176 token => Data::UUID->new->create_str(),
177 applicant_id => $applicant_id,
178 referrer => $referrer,
179 };
180 push @sdk_tokens, $sdk_token;
181 return json_response($req, $sdk_token);
182 },
183 },
184 get => {
185 '/v3.4/applicants' => sub {
186 my $req = shift;
187 return json_response($req, {applicants => [sort { $b->{created_at} cmp $a->{created_at} } values %applicants]});
188 },
189 '/v3.4/applicants/:id' => sub {
190 my $req = shift;
191 my @stash = route_params($req);
192 my $id = $stash[2];
193  
194 # There is no description that what result should be if there is no such applicant.
195 # So return 'Not Found' temporarily
196 my $applicant = $applicants{$id} // {status => 'Not Found'};
197  
198 return json_response($req, $applicant);
199 },
200 '/v3.4/documents' => sub {
201 my $req = shift;
202 my $query = +{$req->query_form};
203 my $applicant_id = $query->{applicant_id};
204  
205 my @documents =
206 sort { $b->{created_at} cmp $a->{created_at} }
207 map { clone_and_remove_private($_) }
208 grep { $_->{_applicant_id} eq $applicant_id } values %documents;
209  
210 return json_response($req, {documents => \@documents});
211 },
212 '/v3.4/documents/:id' => sub {
213 my $req = shift;
214 my @stash = route_params($req);
215 my $document_id = $stash[2];
216  
217 unless (exists($documents{$document_id})) {
218 return json_response($req, {status => 'Not Found'});
219 }
220  
221 return json_response($req, clone_and_remove_private($documents{$document_id}));
222 },
223 '/v3.4/documents/:document_id/download' => sub {
224 my $req = shift;
225 my @stash = route_params($req);
226 my $document_id = $stash[2];
227  
228 unless (exists($documents{$document_id})) {
229 return json_response($req, {status => 'Not Found'});
230 }
231  
232 return file_response($req, $document_id);
233 },
234 '/v3.4/live_photos' => sub {
235 my $req = shift;
236 my $query = +{$req->query_form};
237 my $applicant_id = $query->{applicant_id};
238  
239 my @photos =
240 sort { $b->{created_at} cmp $a->{created_at} }
241 map { clone_and_remove_private($_) }
242 grep { $_->{_applicant_id} eq $applicant_id } values %photos;
243  
244 return json_response($req, {live_photos => \@photos});
245 },
246 '/v3.4/live_photos/:photo_id' => sub {
247 my $req = shift;
248 my @stash = route_params($req);
249 my $photo_id = $stash[2];
250  
251 unless (exists($photos{$photo_id})) {
252 return json_response($req, {status => 'Not Found'});
253 }
254  
255 return json_response($req, clone_and_remove_private($photos{$photo_id}));
256 },
257 '/v3.4/live_photos/:photo_id/download' => sub {
258 my $req = shift;
259 my @stash = route_params($req);
260 my $photo_id = $stash[2];
261  
262 unless (exists($photos{$photo_id})) {
263 return json_response($req, {status => 'Not Found'});
264 }
265  
266 return file_response($req, $photo_id);
267 },
268 '/v3.4/checks/:check_id/download' => sub {
269 my $req = shift;
270 my @stash = route_params($req);
271 my $check_id = $stash[2];
272  
273 unless (exists($checks{$check_id})) {
274 return json_response($req, {status => 'Not Found'});
275 }
276  
277 return pdf_response($req, $check_id);
278 },
279 '/v3.4/checks/:check_id' => sub {
280 my $req = shift;
281 my @stash = route_params($req);
282 my $check_id = $stash[2];
283  
284 unless (exists($checks{$check_id})) {
285 return json_response($req, {status => 'Not Found'});
286 }
287 $checks{$check_id}{status} = 'complete';
288 return json_response($req, clone_and_remove_private($checks{$check_id}));
289 },
290 '/v3.4/checks' => sub {
291 my $req = shift;
292 my $query = +{$req->query_form};
293 my $applicant_id = $query->{applicant_id};
294  
295 my @checks =
296 sort { $b->{created_at} cmp $a->{created_at} }
297 map { clone_and_remove_private($_) }
298 grep { $_->{applicant_id} eq $applicant_id } values %checks;
299 return json_response($req, {checks => \@checks});
300 },
301 '/v3.4/reports' => sub {
302 my $req = shift;
303 my $query = +{$req->query_form};
304 my $check_id = $query->{check_id};
305  
306 my @reports =
307 sort { $b->{created_at} cmp $a->{created_at} }
308 map { clone_and_remove_private($_) }
309 grep { $_->{_check_id} eq $check_id } values %reports;
310 return json_response($req, {reports => \@reports});
311 },
312 '/v3.4/reports/:report_id' => sub {
313 my $req = shift;
314 my @stash = route_params($req);
315 my $report_id = $stash[2];
316 unless (exists($reports{$report_id})) {
317 return json_response($req, {status => 'Not Found'});
318 }
319 return json_response($req, clone_and_remove_private($reports{$report_id}));
320 },
321 },
322 put => {
323 '/v3.4/applicants/:id' => sub {
324 my $req = shift;
325 my @stash = route_params($req);
326 my $id = $stash[2];
327 my $applicant = $applicants{$id};
328 my $data = decode_json_utf8($req->body);
329 for my $k (keys %$data) {
330 $applicant->{$k} = $data->{$k};
331 }
332  
333 return json_response($req, $applicant);
334 }
335 },
336 delete => {
337 '/v3.4/applicants/:id' => sub {
338 my $req = shift;
339 my @stash = route_params($req);
340 my $id = $stash[2];
341  
342 if (exists $applicants{$id}) {
343 $deleted_applicants{$id} = delete $applicants{$id};
344 $deleted_applicants{$id}->{delete_at} =
345 Date::Utility->new()->datetime_iso8601;
346 }
347  
348 # no content
349 return HTTP::Response->new(204);
350 }
351 }};
352  
353 # here lies the http server
354  
355 my $httpserver = Net::Async::HTTP::Server->new(
356 on_request => sub {
357 my $self = shift;
358 my ($req) = @_;
359  
360 my $controller = $router->{lc $req->method}->{$req->path};
361  
362 # parametric route pairing
363 # if some route is parametric (e.g: /:document_id)
364 # we will split that path and compare coincidences against the router
365 # a full coincidence would resolve to that controller
366 unless ($controller) {
367 for my $route (keys $router->{lc $req->method}->%*) {
368 my @path_chunks = split /\//, $req->path;
369 my @route_chunks = split /\//, $route;
370  
371 next unless scalar @route_chunks == scalar @path_chunks;
372  
373 my @matching_chunks = grep {
374 my $path_chunk = shift @path_chunks;
375  
376 # a parametric path can be considered a coincidence regardless of the actual path value
377 # at that position
378 $_ =~ /^:.*/ ? 1 : $_ eq $path_chunk;
379 } @route_chunks;
380  
381 $controller = $router->{lc $req->method}->{$route}
382 if scalar @matching_chunks == scalar @route_chunks;
383  
384 last if $controller;
385 }
386 }
387  
388 $controller
389 ? $req->respond($controller->($req))
390 : $req->respond(HTTP::Response->new(404));
391 },
392 );
393  
394 # Run the HTTP server
395  
396 my $loop = IO::Async::Loop->new();
397 $loop->add($httpserver);
398  
399 $httpserver->listen(
400 addr => {
401 family => "inet6",
402 socktype => "stream",
403 port => 3000
404 },
405 )->get;
406  
407 $loop->run;
408  
409 sub END {
410 for my $f (values %files) {
411 print "removing $f\n";
412 $f->remove;
413 }
414  
415 $loop->stop;
416 }
417  
418 # HTTP SERVER UTILITIES
419  
420 # sends a json response
421  
422 sub json_response {
423 my ($req, $payload) = @_;
424  
425 my $response = HTTP::Response->new(200);
426 my $json = encode_json_utf8($payload);
427  
428 $response->add_content($json);
429 $response->content_type('application/json');
430 $response->content_length(length $response->content);
431  
432 return $response;
433 }
434 # dumps a generated on the fly really tiny pdf file
435  
436 sub pdf_response {
437 my ($req, $id) = @_;
438  
439 my $response = HTTP::Response->new(200);
440 my $file = decode_base64(DAMN_SMALL_PDF);
441  
442 $response->add_content($file);
443 $response->content_type('application/pdf');
444 $response->content_length(length $file);
445 $response->header('content-disposition' => 'attachment; filename="' . $id . '.pdf"');
446  
447 return $response;
448 }
449  
450 # dumps a file
451  
452 sub file_response {
453 my ($req, $id) = @_;
454  
455 my $response = HTTP::Response->new(200);
456 $response->add_content($files{$id}->slurp_raw);
457  
458 my $data = $documents{$id} // $photos{$id};
459  
460 $response->content_type($data->{file_type});
461 $response->content_length($data->{file_size});
462 $response->header('content-disposition' => 'attachment; filename="' . $data->{file_name} . '";');
463  
464 return $response;
465 }
466  
467 # fetch route params
468  
469 sub route_params {
470 my ($req) = @_;
471  
472 return grep { $_ ne '' } split /\//, $req->path;
473 }
474  
475 # fetch mulitpart form data
476  
477 sub multipart_data {
478 my ($req) = @_;
479  
480 my $content_type = +{map { @$_ } $req->headers}->{'Content-Type'};
481  
482 my ($boundary) = $content_type =~ /^multipart\/form-data; boundary=(.*)$/;
483  
484 return {} unless $boundary;
485  
486 my @parts = split /[\r\n]/, $req->body;
487 my $blanks = 0;
488 my $blank_spree = 0;
489 my $is_blank;
490 my $is_at_boundary;
491 my $header;
492 my $value;
493 my $name;
494 my $data = {};
495 my $headers = {};
496 my $meta = {};
497 my $body_mode = 0;
498  
499 # a good enough multipart parser
500  
501 for my $part (@parts) {
502 $is_at_boundary = $part eq "--$boundary" || $part eq "--$boundary--";
503  
504 # clean up if at boundary
505 $data->{$name} = {
506 value => $value,
507 headers => {$headers->%*},
508 $meta->%*
509 }
510 if $name && $value;
511 $blanks = 0 if $is_at_boundary;
512 $blank_spree = 0 if $is_at_boundary;
513 $body_mode = 0 if $is_at_boundary;
514 $name = undef if $is_at_boundary;
515 $value = '' if $is_at_boundary;
516 $headers = {} if $is_at_boundary;
517 $meta = {} if $is_at_boundary;
518  
519 next if $is_at_boundary;
520  
521 # blanks counter
522 $is_blank = $part eq '';
523  
524 $blanks++ if $is_blank;
525  
526 $blank_spree++ if $is_blank;
527  
528 $blank_spree = 0 unless $is_blank;
529  
530 # activate body mode
531  
532 $body_mode = 1 if $blank_spree > 2;
533  
534 next if $is_blank;
535  
536 # while body mode is off, process the headers
537  
538 $header = $part unless $body_mode;
539  
540 $header = undef if $body_mode;
541  
542 # specific name of the field
543 my $field_name;
544  
545 ($field_name) = $header =~ /^Content-Disposition: form-data; name=\"(.*?)\"/
546 if $header;
547  
548 # extract the file name if any
549 my $file_name;
550  
551 ($file_name) = $header =~ /^Content-Disposition: form-data;.*filename=\"(.*?)\"/
552 if $header;
553  
554 # process the headers
555  
556 my $header_name;
557 my $header_value;
558 ($header_name, $header_value) = split ': ', $header if $header;
559  
560 $headers->{$header_name} = $header_value if $header;
561  
562 $name = $field_name if $field_name;
563 $meta->{filename} = $file_name if $file_name;
564  
565 next unless $name;
566  
567 # while body mode is on, add to the field value
568  
569 $value .= $part if $body_mode;
570 }
571  
572 return $data;
573 }