first pass RT4 merge, RT#13852
[freeside.git] / rt / lib / RT / Test / GnuPG.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2012 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 package RT::Test::GnuPG;
50 use strict;
51 use Test::More;
52 use base qw(RT::Test);
53 use File::Temp qw(tempdir);
54
55 our @EXPORT =
56   qw(create_a_ticket update_ticket cleanup_headers set_queue_crypt_options 
57           check_text_emails send_email_and_check_transaction
58           create_and_test_outgoing_emails
59           );
60
61 sub import {
62     my $class = shift;
63     my %args  = @_;
64     my $t     = $class->builder;
65
66     $t->plan( skip_all => 'GnuPG required.' )
67       unless eval { require GnuPG::Interface; 1 };
68     $t->plan( skip_all => 'gpg executable is required.' )
69       unless RT::Test->find_executable('gpg');
70
71     require RT::Crypt::GnuPG;
72     $class->SUPER::import(%args);
73
74     RT::Test::diag "GnuPG --homedir " . RT->Config->Get('GnuPGOptions')->{'homedir'};
75
76     $class->set_rights(
77         Principal => 'Everyone',
78         Right => ['CreateTicket', 'ShowTicket', 'SeeQueue', 'ReplyToTicket', 'ModifyTicket'],
79     );
80
81     $class->export_to_level(1);
82 }
83
84 sub bootstrap_more_config {
85     my $self = shift;
86     my $handle = shift;
87     my $args = shift;
88
89     $self->SUPER::bootstrap_more_config($handle, $args, @_);
90
91     my %gnupg_options = (
92         'no-permission-warning' => undef,
93         $args->{gnupg_options} ? %{ $args->{gnupg_options} } : (),
94     );
95     $gnupg_options{homedir} ||= scalar tempdir( CLEANUP => 1 );
96
97     use Data::Dumper;
98     local $Data::Dumper::Terse = 1; # "{...}" instead of "$VAR1 = {...};"
99     my $dumped_gnupg_options = Dumper(\%gnupg_options);
100
101     print $handle qq{
102 Set(\%GnuPG, (
103     Enable                 => 1,
104     OutgoingMessagesFormat => 'RFC',
105 ));
106 Set(\%GnuPGOptions => \%{ $dumped_gnupg_options });
107 Set(\@MailPlugins => qw(Auth::MailFrom Auth::GnuPG));
108 };
109
110 }
111
112 sub create_a_ticket {
113     my $queue = shift;
114     my $mail = shift;
115     my $m = shift;
116     my %args = (@_);
117
118     RT::Test->clean_caught_mails;
119
120     $m->goto_create_ticket( $queue );
121     $m->form_name('TicketCreate');
122     $m->field( Subject    => 'test' );
123     $m->field( Requestors => 'rt-test@example.com' );
124     $m->field( Content    => 'Some content' );
125
126     foreach ( qw(Sign Encrypt) ) {
127         if ( $args{ $_ } ) {
128             $m->tick( $_ => 1 );
129         } else {
130             $m->untick( $_ => 1 );
131         }
132     }
133
134     $m->submit;
135     is $m->status, 200, "request successful";
136
137     $m->content_lacks("unable to sign outgoing email messages");
138
139
140     my @mail = RT::Test->fetch_caught_mails;
141     check_text_emails(\%args, @mail );
142     categorize_emails($mail, \%args, @mail );
143 }
144
145 sub update_ticket {
146     my $tid = shift;
147     my $mail = shift;
148     my $m = shift;
149     my %args = (@_);
150
151     RT::Test->clean_caught_mails;
152
153     $m->get( $m->rt_base_url . "/Ticket/Update.html?Action=Respond&id=$tid" );
154     $m->form_number(3);
155     $m->field( UpdateContent => 'Some content' );
156
157     foreach ( qw(Sign Encrypt) ) {
158         if ( $args{ $_ } ) {
159             $m->tick( $_ => 1 );
160         } else {
161             $m->untick( $_ => 1 );
162         }
163     }
164
165     $m->click('SubmitTicket');
166     is $m->status, 200, "request successful";
167     $m->content_contains("Message recorded", 'Message recorded') or diag $m->content;
168
169
170     my @mail = RT::Test->fetch_caught_mails;
171     check_text_emails(\%args, @mail );
172     categorize_emails($mail, \%args, @mail );
173 }
174
175 sub categorize_emails {
176     my $mail = shift;
177     my $args = shift;
178     my @mail = @_;
179
180     if ( $args->{'Sign'} && $args->{'Encrypt'} ) {
181         push @{ $mail->{'signed_encrypted'} }, @mail;
182     }
183     elsif ( $args->{'Sign'} ) {
184         push @{ $mail->{'signed'} }, @mail;
185     }
186     elsif ( $args->{'Encrypt'} ) {
187         push @{ $mail->{'encrypted'} }, @mail;
188     }
189     else {
190         push @{ $mail->{'plain'} }, @mail;
191     }
192 }
193
194 sub check_text_emails {
195     my %args = %{ shift @_ };
196     my @mail = @_;
197
198     ok scalar @mail, "got some mail";
199     for my $mail (@mail) {
200         for my $type ('email', 'attachment') {
201             next if $type eq 'attachment' && !$args{'Attachment'};
202
203             my $content = $type eq 'email'
204                         ? "Some content"
205                         : "Attachment content";
206
207             if ( $args{'Encrypt'} ) {
208                 unlike $mail, qr/$content/, "outgoing $type was encrypted";
209             } else {
210                 like $mail, qr/$content/, "outgoing $type was not encrypted";
211             } 
212
213             next unless $type eq 'email';
214
215             if ( $args{'Sign'} && $args{'Encrypt'} ) {
216                 like $mail, qr/BEGIN PGP MESSAGE/, 'outgoing email was signed';
217             } elsif ( $args{'Sign'} ) {
218                 like $mail, qr/SIGNATURE/, 'outgoing email was signed';
219             } else {
220                 unlike $mail, qr/SIGNATURE/, 'outgoing email was not signed';
221             }
222         }
223     }
224 }
225
226 sub cleanup_headers {
227     my $mail = shift;
228     # strip id from subject to create new ticket
229     $mail =~ s/^(Subject:)\s*\[.*?\s+#\d+\]\s*/$1 /m;
230     # strip several headers
231     foreach my $field ( qw(Message-ID X-RT-Original-Encoding RT-Originator RT-Ticket X-RT-Loop-Prevention) ) {
232         $mail =~ s/^$field:.*?\n(?! |\t)//gmsi;
233     }
234     return $mail;
235 }
236
237 sub set_queue_crypt_options {
238     my $queue = shift;
239     my %args = @_;
240     $queue->SetEncrypt($args{'Encrypt'});
241     $queue->SetSign($args{'Sign'});
242 }
243
244 sub send_email_and_check_transaction {
245     my $mail = shift;
246     my $type = shift;
247
248     my ( $status, $id ) = RT::Test->send_via_mailgate($mail);
249     is( $status >> 8, 0, "The mail gateway exited normally" );
250     ok( $id, "got id of a newly created ticket - $id" );
251
252     my $tick = RT::Ticket->new( RT->SystemUser );
253     $tick->Load($id);
254     ok( $tick->id, "loaded ticket #$id" );
255
256     my $txn = $tick->Transactions->First;
257     my ( $msg, @attachments ) = @{ $txn->Attachments->ItemsArrayRef };
258
259     if ( $attachments[0] ) {
260         like $attachments[0]->Content, qr/Some content/,
261           "RT's mail includes copy of ticket text";
262     }
263     else {
264         like $msg->Content, qr/Some content/,
265           "RT's mail includes copy of ticket text";
266     }
267
268     if ( $type eq 'plain' ) {
269         ok !$msg->GetHeader('X-RT-Privacy'), "RT's outgoing mail has no crypto";
270         is $msg->GetHeader('X-RT-Incoming-Encryption'), 'Not encrypted',
271           "RT's outgoing mail looks not encrypted";
272         ok !$msg->GetHeader('X-RT-Incoming-Signature'),
273           "RT's outgoing mail looks not signed";
274     }
275     elsif ( $type eq 'signed' ) {
276         is $msg->GetHeader('X-RT-Privacy'), 'PGP',
277           "RT's outgoing mail has crypto";
278         is $msg->GetHeader('X-RT-Incoming-Encryption'), 'Not encrypted',
279           "RT's outgoing mail looks not encrypted";
280         like $msg->GetHeader('X-RT-Incoming-Signature'),
281           qr/<rt-recipient\@example.com>/,
282           "RT's outgoing mail looks signed";
283     }
284     elsif ( $type eq 'encrypted' ) {
285         is $msg->GetHeader('X-RT-Privacy'), 'PGP',
286           "RT's outgoing mail has crypto";
287         is $msg->GetHeader('X-RT-Incoming-Encryption'), 'Success',
288           "RT's outgoing mail looks encrypted";
289         ok !$msg->GetHeader('X-RT-Incoming-Signature'),
290           "RT's outgoing mail looks not signed";
291
292     }
293     elsif ( $type eq 'signed_encrypted' ) {
294         is $msg->GetHeader('X-RT-Privacy'), 'PGP',
295           "RT's outgoing mail has crypto";
296         is $msg->GetHeader('X-RT-Incoming-Encryption'), 'Success',
297           "RT's outgoing mail looks encrypted";
298         like $msg->GetHeader('X-RT-Incoming-Signature'),
299           qr/<rt-recipient\@example.com>/,
300           "RT's outgoing mail looks signed";
301     }
302     else {
303         die "unknown type: $type";
304     }
305 }
306
307 sub create_and_test_outgoing_emails {
308     my $queue = shift;
309     my $m     = shift;
310     my @variants =
311       ( {}, { Sign => 1 }, { Encrypt => 1 }, { Sign => 1, Encrypt => 1 }, );
312
313     # collect emails
314     my %mail;
315
316     # create a ticket for each combination
317     foreach my $ticket_set (@variants) {
318         create_a_ticket( $queue, \%mail, $m, %$ticket_set );
319     }
320
321     my $tid;
322     {
323         my $ticket = RT::Ticket->new( RT->SystemUser );
324         ($tid) = $ticket->Create(
325             Subject   => 'test',
326             Queue     => $queue->id,
327             Requestor => 'rt-test@example.com',
328         );
329         ok $tid, 'ticket created';
330     }
331
332     # again for each combination add a reply message
333     foreach my $ticket_set (@variants) {
334         update_ticket( $tid, \%mail, $m, %$ticket_set );
335     }
336
337 # ------------------------------------------------------------------------------
338 # now delete all keys from the keyring and put back secret/pub pair for rt-test@
339 # and only public key for rt-recipient@ so we can verify signatures and decrypt
340 # like we are on another side recieve emails
341 # ------------------------------------------------------------------------------
342
343     unlink $_
344       foreach glob( RT->Config->Get('GnuPGOptions')->{'homedir'} . "/*" );
345     RT::Test->import_gnupg_key( 'rt-recipient@example.com', 'public' );
346     RT::Test->import_gnupg_key('rt-test@example.com');
347
348     $queue = RT::Test->load_or_create_queue(
349         Name              => 'Regression',
350         CorrespondAddress => 'rt-test@example.com',
351         CommentAddress    => 'rt-test@example.com',
352     );
353     ok $queue && $queue->id, 'changed props of the queue';
354
355     for my $type ( keys %mail ) {
356         for my $mail ( map cleanup_headers($_), @{ $mail{$type} } ) {
357             send_email_and_check_transaction( $mail, $type );
358         }
359     }
360 }