import of rt 3.0.9
[freeside.git] / rt / bin / rt-mailgate
1 #!/usr/bin/perl -w
2 # BEGIN LICENSE BLOCK
3
4 # Copyright (c) 1996-2003 Jesse Vincent <jesse@bestpractical.com>
5
6 # (Except where explictly superceded by other copyright notices)
7
8 # This work is made available to you under the terms of Version 2 of
9 # the GNU General Public License. A copy of that license should have
10 # been provided with this software, but in any event can be snarfed
11 # from www.gnu.org.
12
13 # This work is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17
18 # Unless otherwise specified, all modifications, corrections or
19 # extensions to this work which alter its source code become the
20 # property of Best Practical Solutions, LLC when submitted for
21 # inclusion in the work.
22
23
24 # END LICENSE BLOCK
25
26 =head1 NAME
27
28 rt-mailgate - Mail interface to RT3.
29
30 =begin testing
31
32 use RT::I18N;
33
34 # Make sure that when we call the mailgate wrong, it tempfails
35
36 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://bad.address"), "Opened the mailgate - The error below is expected - $@");
37 print MAIL <<EOF;
38 From: root\@localhost
39 To: rt\@example.com
40 Subject: This is a test of new ticket creation
41
42 Foob!
43 EOF
44 close (MAIL);
45
46 # Check the return value
47 is ( $? >> 8, 75, "The error message above is expected The mail gateway exited with a failure. yay");
48
49
50 # {{{ Test new ticket creation by root who is privileged and superuser
51
52 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
53 print MAIL <<EOF;
54 From: root\@localhost
55 To: rt\@example.com
56 Subject: This is a test of new ticket creation
57
58 Blah!
59 Foob!
60 EOF
61 close (MAIL);
62
63 #Check the return value
64 is ($? >> 8, 0, "The mail gateway exited normally. yay");
65
66 use RT::Tickets;
67 my $tickets = RT::Tickets->new($RT::SystemUser);
68 $tickets->OrderBy(FIELD => 'id', ORDER => 'DESC');
69 $tickets->Limit(FIELD => 'id', OPERATOR => '>', VALUE => '0');
70 my $tick = $tickets->First();
71 ok (UNIVERSAL::isa($tick,'RT::Ticket'));
72 ok ($tick->Id, "found ticket ".$tick->Id);
73 ok ($tick->Subject eq 'This is a test of new ticket creation', "Created the ticket");
74
75 # }}}
76
77
78 # {{{This is a test of new ticket creation as an unknown user
79
80 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
81 print MAIL <<EOF;
82 From: doesnotexist\@example.com
83 To: rt\@example.com
84 Subject: This is a test of new ticket creation as an unknown user
85
86 Blah!
87 Foob!
88 EOF
89 close (MAIL);
90 #Check the return value
91 is ($? >> 8, 0, "The mail gateway exited normally. yay");
92
93 $tickets = RT::Tickets->new($RT::SystemUser);
94 $tickets->OrderBy(FIELD => 'id', ORDER => 'DESC');
95 $tickets->Limit(FIELD => 'id' ,OPERATOR => '>', VALUE => '0');
96 $tick = $tickets->First();
97 ok ($tick->Id, "found ticket ".$tick->Id);
98 ok ($tick->Subject ne 'This is a test of new ticket creation as an unknown user', "failed to create the new ticket from an unprivileged account");
99 my $u = RT::User->new($RT::SystemUser);
100 $u->Load('doesnotexist@example.com');
101 ok( $u->Id == 0, " user does not exist and was not created by failed ticket submission");
102
103
104 # }}}
105
106 # {{{ now everybody can create tickets.  can a random unkown user create tickets?
107
108 my $g = RT::Group->new($RT::SystemUser);
109 $g->LoadSystemInternalGroup('Everyone');
110 ok( $g->Id, "Found 'everybody'");
111
112 my ($val,$msg) = $g->PrincipalObj->GrantRight(Right => 'CreateTicket');
113 ok ($val, "Granted everybody the right to create tickets - $msg");
114
115 sleep(60); # gotta sleep so the remote process' ACL cache times out
116
117 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
118 print MAIL <<EOF;
119 From: doesnotexist\@example.com
120 To: rt\@example.com
121 Subject: This is a test of new ticket creation as an unknown user
122
123 Blah!
124 Foob!
125 EOF
126 close (MAIL);
127 #Check the return value
128 is ($? >> 8, 0, "The mail gateway exited normally. yay");
129
130
131 $tickets = RT::Tickets->new($RT::SystemUser);
132 $tickets->OrderBy(FIELD => 'id', ORDER => 'DESC');
133 $tickets->Limit(FIELD => 'id' ,OPERATOR => '>', VALUE => '0');
134 $tick = $tickets->First();
135 ok ($tick->Id, "found ticket ".$tick->Id);
136 ok ($tick->Subject eq 'This is a test of new ticket creation as an unknown user', "failed to create the new ticket from an unprivileged account");
137 my $u = RT::User->new($RT::SystemUser);
138 $u->Load('doesnotexist@example.com');
139 ok( $u->Id != 0, " user does not exist and was created by ticket submission");
140
141 # }}}
142
143
144 # {{{  can another random reply to a ticket without being granted privs? answer should be no.
145
146
147 #($val,$msg) = $g->PrincipalObj->GrantRight(Right => 'CreateTicket');
148 #ok ($val, "Granted everybody the right to create tickets - $msg");
149 #sleep(60); # gotta sleep so the remote process' ACL cache times out
150
151 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
152 print MAIL <<EOF;
153 From: doesnotexist-2\@example.com
154 To: rt\@example.com
155 Subject: [example.com #@{[$tick->Id]}] This is a test of a reply as an unknown user
156
157 Blah!
158 Foob!
159 EOF
160 close (MAIL);
161 #Check the return value
162 is ($? >> 8, 0, "The mail gateway exited normally. yay");
163
164 $u = RT::User->new($RT::SystemUser);
165 $u->Load('doesnotexist-2@example.com');
166 ok( $u->Id == 0, " user does not exist and was not created by ticket correspondence submission");
167 # }}}
168 # {{{  can another random reply to a ticket after being granted privs? answer should be yes
169
170
171 ($val,$msg) = $g->PrincipalObj->GrantRight(Right => 'ReplyToTicket');
172 ok ($val, "Granted everybody the right to reply to  tickets - $msg");
173 sleep(60); # gotta sleep so the remote process' ACL cache times out
174
175 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
176 print MAIL <<EOF;
177 From: doesnotexist-2\@example.com
178 To: rt\@example.com
179 Subject: [example.com #@{[$tick->Id]}] This is a test of a reply as an unknown user
180
181 Blah!
182 Foob!
183 EOF
184 close (MAIL);
185 #Check the return value
186 is ($? >> 8, 0, "The mail gateway exited normally. yay");
187
188
189 $u = RT::User->new($RT::SystemUser);
190 $u->Load('doesnotexist-2@example.com');
191 ok( $u->Id != 0, " user exists and was created by ticket correspondence submission");
192
193 # }}}
194
195 # {{{  can another random comment on a ticket without being granted privs? answer should be no.
196
197
198 #($val,$msg) = $g->PrincipalObj->GrantRight(Right => 'CreateTicket');
199 #ok ($val, "Granted everybody the right to create tickets - $msg");
200 #sleep(60); # gotta sleep so the remote process' ACL cache times out
201
202 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action comment"), "Opened the mailgate - $@");
203 print MAIL <<EOF;
204 From: doesnotexist-3\@example.com
205 To: rt\@example.com
206 Subject: [example.com #@{[$tick->Id]}] This is a test of a comment as an unknown user
207
208 Blah!
209 Foob!
210 EOF
211 close (MAIL);
212
213 #Check the return value
214 is ($? >> 8, 0, "The mail gateway exited normally. yay");
215
216 $u = RT::User->new($RT::SystemUser);
217 $u->Load('doesnotexist-3@example.com');
218 ok( $u->Id == 0, " user does not exist and was not created by ticket comment submission");
219
220 # }}}
221 # {{{  can another random reply to a ticket after being granted privs? answer should be yes
222
223
224 ($val,$msg) = $g->PrincipalObj->GrantRight(Right => 'CommentOnTicket');
225 ok ($val, "Granted everybody the right to reply to  tickets - $msg");
226 sleep(60); # gotta sleep so the remote process' ACL cache times out
227
228 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action comment"), "Opened the mailgate - $@");
229 print MAIL <<EOF;
230 From: doesnotexist-3\@example.com
231 To: rt\@example.com
232 Subject: [example.com #@{[$tick->Id]}] This is a test of a comment as an unknown user
233
234 Blah!
235 Foob!
236 EOF
237 close (MAIL);
238
239 #Check the return value
240 is ($? >> 8, 0, "The mail gateway exited normally. yay");
241
242 $u = RT::User->new($RT::SystemUser);
243 $u->Load('doesnotexist-3@example.com');
244 ok( $u->Id != 0, " user exists and was created by ticket comment submission");
245
246 # }}}
247
248 # {{{ Testing preservation of binary attachments
249
250 # Get a binary blob (Best Practical logo) 
251
252 # Create a mime entity with an attachment
253
254 use MIME::Entity;
255 my $entity = MIME::Entity->build( From => 'root@localhost',
256                                  To => 'rt@localhost',
257                                 Subject => 'binary attachment test',
258                                 Data => ['This is a test of a binary attachment']);
259
260 # currently in lib/t/autogen
261 $entity->attach(Path => '/opt/rt3/share/html/NoAuth/images/spacer.gif', 
262                 Type => 'image/gif',
263                 Encoding => 'base64');
264
265 # Create a ticket with a binary attachment
266 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
267
268 $entity->print(\*MAIL);
269
270 close (MAIL);
271
272 #Check the return value
273 is ($? >> 8, 0, "The mail gateway exited normally. yay");
274
275 my $tickets = RT::Tickets->new($RT::SystemUser);
276 $tickets->OrderBy(FIELD => 'id', ORDER => 'DESC');
277 $tickets->Limit(FIELD => 'id', OPERATOR => '>', VALUE => '0');
278  $tick = $tickets->First();
279 ok (UNIVERSAL::isa($tick,'RT::Ticket'));
280 ok ($tick->Id, "found ticket ".$tick->Id);
281 ok ($tick->Subject eq 'binary attachment test', "Created the ticket - ".$tick->Id);
282
283 my $file = `cat ../../../html/NoAuth/images/spacer.gif`;
284 ok ($file, "Read in the logo image");
285
286
287         use Digest::MD5;
288 warn "for the raw file the content is ".Digest::MD5::md5_base64($file);
289
290
291
292 # Verify that the binary attachment is valid in the database
293 my $attachments = RT::Attachments->new($RT::SystemUser);
294 $attachments->Limit(FIELD => 'ContentType', VALUE => 'image/gif');
295 ok ($attachments->Count == 1, 'Found only one gif in the database');
296 my $attachment = $attachments->First;
297 my $acontent = $attachment->Content;
298
299         warn "coming from the  database, the content is ".Digest::MD5::md5_base64($acontent);
300
301 is( $acontent, $file, 'The attachment isn\'t screwed up in the database.');
302 # Log in as root
303 use Getopt::Long;
304 use LWP::UserAgent;
305
306
307 # Grab the binary attachment via the web ui
308 my $ua      = LWP::UserAgent->new();
309
310 my $full_url = "http://localhost".$RT::WebPath."/Ticket/Attachment/".$attachment->TransactionId."/".$attachment->id."/spacer.gif?&user=root&pass=password";
311 my $r = $ua->get( $full_url);
312
313
314 # Verify that the downloaded attachment is the same as what we uploaded.
315 is($file, $r->content, 'The attachment isn\'t screwed up in download');
316
317
318
319 # }}}
320
321 # {{{ Simple I18N testing
322
323 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
324                                                                          
325 print MAIL <<EOF;
326 From: root\@localhost
327 To: rtemail\@example.com
328 Subject: This is a test of I18N ticket creation
329 Content-Type: text/plain; charset="utf-8"
330
331 2 accented lines
332 \303\242\303\252\303\256\303\264\303\273
333 \303\241\303\251\303\255\303\263\303\272
334 bye
335 EOF
336 close (MAIL);
337
338 #Check the return value
339 is ($? >> 8, 0, "The mail gateway exited normally. yay");
340
341 my $unitickets = RT::Tickets->new($RT::SystemUser);
342 $unitickets->OrderBy(FIELD => 'id', ORDER => 'DESC');
343 $unitickets->Limit(FIELD => 'id', OPERATOR => '>', VALUE => '0');
344 my $unitick = $unitickets->First();
345 ok (UNIVERSAL::isa($unitick,'RT::Ticket'));
346 ok ($unitick->Id, "found ticket ".$unitick->Id);
347 ok ($unitick->Subject eq 'This is a test of I18N ticket creation', "Created the ticket - ". $unitick->Subject);
348
349
350
351 my $unistring = "\303\241\303\251\303\255\303\263\303\272";
352 Encode::_utf8_on($unistring);
353 is ($unitick->Transactions->First->Content, $unitick->Transactions->First->Attachments->First->Content, "Content is ". $unitick->Transactions->First->Attachments->First->Content);
354 ok($unitick->Transactions->First->Attachments->First->Content =~ /$unistring/i, $unitick->Id." appears to be unicode ". $unitick->Transactions->First->Attachments->First->Id);
355 # supposedly I18N fails on the second message sent in.
356
357 ok(open(MAIL, "|/opt/rt3/bin/rt-mailgate --url http://localhost".$RT::WebPath."/ --queue general --action correspond"), "Opened the mailgate - $@");
358                                                                          
359 print MAIL <<EOF;
360 From: root\@localhost
361 To: rtemail\@example.com
362 Subject: This is a test of I18N ticket creation
363 Content-Type: text/plain; charset="utf-8"
364
365 2 accented lines
366 \303\242\303\252\303\256\303\264\303\273
367 \303\241\303\251\303\255\303\263\303\272
368 bye
369 EOF
370 close (MAIL);
371
372 #Check the return value
373 is ($? >> 8, 0, "The mail gateway exited normally. yay");
374
375 my $tickets2 = RT::Tickets->new($RT::SystemUser);
376 $tickets2->OrderBy(FIELD => 'id', ORDER => 'DESC');
377 $tickets2->Limit(FIELD => 'id', OPERATOR => '>', VALUE => '0');
378 my $tick2 = $tickets2->First();
379 ok (UNIVERSAL::isa($tick2,'RT::Ticket'));
380 ok ($tick2->Id, "found ticket ".$tick2->Id);
381 ok ($tick2->Subject eq 'This is a test of I18N ticket creation', "Created the ticket");
382
383
384
385 my $unistring = "\303\241\303\251\303\255\303\263\303\272";
386 Encode::_utf8_on($unistring);
387
388 ok ($tick2->Transactions->First->Content =~ $unistring, "It appears to be unicode - ".$tick2->Transactions->First->Content);
389
390 # }}}
391
392
393 ($val,$msg) = $g->PrincipalObj->RevokeRight(Right => 'CreateTicket');
394 ok ($val, $msg);
395
396
397
398 =end testing
399
400 =cut
401
402
403 use strict;
404 use Getopt::Long;
405 use LWP::UserAgent;
406
407 use constant EX_TEMPFAIL => 75;
408
409 my %opts;
410 GetOptions( \%opts, "queue=s", "action=s", "url=s", "jar=s", "help", "debug", "extension=s", "timeout=i" );
411
412 if ( $opts{help} ) {
413     require Pod::Usage;
414     import Pod::Usage;
415     pod2usage("RT Mail Gateway\n");
416     exit 1;    # Don't want to succeed if this is really an email!
417 }
418
419 for (qw(url)) {
420     die "$0 invoked improperly\n\nNo $_ provided to mail gateway!\n" unless $opts{$_};
421 }
422
423 undef $/;
424 my $ua      = LWP::UserAgent->new();
425 $ua->cookie_jar( { file => $opts{jar} } );
426
427 my %args = (
428     queue   => $opts{queue},
429     action  => $opts{action},
430     SessionType => 'REST',    # Surpress login box
431 );
432
433 # Read the message in from STDIN
434 $args{'message'} = <>;
435
436
437 if ($opts{'extension'}) {
438         $args{$opts{'extension'}} = $ENV{'EXTENSION'};
439 }
440
441 # Set up cookie here.
442
443 my $full_url = $opts{'url'}. "/REST/1.0/NoAuth/mail-gateway";
444 warn "Connecting to $full_url" if $opts{'debug'};
445
446
447
448 $ua->timeout(exists($opts{'timeout'}) ? $opts{'timeout'} : 180);
449 my $r = $ua->post( $full_url, {%args} );
450 check_failure($r);
451
452 my $content = $r->content;
453 warn $content if ($opts{debug});
454
455 if ( $content !~ /^(ok|not ok)/ ) {
456
457     # It's not the server's fault if the mail is bogus. We just want to know that
458     # *something* came out of the server.
459     warn <<EOF;
460 RT server error.
461
462 The RT server which handled your email did not behave as expected. It
463 said:
464
465 $content
466 EOF
467
468 exit EX_TEMPFAIL;
469
470 }
471
472 exit;
473
474
475 sub check_failure {
476     my $r = shift;
477     return if $r->is_success();
478
479     # This ordinarily oughtn't to be able to happen, suggests a bug in RT.
480     # So only load these heavy modules when they're needed.
481     require HTML::TreeBuilder;
482     require HTML::FormatText;
483
484     my $error = $r->error_as_HTML;
485     my $tree  = HTML::TreeBuilder->new->parse($error);
486     $tree->eof;
487
488     # It'll be a cold day in hell before RT sends out bounces in HTML
489     my $formatter = HTML::FormatText->new( leftmargin  => 0,
490                                            rightmargin => 50 );
491     warn $formatter->format($tree);
492     warn "This is $0 exiting because of an undefined server error" if ($opts{debug});
493     exit EX_TEMPFAIL;
494 }
495
496
497 =head1 SYNOPSIS
498
499     rt-mailgate --help : this text
500
501 Usual invocation (from MTA):
502
503     rt-mailgate --action (correspond|comment) --queue queuename
504                 --url http://your.rt.server/
505                 [ --debug ]
506                 [ --extension (queue|action|ticket) ]
507                 [ --timeout seconds ]
508
509
510
511 See C<man rt-mailgate> for more.
512
513 =head1 OPTIONS
514
515 =over 3
516
517 =item C<--action>
518
519 Specifies whether this is a correspondence or comment address.
520
521 =item C<--queue>
522
523 Reflects which queue this address handles.
524
525 =item C<--url>
526
527 The location of the web server for your RT instance.
528
529
530 =item C<--extension> OPTIONAL
531
532 Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
533 and present "foo" in the environment variable $EXTENSION. By specifying
534 the value "queue" for this parameter, the queue this message should be
535 submitted to will be set to the value of $EXTENSION. By specifying
536 "ticket", $EXTENSION will be interpreted as the id of the ticket this message
537 is related to.  "action" will allow the user to specify either "comment" or
538 "correspond" in the address extension.
539
540 =item C<--debug> OPTIONAL
541
542 Print debugging output to standard error
543
544
545 =item C<--timeout> OPTIONAL
546
547 Configure the timeout for posting the message to the web server.  The
548 default timeout is 3 minutes (180 seconds).
549
550
551 =head1 DESCRIPTION
552
553 The RT mail gateway is the primary mechanism for communicating with RT
554 via email. This program simply directs the email to the RT web server,
555 which handles filing correspondence and sending out any required mail.
556 It is designed to be run as part of the mail delivery process, either
557 called directly by the MTA or C<procmail>, or in a F<.forward> or
558 equivalent.
559
560 =head1 SETUP
561
562 Much of the set up of the mail gateway depends on your MTA and mail
563 routing configuration. However, you will need first of all to create an
564 RT user for the mail gateway and assign it a password; this helps to
565 ensure that mail coming into the web server did originate from the
566 gateway.
567
568 Next, you need to route mail to C<rt-mailgate> for the queues you're
569 monitoring. For instance, if you're using F</etc/aliases> and you have a
570 "bugs" queue, you will want something like this:
571
572     bugs:         "|/opt/rt3/bin/rt-mailgate --queue bugs --action correspond
573               --url http://rt.mycorp.com/"
574
575     bugs-comment: "|/opt/rt3/bin/rt-mailgate --queue bugs --action comment
576               --url http://rt.mycorp.com/"
577
578 Note that you don't have to run your RT server on your mail server, as
579 the mail gateway will happily relay to a different machine.
580
581 =head1 CUSTOMIZATION
582
583 By default, the mail gateway will accept mail from anyone. However,
584 there are situations in which you will want to authenticate users
585 before allowing them to communicate with the system. You can do this
586 via a plug-in mechanism in the RT configuration.
587
588 You can set the array C<@RT::MailPlugins> to be a list of plugins. The
589 default plugin, if this is not given, is C<Auth::MailFrom> - that is,
590 authentication of the person is done based on the C<From> header of the
591 email. If you have additional filters or authentication mechanisms, you
592 can list them here and they will be called in order:
593
594     @RT::MailPlugins = (
595         "Filter::SpamAssassin",
596         "Auth::LDAP",
597         # ...
598     );
599
600 See the documentation for any additional plugins you have.
601
602 You may also put Perl subroutines into the C<@RT::MailPlugins> array, if
603 they behave as described below.
604
605 =head1 WRITING PLUGINS
606
607 What's actually going on in the above is that C<@RT::MailPlugins> is a
608 list of Perl modules; RT prepends C<RT::Interface::Email::> to the name,
609 to form a package name, and then C<use>'s this module. The module is
610 expected to provide a C<GetCurrentUser> subroutine, which takes a hash of
611 several parameters:
612
613 =over 4
614
615 =item Message
616
617 A C<MIME::Entity> object representing the email
618 =item CurrentUser
619
620 An C<RT::CurrentUser> object
621
622 =item AuthStat
623
624 The authentication level returned from the previous plugin.
625
626 =item Ticket [OPTIONAL]
627
628 The ticket under discussion
629
630 =item Queue [OPTIONAL]
631
632 If we don't already have a ticket id, we need to know which queue we're talking about
633
634 =item Action
635
636 The action being performed. At the moment, it's one of "comment" or "correspond"
637
638 =back 4
639
640 It returns two values, the new C<RT::CurrentUser> object, and the new
641 authentication level. The authentication level can be zero, not allowed
642 to communicate with RT at all, (a "permission denied" error is mailed to
643 the correspondent) or one, which is the normal mode of operation.
644 Additionally, if C<-1> is returned, then the processing of the plug-ins
645 stops immediately and the message is ignored.
646
647 =cut
648