PSGI.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« PSGI/File.pm ↑ Summary
1 package Net::AS2::PSGI;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use autodie qw(:file :filesys);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 our $VERSION = '1.0'; # VERSION
8  
9 =head1 NAME
10  
11 Net::AS2::PSGI - AS2 Protocol Plack application
12  
13 =head1 VERSION
14  
15 This documentation is for AS2 Protocol Version 1.0.
16  
17 =head1 SYNOPSIS
18  
19 ### Create an AS2 PSGI Server
20  
21 my $view_app = Net::AS2::PSGI->to_view_app();
22  
23 my $server_app = Net::AS2::PSGI->to_server_app();
24  
25 =head1 DESCRIPTION
26  
27 This module defines an AS2 Protocol compliant Plack application.
28  
29 The AS2 Protocol is specified by RFC 4130. This protocol defines a
30 secure peer-to-peer data transfer with receipt using HTTP. The receipt
31 is called a Message Disposition Notification (MDN) and is specified by
32 RFC 3798.
33  
34 The Public certificates between each partnership are exchanged
35 independently. i.e. The AS2 protocol does not allow for the public
36 certificate to be downloaded, they must be exchanged before any AS2
37 communication can occur.
38  
39 Implementations of the AS2 Protocol extend the original RFC 4130 to
40 allow for transfer over HTTPS and use of newer signing algorithms,
41 e.g. the SHA-2 family.
42  
43 The AS2 Protocol defines two modes, Synchronous and Asynchronous.
44  
45 The supported AS2 Protocol version is 1.0. Version 1.1 (compression)
46 is not supported.
47  
48 =over 4
49  
50 =item Synchronous
51  
52 In this mode the data is POSTed from the sender to the receiver and
53 the response is the MDN receipt.
54  
55 =item Asynchronous
56  
57 In this mode the data is POSTed from the sender to the receiver but
58 the response only confirms the data was sent.
59  
60 The receiver on completion of receiving the data, POSTs the MDN
61 receipt for the data back to the sender.
62  
63 =back
64  
65 =cut
66  
67 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
68  
69 4 ▶use File::Path qw(mkpath);
Subroutine BEGIN: called CC=1 SCAR=0.0
70 4 ▶use JSON::XS qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
71 4 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 4 ▶use Plack::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
74  
75 4 ▶use Net::AS2;
Subroutine BEGIN: called CC=1 SCAR=2.6
76 use Net::AS2::PSGI::FileHandler;
77 use Net::AS2::PSGI::StateHandler;
78  
79 # AS2 Directories
80 our $CERTIFICATE_DIR;
81 our $PARTNERSHIP_DIR;
82 our $FILE_DIR;
83  
84 # Certificate and Private Key Caches
85 my %CERTIFICATE = ();
86 my %PRIVATE_KEY = ();
87  
88 # API functions
89 my %API_FUNCTIONS = (
90 send => 1,
91 receive => 1,
92 MDNsend => 1,
93 MDNreceive => 1,
94 );
95  
96 # HTTP Codes
97 use constant HTTP_OK => 200;
98 use constant HTTP_BAD_REQUEST => 404;
99  
100 =head1 CONFIGURATION AND ENVIRONMENT
101  
102 The server uses the following directories.
103  
104 =over 4
105  
106 =item certificate_dir
107  
108 This directory contains Private and Public Certificate pairings and
109 the Public Certificate for each defined Partnership.
110  
111 For security, this directory and the files within it should not be
112 world readable.
113  
114 An alternative, is to either supply the key and certificate text
115 strings directly in the L<Net::AS2> hash or supply an alternative
116 directory per partnership, using the C<CertificateDirectory>
117 L<Net::AS2> hash key.
118  
119 =item partnership_dir
120  
121 This directory contains JSON files that each define a partnership
122 between two AS2 Protocol Servers.
123  
124 Subdirectories may be used, with the whole relative path being used to
125 define the partnership name.
126  
127 For security, this directory and the files within it should not be
128 world readable.
129  
130 The partnership file contains the key names defined in L<Net::AS2>, along with the following additions:
131  
132 =over 4
133  
134 =item FileHandlerClass
135  
136 A Perl class that can process the files being sent and received via the AS2 protocol.
137 See L<Net::AS2::PSGI::FileHandler>, default is "Net::AS2::PSGI::FileHandler".
138  
139 =back
140  
141 =item file_dir
142  
143 This directory will contain either files received from a partnership
144 transfer or an MDN after sending data to a partnership.
145  
146 For security, this directory and the files within it should not be
147 world readable.
148  
149 The directory structure is as follows:
150  
151 =over 4
152  
153 =item partnership
154  
155 The subdirectory structure is created and named after the partnership
156 file (without the .json extension). For security, this directory
157 structure is created with owner read/write only.
158  
159 The files being transferred between this partnership are then stored
160 under the following directories:
161  
162 =over 4
163  
164 =item SENDING
165  
166 Files here are being sent to the partner, but no receipt has been received yet.
167  
168 =item SENT
169  
170 Files here have been sent to the partner and a receipt has been received.
171  
172 =item RECEIVING
173  
174 Files here are being received from the partner, but no receipt has been sent yet.
175  
176 =item RECEIVED
177  
178 Files here have been received from the partner and a receipt has been sent.
179  
180 =back
181  
182 =back
183  
184 =back
185  
186 =head1 SUBROUTINES
187  
188 =over 4
189  
190 =item init ( $config, $log )
191  
192 Class Method for initialising the AS2 directory structures.
193  
194 =cut
195  
196 sub init {
197 my ($class, $config, $log) = @_;
198  
199 # initialise the package variables, unless already defined.
200 $CERTIFICATE_DIR //= $config->{certificate_dir};
201 $PARTNERSHIP_DIR //= $config->{partnership_dir};
202 $FILE_DIR //= $config->{file_dir};
203  
204 if ($log) {
205 $log->({ level => 'warn', message => "Failed to set CERTIFICATE_DIR" }) unless $CERTIFICATE_DIR;
206 $log->({ level => 'warn', message => "Failed to set PARTNERSHIP_DIR" }) unless $PARTNERSHIP_DIR;
207 $log->({ level => 'warn', message => "Failed to set FILE_DIR" }) unless $FILE_DIR;
208 }
209  
210 _create_directories($log, 'init', $CERTIFICATE_DIR, $PARTNERSHIP_DIR, $FILE_DIR);
211  
212 return;
213 }
214  
215 =item view_psgi ()
216  
217 Class Method returning a PSGI application for viewing partnerships.
218  
219 This app is B<not> part of the AS2 specification. It may be useful
220 for checking end-to-end access between partners and confirming
221 partnership configurations.
222  
223 =cut
224  
225 sub view_psgi {
226 my ($class) = @_;
227  
228 return sub {
229 my $request = Plack::Request->new(shift);
230  
231 return _error_bad_request($request, "Called HTTP Method is not GET")->finalize
232 unless $request->method eq 'GET';
233  
234 return $class->view($request)->finalize;
235 };
236 }
237  
238 =item app_psgi ()
239  
240 Class Method returning a PSGI application for AS2.
241  
242 =cut
243  
244 sub app_psgi {
245 my ($class) = @_;
246  
247 return sub {
248 my $request = Plack::Request->new(shift);
249  
250 return _error_bad_request($request, "Called HTTP Method is not POST")->finalize
251 unless $request->method eq 'POST';
252  
253 return $class->app($request)->finalize;
254 };
255 }
256  
257 =item app ( request )
258  
259 API Method implementing AS2.
260  
261 =back
262  
263 =cut
264  
265 sub app {
266 my ($class, $request) = @_;
267  
268 my ($api, $new_path) = $request->path =~ m{/(\w+)(/.*)};
269  
270 return _error_bad_request($request, 'No API function: "' . ($api // '') . '"')
271 unless $api && $new_path && exists $API_FUNCTIONS{$api};
272  
273 $request->env->{PATH_INFO} = $new_path;
274  
275 return $class->$api($request);
276 }
277  
278 =head1 API METHODS
279  
280 All API methods receive a Plack request as their one and only argument.
281  
282 =over 4
283  
284 =item send ( request )
285  
286 To send data to a partner, a POST request is created with a URL of the form /send/C<partnership>
287  
288 The data is sent as the content of the POST request along with the following headers:
289  
290 =over 4
291  
292 =item MessageId
293  
294 The AS2 Message ID.
295  
296 The Message ID is validated to ensure it conforms to RFC 822.
297  
298 In Asynchronous mode, the received MDN will include this value as the
299 C<Original Message ID>, thus tying the two independent POST requests
300 (send and MDN receipt) together, to complete the transfer.
301  
302 =item Content-Type
303  
304 The Content-Type of the data being sent.
305  
306 =item Subject
307  
308 I<Optional.>
309 The subject is an arbitrary brief one-line string. Default is "AS2 Message".
310  
311 =item Filename
312  
313 I<Optional.>
314 Sets the Content-Disposition filename. Default is "payload".
315  
316 =back
317  
318 =cut
319  
320 sub send { ## no critic (ProhibitBuiltinHomonyms)
321 my ($class, $request) = @_;
322  
323 my $log = $request->logger;
324 my $headers = $request->headers;
325  
326 my $message_id = $headers->header('MessageId');
327 return _error_bad_request($request, 'send not given MessageId header') unless $message_id;
328  
329 my $partnership = _partnership($request, $message_id, 'Starting to send data');
330  
331 my $as2 = _as2($partnership);
332  
333 $message_id = $as2->get_message_id($message_id);
334  
335 my $state = Net::AS2::PSGI::StateHandler->new($message_id, $log);
336  
337 my $handler = $as2->{FileHandlerClass}->new($message_id, $log) or croak "FileHandlerClass is not configured";
338  
339 my ($sending, $sent) = _send_directories($request, $message_id, $partnership);
340  
341 my $state_content = JSON::XS->new->ascii->canonical->encode({ mdn => $as2->{Mdn}, pending => \1 });
342  
343 my $message_file_state = $state->save($state_content, $sending);
344  
345 my $content = $request->content;
346 my %mime_options = (
347 'MessageId' => $message_id,
348 'Type' => scalar($headers->content_type),
349 'Subject' => scalar($headers->header('Subject')),
350 'Filename' => scalar($headers->header('Filename')),
351 );
352 my ($mdn, $mic, $mic_alg) = $as2->send($content, %mime_options);
353  
354 my $sending_file = $handler->file($sending);
355  
356 $handler->sending($content, $sending_file);
357  
358 my $response = $request->new_response(HTTP_OK);
359  
360 if ($mdn->{status_text} =~ qr{HTTP failure: (\d+) (.*)}) {
361 $response->code($1);
362 $response->body($2);
363  
364 # overwrite state file in SENDING directory
365 $state_content = JSON::XS->new->ascii->canonical->encode({ %$mdn });
366  
367 $message_file_state = $state->save($state_content, $sending); # convert to simple hash
368  
369 $state->move($message_file_state, $sent, '.failed', " ($mdn->{status_text})");
370  
371 $handler->sent($sending_file, $sent, 0);
372  
373 return $response;
374 }
375 elsif ($as2->{Mdn} eq 'async') {
376 return $response;
377 }
378  
379 my $match_mic = $mdn->match_mic($mic, $mic_alg) ? 1 : 0;
380 my $successful = $mdn->is_success && $match_mic ? 1 : 0;
381  
382 my $body = JSON::XS->new->ascii->canonical->encode({
383 match_mic => $match_mic,
384 successful => $successful,
385 %$mdn, # convert to simple hash
386 });
387  
388 $response->body($body);
389 $response->headers([
390 'OriginalMessageId' => $mdn->original_message_id,
391 'Content-Type' => 'application/json; charset=utf-8',
392 'Content-Length' => length($body),
393 ]);
394  
395 $message_file_state = $state->save($body, $sending);
396  
397 my $ext = $successful ? '' : '.failed';
398 $state->move($message_file_state, $sent, $ext, '(send)');
399  
400 $handler->sent($sending_file, $sent, $successful);
401  
402 return $response;
403 }
404  
405  
406 =item receive ( request )
407  
408 To receive data from a partner, a POST request is received via a URL of the form /receive/C<partnership>
409  
410 The data is received as the content of the POST request along with the following headers:
411  
412 =over 4
413  
414 =item Message-Id
415  
416 The AS2 Message ID.
417  
418 The Message ID is validated to ensure it conforms to RFC 2822.
419  
420 =item Content-Type
421  
422 The Content-Type of the data being received.
423  
424 =item AS2-Version
425  
426 The AS2 Protocol version, it should be in the form 1.x. Only 1.0 is supported.
427  
428 See RFC 4130 for further details about the different version numbers.
429  
430 =item AS2-From
431  
432 The partner's AS2 ID.
433  
434 This value should match the PartnerId in the C<partnership.json> file.
435  
436 =item AS2-To
437  
438 The receiver's (i.e. this application's) AS2 ID.
439  
440 This value should match the MyId in the C<partnership.json> file.
441  
442 =item Disposition-Notification-Options
443  
444 I<Optional> This header is only defined if digital signatures are requested.
445  
446 This header contains the requirements for the digital signature.
447 An example is:
448  
449 signed-receipt-protocol=required, pkcs7-signature; signed-receipt-micalg=required, sha256
450  
451 =item Receipt-Delivery-Option
452  
453 I<Optional> This header is only defined for Asynchronous mode.
454  
455 This header defines a URL for the receiver to POST the MDN receipt to,
456 once the data has been received.
457  
458 =back
459  
460 =cut
461  
462 sub receive {
463 my ($class, $request) = @_;
464  
465 my $log = $request->logger;
466 my $headers = $request->headers;
467  
468 my $message_id = $headers->header('Message-Id');
469 return _error_bad_request($request, 'receive not given Message-Id header') unless $message_id;
470  
471 my $partnership = _partnership($request, $message_id, 'Starting to receive data');
472  
473 my $as2 = _as2($partnership);
474  
475 $message_id = $as2->get_message_id($message_id);
476  
477 my $state = Net::AS2::PSGI::StateHandler->new($message_id, $log);
478  
479 my $handler = $as2->{FileHandlerClass}->new($message_id, $log) or croak "FileHandlerClass is not configured";
480  
481 my ($receiving, $received) = _receive_directories($request, $message_id, $partnership);
482  
483 # Decode the incoming HTTP request as AS2 Message.
484 my $message = $as2->decode_message($headers, $request->content);
485  
486 my $message_file_state = $state->save($message->serialized_state, $receiving);
487  
488 my $receiving_file = $handler->receiving($message->content, $receiving);
489  
490 my $response = $request->new_response(HTTP_OK);
491  
492 my $mode = $message->is_mdn_async ? 'async' : 'sync';
493  
494 $log->({ level => 'info', message => "<$message_id> : Receiving $mode message from $partnership" }) if $log;
495  
496 # $log->({ level => 'debug', message => "<$message_id> : Receiving sync content:\n------\n" . $message->content . "\n------\n" }) if $log;
497  
498 if ($mode eq 'sync') {
499 my ($h, $c) = $as2->prepare_sync_mdn(
500 $message->is_success ?
501 Net::AS2::MDN->create_success($message) :
502 Net::AS2::MDN->create_from_unsuccessful_message($message)
503 );
504  
505 $response->headers($h);
506 $response->body($c);
507  
508 my $ext = $message->is_success ? '' : $message->is_failure ? '.failed' : '.error';
509 $state->move($message_file_state, $received, $ext, '(receive)');
510  
511 $handler->received($receiving_file, $received, $message);
512 }
513  
514 return $response;
515 }
516  
517  
518 =item MDNsend ( request )
519  
520 Sends an MDN message to a partner.
521  
522 The POST request is created with a URL of the form
523 /MDNsend/C<partnership> along with the following headers:
524  
525 =over 4
526  
527 =item MessageId
528  
529 The AS2 Message ID.
530  
531 The Message ID is validated to ensure it conforms to RFC 2822.
532  
533 =back
534  
535 In the RECEIVING directory, the file containing the saved MDN state of
536 the given Message ID is read and an MDN response is created from the
537 content. The MDN response is POSTed to the partner.
538  
539 If the POST fails, the POST response code and content is stored in a
540 file called C<Message-Id>.C<Timestamp: %F-%H-%M-%S>.mdn-failed in the
541 RECEIVING directory and the POST response code is returned.
542  
543 Otherwise, the data file is moved from the RECEIVING directory to
544 RECEIVED and the MDN state file is moved from the RECEIVING directory
545 to RECEIVED and renamed to have a .sent extension. If the MDN message
546 is not indicating success, the data filename is also renamed to have a
547 .failed extension.
548  
549 =cut
550  
551 sub MDNsend {
552 my ($class, $request) = @_;
553  
554 my $log = $request->logger;
555 my $headers = $request->headers;
556  
557 my $message_id = $headers->header('MessageId');
558 return _error_bad_request($request, 'MDNsend not given MessageId header') unless $message_id;
559  
560 my $partnership = _partnership($request, $message_id, 'Starting to send MDN receipt');
561  
562 my $as2 = _as2($partnership);
563  
564 $message_id = $as2->get_message_id($message_id);
565  
566 my $state = Net::AS2::PSGI::StateHandler->new($message_id, $log);
567  
568 my $handler = $as2->{FileHandlerClass}->new($message_id, $log) or croak "FileHandlerClass is not configured";
569  
570 my ($receiving, $received) = _receive_directories($request, $message_id, $partnership);
571  
572 my $state_file = $state->file($receiving);
573  
574 my $state_content = $state->retrieve($state_file, 'Read MDN contact details');
575  
576 my $message = Net::AS2::Message->create_from_serialized_state($state_content);
577 my $mdn_resp = $as2->send_async_mdn(
578 $message->is_success ?
579 Net::AS2::MDN->create_success($message) :
580 Net::AS2::MDN->create_from_unsuccessful_message($message),
581 $message->message_id,
582 );
583  
584 my $code;
585 if ($mdn_resp->is_success) {
586 $code = HTTP_OK;
587  
588 $state->move($state_file, $received, '.sent', '(MDNsend)');
589  
590 $state->logger(info => "Sent MDN receipt to $partnership") if $log;
591 }
592 else {
593 $code = $mdn_resp->code;
594  
595 my $status_text = $mdn_resp->message;
596  
597 my $ext = $message->is_error ? '.error' : '.failed';
598  
599 my $content = $code . "\n" . strftime("%F-%H-%M-%S", localtime) . "\n" . $mdn_resp->content;
600  
601 my $message_state_failure = $state->save($content, $receiving, ".response.$ext");
602  
603 $state->move($message_state_failure, $received, ".response.$ext", $status_text);
604  
605 $state->logger(warn => "Failed to send MDN receipt. See $message_state_failure") if $log;
606  
607 $state->move($state_file, $received, $ext, $status_text);
608  
609 }
610  
611 my $receiving_file = $handler->file($receiving);
612  
613 $handler->received($receiving_file, $received, $message);
614  
615 return $request->new_response($code);
616 }
617  
618 =item MDNreceive ( request )
619  
620 Receives an MDN receipt from a partner.
621  
622 The POST request is received via a URL of the form
623 /MDNreceive/C<partnership>
624  
625 The received MDN is decoded.
626  
627 If the receipt is for a successful transfer, the Original Message ID
628 is extracted and the file in the SENDING directory is moved to the
629 SENT directory and its contents replaced with the decoded MDN details.
630  
631 Otherwise, the MDN details are stored in SENDING directory with a
632 filename called UNKNOWN.MDN.C<Message-Id> with a 200 HTTP response
633 being returned.
634  
635 =over 4
636  
637 =item Message-Id
638  
639 The AS2 Message ID.
640  
641 The Message ID is validated to ensure it conforms to RFC 2822.
642  
643 =item Content-Type
644  
645 The Content-Type of the data being received.
646  
647 =item AS2-Version
648  
649 The AS2 Protocol version, it should be in the form 1.x. Only 1.0 is supported.
650  
651 See RFC 4130 for further details about the different version numbers.
652  
653 =item AS2-From
654  
655 The partner's AS2 ID.
656  
657 This value should match the PartnerId in the C<partnership.json> file.
658  
659 =item AS2-To
660  
661 The receiver's (i.e. this application's) AS2 ID.
662  
663 This value should match the MyId in the C<partnership.json> file.
664  
665 =back
666  
667 =cut
668  
669 sub MDNreceive {
670 my ($class, $request) = @_;
671  
672 my $log = $request->logger;
673 my $headers = $request->headers;
674  
675 my $message_id = $headers->header('Message-Id');
676 return _error_bad_request($request, 'MDNreceive not given Message-Id header') unless $message_id;
677  
678 my $partnership = _partnership($request, $message_id, 'Starting to receive MDN');
679  
680 my $as2 = _as2($partnership);
681  
682 $message_id = $as2->get_message_id($message_id);
683  
684 my $state = Net::AS2::PSGI::StateHandler->new($message_id, $log);
685  
686 my $handler = $as2->{FileHandlerClass}->new($message_id, $log) or croak "FileHandlerClass is not configured";
687  
688 my ($sending, $sent) = _send_directories($request, $message_id, $partnership);
689  
690 my $mdn = $as2->decode_mdn($headers, $request->content);
691  
692 if (my $original_message_id = $mdn->original_message_id) {
693 $state->logger(debug => "MDN original message ID <$original_message_id> from $partnership") if $log;
694  
695 # This code silently allows for repeated MDN receive requests
696  
697 $state->message_id($original_message_id);
698  
699 my $body = JSON::XS->new->ascii->canonical->encode({ %$mdn }); # convert to simple hash
700  
701 my $message_file_state = $state->save($body, $sending);
702  
703 my $message_file_state_sent = $state->file($sent);
704 $state->logger(warn => "MDN already received, file exists: $message_file_state_sent")
705 if $log && -f $message_file_state_sent;
706  
707 my $ext = $mdn->is_success ? '' : '.failed';
708 $state->move($message_file_state, $sent, $ext, '(MDNreceive)');
709  
710 $state->logger(info => "Received MDN$ext receipt from $partnership") if $log;
711  
712 my $sending_file = $handler->file($sending);
713  
714 if (-f $sending_file) {
715 $handler->sent($sending_file, $sent, $mdn->is_success);
716 }
717 }
718 else {
719 my $receipt_file = $state->save($request->content, $sending, '.UNKNOWN.MDN');
720  
721 $state->logger(debug => 'MDN receipt did not contain valid original_message_id') if $log;
722 }
723  
724 return $request->new_response(HTTP_OK);
725 }
726  
727 =item view ( env )
728  
729 View a given partnership configuration.
730  
731 The request is received via a URL of the form
732 /view/C<partnership>
733  
734 The actual content of the cached private key or certificates are not
735 displayed, replaced instead by "...".
736  
737 =back
738  
739 =cut
740  
741 sub view {
742 my ($class, $request) = @_;
743  
744 my $partnership = _partnership($request, '<view>', 'View API');
745  
746 my $as2 = _as2($partnership);
747  
748 # Display relevant partnership, blanking out private and public key text
749 my $p = { %$as2 };
750 map { delete $p->{$_} } grep { ref($p->{$_}) } keys %$p;
751 map { $p->{$_} = '...' } grep { /^.+Certificate|Key/ && ! /File/ } keys %$p;
752  
753 my $content = JSON::XS->new->ascii->canonical->encode($p);
754  
755 my $response = $request->new_response(HTTP_OK);
756 $response->body($content);
757 $response->headers([
758 'Content-Type' => 'application/json; charset=utf-8',
759 'Content-Length' => length($content),
760 ]);
761  
762 return $response;
763 }
764  
765  
766 # INTERNAL FUNCTIONS
767 #
768  
769 # _partnership ( request, message_id, text )
770 #
771 # get partnership from URI.
772 #
773 sub _partnership {
774 my ($request, $message_id, $text) = @_;
775  
776 my $log = $request->logger;
777  
778 $log->({ level => 'debug', message => "$message_id : $text" }) if $log;
779  
780 (my $partnership = $request->path) =~ s{^/}{};
781  
782 $log->({ level => 'debug', message => "$message_id : from $partnership" }) if $log;
783  
784 return $partnership;
785 }
786  
787 # _as2 ( partnership )
788 #
789 # Internal routine that returns the L<Net::AS2> object configured
790 # using a relative filename given by C<partnership>, without the .json
791 # file extension.
792 #
793 # The partnership files are located in C<$PARTNERSHIP_DIR>, given by the
794 # configuration file.
795 #
796  
797 sub _as2 {
798 my ($partnership) = @_;
799  
800 my $file = "$PARTNERSHIP_DIR/$partnership.json";
801  
802 croak "No partnership file $file" unless -f $file;
803  
804 local $/ = undef;
805  
806 open my $fh, '<', $file;
807 my $json = scalar(<$fh>);
808 close $fh;
809  
810 my $params = JSON::XS->new->relaxed->decode($json);
811  
812 # Set the certificate directory unless already given for this specific partnership
813 $params->{CertificateDirectory} //= $CERTIFICATE_DIR;
814  
815 # Set the default File Handling Class
816 $params->{FileHandlerClass} //= 'Net::AS2::PSGI::FileHandler';
817  
818 return Net::AS2->new(%$params); # Will die if the parameters are not valid
819 }
820  
821 sub _send_directories {
822 my ($request, $message_id, $partnership) = @_;
823  
824 my $parent = $FILE_DIR . '/' . $partnership;
825 my $sending = "$parent/SENDING";
826 my $sent = "$parent/SENT";
827  
828 _create_directories($request->logger, $message_id, $parent, $sending, $sent);
829  
830 return ($sending, $sent);
831 }
832  
833 sub _receive_directories {
834 my ($request, $message_id, $partnership) = @_;
835  
836 my $parent = $FILE_DIR . '/' . $partnership;
837 my $receiving = "$parent/RECEIVING";
838 my $received = "$parent/RECEIVED";
839  
840 _create_directories($request->logger, $message_id, $parent, $receiving, $received);
841  
842 return ($receiving, $received);
843 }
844  
845 sub _create_directories {
846 my ($log, $message_id, @dir) = @_;
847  
848 my $status;
849 my $level;
850 my @errors;
851  
852 foreach my $dir (@dir) {
853 next if -d $dir;
854 if (mkpath($dir, 0, oct(700))) {
855 $status = 'Created';
856 $level = 'debug';
857 }
858 else {
859 $status = 'Error creating';
860 $level = 'error';
861 push @errors, $dir;
862 }
863 $log->({ level => $level, message => "<$message_id> $status directory $dir" }) if $log;
864 }
865 croak "Error creating directories: @errors" if @errors;
866  
867 return;
868 }
869  
870 sub _error_bad_request {
871 my ($request, $message) = @_;
872  
873 if (my $log = $request->logger) {
874 $log->({ level => 'error', message => $message });
875 }
876  
877 return $request->new_response(HTTP_BAD_REQUEST);
878 }
879  
880 1;
881  
882 =head1 EXAMPLES
883  
884 This module has an /examples directory. It contains an example PSGI
885 application, its base configuration file, a systemd service for
886 starman and an nginx conf file with SSL configurations. There is also
887 some basic configuration files to get you started with partnering up
888 with an instance of L<https://github.com/phax/as2-server>.
889  
890 The module's /t testing directory, includes test cases that forks AS2
891 L<Plack::Test> applications, and then tests transferring files between
892 using AS2 synchronous and AS2 asynchronous transfer modes.
893  
894 =head1 SEE ALSO
895  
896 L<Net::AS2>, L<Net::AS2::PSGI::FileHandler>, L<Net::AS2::PSGI::StateHandler>
897  
898 L<RFC 4130|https://www.ietf.org/rfc/rfc4130.txt>, L<RFC 3798|https://www.ietf.org/rfc/rfc3798.txt>,
899 L<RFC 822|https://www.ietf.org/rfc/rfc822.txt>, L<RFC 2822|https://www.ietf.org/rfc/rfc2822.txt>
900  
901 =head1 LICENSE AND COPYRIGHT
902  
903 This software is copyright (c) 2019 by Catalyst IT, <ajm@cpan.org>
904  
905 This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
906  
907 =head1 BUGS AND LIMITATIONS
908  
909 =over 4
910  
911 =item Content-Transfer-Encoding: binary and LF line-endings
912  
913 During testing against an Oracle B2B implementation, an issue with
914 Digital Signatures was found. The Oracle instance was sending data
915 with LF line-endings using binary Content-Transfer-Encoding.
916  
917 The L<Crypt::SMIME> validation failed the signature check.
918  
919 A similar scenario occurred when testing with RSSBus software. In that
920 case, just sending the file with CRLF line-endings was successful. It
921 was not possible to test whether the same workaround would work with
922 Oracle B2B. Another possibility is to configure sending/receiving base64
923 Content-Transfer-Encoding requests.
924  
925 The issue may lie in the OpenSSL canonicalisation code when handling
926 binary Content-Transfer-Encoding data. It appears to incorrectly apply
927 canonicalisation of binary specified data. (OpenSSL version 1.1.0g).
928  
929 =item AS2 1.1 compression
930  
931 The AS2 Protocol Version 1.1 (compression) is not supported.
932  
933 =item Filesystem initiated interface
934  
935 Unlike other AS2 software, this module does not provide a means to
936 send file to partners simply by copying a file to a designated 'send'
937 directory. That functionality could probably be created by combining
938 L<AnyEvent>, L<Twiggy> and this PSGI interface.
939  
940 =back
941  
942 =head1 DISCLAIMER OF WARRANTY
943  
944 This module is not certificated by any AS2 body. This module creates a basic AS2 server.
945  
946 When using this server, you must have reviewed and be responsible for
947 all the actions and inactions caused by this server.
948  
949 More legal jargon follows:
950  
951 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
952  
953 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
954  
955 =head1 AUTHOR
956  
957 Andrew Maguire ajm@cpan.org
« PSGI/File.pm ↑ Summary