mailpipe: add a warning message before loading a message from a stream.
[pygrader.git] / pygrader / mailpipe.py
1 # Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of pygrader.
4 #
5 # pygrader is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # pygrader is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # pygrader.  If not, see <http://www.gnu.org/licenses/>.
16
17 "Incoming email processing."
18
19 from __future__ import absolute_import
20
21 from email import message_from_file as _message_from_file
22 from email.header import decode_header as _decode_header
23 from email.mime.text import MIMEText as _MIMEText
24 import mailbox as _mailbox
25 import re as _re
26 import sys as _sys
27
28 import pgp_mime as _pgp_mime
29 from lxml import etree as _etree
30
31 from . import LOG as _LOG
32 from .email import construct_email as _construct_email
33 from .email import construct_response as _construct_response
34 from .model.person import Person as _Person
35
36 from .handler import InvalidMessage as _InvalidMessage
37 from .handler import InvalidSubjectMessage as _InvalidSubjectMessage
38 from .handler import Response as _Response
39 from .handler import UnsignedMessage as _UnsignedMessage
40 from .handler.get import InvalidStudent as _InvalidStudent
41 from .handler.get import run as _handle_get
42 from .handler.submission import InvalidAssignment as _InvalidAssignment
43 from .handler.submission import run as _handle_submission
44
45
46 _TAG_REGEXP = _re.compile('^.*\[([^]]*)\].*$')
47
48
49 class NoReturnPath (_InvalidMessage):
50     def __init__(self, address, **kwargs):
51         if 'error' not in kwargs:
52             kwargs['error'] = 'no Return-Path'
53         super(NoReturnPath, self).__init__(**kwargs)
54
55
56 class UnregisteredAddress (_InvalidMessage):
57     def __init__(self, address, **kwargs):
58         if 'error' not in kwargs:
59             kwargs['error'] = 'unregistered address {}'.format(address)
60         super(UnregisteredAddress, self).__init__(**kwargs)
61         self.address = address
62
63
64 class AmbiguousAddress (_InvalidMessage):
65     def __init__(self, address, people, **kwargs):
66         if 'error' not in kwargs:
67             kwargs['error'] = 'ambiguous address {}'.format(address)
68         super(AmbiguousAddress, self).__init__(**kwargs)
69         self.address = address
70         self.people = people
71
72
73 class SubjectlessMessage (_InvalidSubjectMessage):
74     def __init__(self, **kwargs):
75         if 'error' not in kwargs:
76             kwargs['error'] = 'no subject'
77         super(SubjectlessMessage, self).__init__(**kwargs)
78
79
80 class InvalidHandlerMessage (_InvalidSubjectMessage):
81     def __init__(self, target=None, handlers=None, **kwargs):
82         if 'error' not in kwargs:
83             kwargs['error'] = 'no handler for {!r}'.format(target)
84         super(InvalidHandlerMessage, self).__init__(**kwargs)
85         self.target = target
86         self.handlers = handlers
87
88
89 def mailpipe(basedir, course, stream=None, mailbox=None, input_=None,
90              output=None, continue_after_invalid_message=False, max_late=0,
91              handlers={
92         'get': _handle_get,
93         'submit': _handle_submission,
94         }, respond=None, dry_run=False, **kwargs):
95     """Run from procmail to sort incomming submissions
96
97     For example, you can setup your ``.procmailrc`` like this::
98
99       SHELL=/bin/sh
100       DEFAULT=$MAIL
101       MAILDIR=$HOME/mail
102       DEFAULT=$MAILDIR/mbox
103       LOGFILE=$MAILDIR/procmail.log
104       #VERBOSE=yes
105       PYGRADE_MAILPIPE="pg.py -d $HOME/grades/phys160"
106
107       # Grab all incoming homeworks emails.  This rule eats matching emails
108       # (i.e. no further procmail processing).
109       :0
110       * ^Subject:.*\[phys160:submit]
111       | "$PYGRADE_MAILPIPE" mailpipe
112
113     If you don't want procmail to eat the message, you can use the
114     ``c`` flag (carbon copy) by starting your rule off with ``:0 c``.
115
116     >>> from io import StringIO
117     >>> from pgp_mime.email import encodedMIMEText
118     >>> from .handler import InvalidMessage, Response
119     >>> from .test.course import StubCourse
120
121     >>> course = StubCourse()
122     >>> def respond(message):
123     ...     print('respond with:\\n{}'.format(message.as_string()))
124     >>> def process(message):
125     ...     mailpipe(
126     ...         basedir=course.basedir, course=course.course,
127     ...         stream=StringIO(message.as_string()),
128     ...         output=course.mailbox,
129     ...         continue_after_invalid_message=True,
130     ...         respond=respond)
131     >>> message = encodedMIMEText('The answer is 42.')
132     >>> message['Message-ID'] = '<123.456@home.net>'
133     >>> message['Received'] = (
134     ...     'from smtp.home.net (smtp.home.net [123.456.123.456]) '
135     ...     'by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF '
136     ...     'for <wking@tremily.us>; Sun, 09 Oct 2011 11:50:46 -0400 (EDT)')
137     >>> message['From'] = 'Billy B <bb@greyhavens.net>'
138     >>> message['To'] = 'phys101 <phys101@tower.edu>'
139     >>> message['Subject'] = '[submit] assignment 1'
140
141     Messages with unrecognized ``Return-Path``\s are silently dropped:
142
143     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
144     >>> course.print_tree()  # doctest: +REPORT_UDIFF, +ELLIPSIS
145     course.conf
146     mail
147     mail/cur
148     mail/new
149     mail/tmp
150
151     Response to a message from an unregistered person:
152
153     >>> message['Return-Path'] = '<invalid.return.path@home.net>'
154     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
155     respond with:
156     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
157     MIME-Version: 1.0
158     Content-Disposition: inline
159     Date: ...
160     From: Robot101 <phys101@tower.edu>
161     Reply-to: Robot101 <phys101@tower.edu>
162     To: "invalid.return.path@home.net" <invalid.return.path@home.net>
163     Subject: unregistered address invalid.return.path@home.net
164     <BLANKLINE>
165     --===============...==
166     Content-Type: multipart/mixed; boundary="===============...=="
167     MIME-Version: 1.0
168     <BLANKLINE>
169     --===============...==
170     Content-Type: text/plain; charset="us-ascii"
171     MIME-Version: 1.0
172     Content-Transfer-Encoding: 7bit
173     Content-Disposition: inline
174     <BLANKLINE>
175     invalid.return.path@home.net,
176     <BLANKLINE>
177     Your email address is not registered with pygrader for
178     Physics 101.  If you feel it should be, contact your professor
179     or TA.
180     <BLANKLINE>
181     Yours,
182     phys-101 robot
183     <BLANKLINE>
184     --===============...==
185     Content-Type: message/rfc822
186     MIME-Version: 1.0
187     <BLANKLINE>
188     Content-Type: text/plain; charset="us-ascii"
189     MIME-Version: 1.0
190     Content-Transfer-Encoding: 7bit
191     Content-Disposition: inline
192     Message-ID: <123.456@home.net>
193     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Sun, 09 Oct 2011 11:50:46 -0400 (EDT)
194     From: Billy B <bb@greyhavens.net>
195     To: phys101 <phys101@tower.edu>
196     Subject: [submit] assignment 1
197     Return-Path: <invalid.return.path@home.net>
198     <BLANKLINE>
199     The answer is 42.
200     --===============...==--
201     --===============...==
202     MIME-Version: 1.0
203     Content-Transfer-Encoding: 7bit
204     Content-Description: OpenPGP digital signature
205     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
206     <BLANKLINE>
207     -----BEGIN PGP SIGNATURE-----
208     Version: GnuPG v2.0.19 (GNU/Linux)
209     <BLANKLINE>
210     ...
211     -----END PGP SIGNATURE-----
212     <BLANKLINE>
213     --===============...==--
214
215     If we add a valid ``Return-Path``, we get the expected delivery:
216
217     >>> del message['Return-Path']
218     >>> message['Return-Path'] = '<bb@greyhavens.net>'
219     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
220     respond with:
221     Content-Type: text/plain; charset="us-ascii"
222     MIME-Version: 1.0
223     Content-Disposition: inline
224     Content-Transfer-Encoding: 7bit
225     <BLANKLINE>
226     Billy,
227     <BLANKLINE>
228     We received your submission for Assignment 1 on Sun, 09 Oct 2011 15:50:46 -0000.
229     <BLANKLINE>
230     Yours,
231     phys-101 robot
232     <BLANKLINE>
233
234     >>> course.print_tree()  # doctest: +REPORT_UDIFF, +ELLIPSIS
235     Bilbo_Baggins
236     Bilbo_Baggins/Assignment_1
237     Bilbo_Baggins/Assignment_1/mail
238     Bilbo_Baggins/Assignment_1/mail/cur
239     Bilbo_Baggins/Assignment_1/mail/new
240     Bilbo_Baggins/Assignment_1/mail/new/...:2,S
241     Bilbo_Baggins/Assignment_1/mail/tmp
242     course.conf
243     mail
244     mail/cur
245     mail/new
246     mail/new/...
247     mail/tmp
248
249     The last ``Received`` is used to timestamp the message:
250
251     >>> del message['Message-ID']
252     >>> message['Message-ID'] = '<abc.def@home.net>'
253     >>> del message['Received']
254     >>> message['Received'] = (
255     ...     'from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) '
256     ...     'by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 '
257     ...     'for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)')
258     >>> message['Received'] = (
259     ...     'from smtp.home.net (smtp.home.net [123.456.123.456]) '
260     ...     'by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF '
261     ...     'for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)')
262     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
263     respond with:
264     Content-Type: text/plain; charset="us-ascii"
265     MIME-Version: 1.0
266     Content-Disposition: inline
267     Content-Transfer-Encoding: 7bit
268     <BLANKLINE>
269     Billy,
270     <BLANKLINE>
271     We received your submission for Assignment 1 on Mon, 10 Oct 2011 16:50:46 -0000.
272     <BLANKLINE>
273     Yours,
274     phys-101 robot
275     <BLANKLINE>
276     >>> course.print_tree()  # doctest: +REPORT_UDIFF, +ELLIPSIS
277     Bilbo_Baggins
278     Bilbo_Baggins/Assignment_1
279     Bilbo_Baggins/Assignment_1/late
280     Bilbo_Baggins/Assignment_1/mail
281     Bilbo_Baggins/Assignment_1/mail/cur
282     Bilbo_Baggins/Assignment_1/mail/new
283     Bilbo_Baggins/Assignment_1/mail/new/...:2,S
284     Bilbo_Baggins/Assignment_1/mail/new/...:2,S
285     Bilbo_Baggins/Assignment_1/mail/tmp
286     course.conf
287     mail
288     mail/cur
289     mail/new
290     mail/new/...
291     mail/new/...
292     mail/tmp
293
294     You can send receipts to the acknowledge incoming messages, which
295     includes warnings about dropped messages (except for messages
296     without ``Return-Path`` and messages where the ``Return-Path``
297     email belongs to multiple ``People``.  The former should only
298     occur with malicious emails, and the latter with improper pygrader
299     configurations).
300
301     Response to a successful submission:
302
303     >>> del message['Message-ID']
304     >>> message['Message-ID'] = '<hgi.jlk@home.net>'
305     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
306     respond with:
307     Content-Type: text/plain; charset="us-ascii"
308     MIME-Version: 1.0
309     Content-Disposition: inline
310     Content-Transfer-Encoding: 7bit
311     <BLANKLINE>
312     Billy,
313     <BLANKLINE>
314     We received your submission for Assignment 1 on Mon, 10 Oct 2011 16:50:46 -0000.
315     <BLANKLINE>
316     Yours,
317     phys-101 robot
318     <BLANKLINE>
319
320     Response to a submission on an unsubmittable assignment:
321
322     >>> del message['Subject']
323     >>> message['Subject'] = '[submit] attendance 1'
324     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
325     respond with:
326     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
327     MIME-Version: 1.0
328     Content-Disposition: inline
329     Date: ...
330     From: Robot101 <phys101@tower.edu>
331     Reply-to: Robot101 <phys101@tower.edu>
332     To: Bilbo Baggins <bb@shire.org>
333     Subject: Received invalid Attendance 1 submission
334     <BLANKLINE>
335     --===============...==
336     Content-Type: multipart/mixed; boundary="===============...=="
337     MIME-Version: 1.0
338     <BLANKLINE>
339     --===============...==
340     Content-Type: text/plain; charset="us-ascii"
341     MIME-Version: 1.0
342     Content-Transfer-Encoding: 7bit
343     Content-Disposition: inline
344     <BLANKLINE>
345     Billy,
346     <BLANKLINE>
347     We received your submission for Attendance 1, but you are not
348     allowed to submit that assignment via email.
349     <BLANKLINE>
350     Yours,
351     phys-101 robot
352     <BLANKLINE>
353     --===============...==
354     Content-Type: message/rfc822
355     MIME-Version: 1.0
356     <BLANKLINE>
357     Content-Type: text/plain; charset="us-ascii"
358     MIME-Version: 1.0
359     Content-Transfer-Encoding: 7bit
360     Content-Disposition: inline
361     From: Billy B <bb@greyhavens.net>
362     To: phys101 <phys101@tower.edu>
363     Return-Path: <bb@greyhavens.net>
364     Received: from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)
365     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)
366     Message-ID: <hgi.jlk@home.net>
367     Subject: [submit] attendance 1
368     <BLANKLINE>
369     The answer is 42.
370     --===============...==--
371     --===============...==
372     MIME-Version: 1.0
373     Content-Transfer-Encoding: 7bit
374     Content-Description: OpenPGP digital signature
375     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
376     <BLANKLINE>
377     -----BEGIN PGP SIGNATURE-----
378     Version: GnuPG v2.0.19 (GNU/Linux)
379     <BLANKLINE>
380     ...
381     -----END PGP SIGNATURE-----
382     <BLANKLINE>
383     --===============...==--
384
385     Response to a bad subject:
386
387     >>> del message['Subject']
388     >>> message['Subject'] = 'need help for the first homework'
389     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
390     respond with:
391     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
392     MIME-Version: 1.0
393     Content-Disposition: inline
394     Date: ...
395     From: Robot101 <phys101@tower.edu>
396     Reply-to: Robot101 <phys101@tower.edu>
397     To: Bilbo Baggins <bb@shire.org>
398     Subject: no tag in 'need help for the first homework'
399     <BLANKLINE>
400     --===============...==
401     Content-Type: multipart/mixed; boundary="===============...=="
402     MIME-Version: 1.0
403     <BLANKLINE>
404     --===============...==
405     Content-Type: text/plain; charset="us-ascii"
406     MIME-Version: 1.0
407     Content-Transfer-Encoding: 7bit
408     Content-Disposition: inline
409     <BLANKLINE>
410     Billy,
411     <BLANKLINE>
412     We received an email message from you with an invalid
413     subject.
414     <BLANKLINE>
415     Yours,
416     phys-101 robot
417     <BLANKLINE>
418     --===============...==
419     Content-Type: message/rfc822
420     MIME-Version: 1.0
421     <BLANKLINE>
422     Content-Type: text/plain; charset="us-ascii"
423     MIME-Version: 1.0
424     Content-Transfer-Encoding: 7bit
425     Content-Disposition: inline
426     From: Billy B <bb@greyhavens.net>
427     To: phys101 <phys101@tower.edu>
428     Return-Path: <bb@greyhavens.net>
429     Received: from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)
430     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)
431     Message-ID: <hgi.jlk@home.net>
432     Subject: need help for the first homework
433     <BLANKLINE>
434     The answer is 42.
435     --===============...==--
436     --===============...==
437     MIME-Version: 1.0
438     Content-Transfer-Encoding: 7bit
439     Content-Description: OpenPGP digital signature
440     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
441     <BLANKLINE>
442     -----BEGIN PGP SIGNATURE-----
443     Version: GnuPG v2.0.19 (GNU/Linux)
444     <BLANKLINE>
445     ...
446     -----END PGP SIGNATURE-----
447     <BLANKLINE>
448     --===============...==--
449
450     Response to a missing subject:
451
452     >>> del message['Subject']
453     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
454     respond with:
455     Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
456     MIME-Version: 1.0
457     Content-Disposition: inline
458     Date: ...
459     From: Robot101 <phys101@tower.edu>
460     Reply-to: Robot101 <phys101@tower.edu>
461     To: Bilbo Baggins <bb@shire.org>
462     Subject: no subject in <hgi.jlk@home.net>
463     <BLANKLINE>
464     --===============...==
465     Content-Type: multipart/mixed; boundary="===============...=="
466     MIME-Version: 1.0
467     <BLANKLINE>
468     --===============...==
469     Content-Type: text/plain; charset="us-ascii"
470     MIME-Version: 1.0
471     Content-Transfer-Encoding: 7bit
472     Content-Disposition: inline
473     <BLANKLINE>
474     Billy,
475     <BLANKLINE>
476     We received an email message from you without a subject.
477     <BLANKLINE>
478     Yours,
479     phys-101 robot
480     <BLANKLINE>
481     --===============...==
482     Content-Type: message/rfc822
483     MIME-Version: 1.0
484     <BLANKLINE>
485     Content-Type: text/plain; charset="us-ascii"
486     MIME-Version: 1.0
487     Content-Transfer-Encoding: 7bit
488     Content-Disposition: inline
489     From: Billy B <bb@greyhavens.net>
490     To: phys101 <phys101@tower.edu>
491     Return-Path: <bb@greyhavens.net>
492     Received: from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)
493     Received: from smtp.home.net (smtp.home.net [123.456.123.456]) by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)
494     Message-ID: <hgi.jlk@home.net>
495     <BLANKLINE>
496     The answer is 42.
497     --===============...==--
498     --===============...==
499     MIME-Version: 1.0
500     Content-Transfer-Encoding: 7bit
501     Content-Description: OpenPGP digital signature
502     Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
503     <BLANKLINE>
504     -----BEGIN PGP SIGNATURE-----
505     Version: GnuPG v2.0.19 (GNU/Linux)
506     <BLANKLINE>
507     ...
508     -----END PGP SIGNATURE-----
509     <BLANKLINE>
510     --===============...==--
511
512     Response to an insecure message from a person with a PGP key:
513
514     >>> student = course.course.person(email='bb@greyhavens.net')
515     >>> student.pgp_key = '4332B6E3'
516     >>> del message['Subject']
517     >>> process(message)  # doctest: +REPORT_UDIFF, +ELLIPSIS
518     respond with:
519     Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; micalg="pgp-sha1"; boundary="===============...=="
520     MIME-Version: 1.0
521     Content-Disposition: inline
522     Date: ...
523     From: Robot101 <phys101@tower.edu>
524     Reply-to: Robot101 <phys101@tower.edu>
525     To: Bilbo Baggins <bb@shire.org>
526     Subject: unsigned message <hgi.jlk@home.net>
527     <BLANKLINE>
528     --===============...==
529     MIME-Version: 1.0
530     Content-Transfer-Encoding: 7bit
531     Content-Type: application/pgp-encrypted; charset="us-ascii"
532     <BLANKLINE>
533     Version: 1
534     <BLANKLINE>
535     --===============...==
536     MIME-Version: 1.0
537     Content-Transfer-Encoding: 7bit
538     Content-Description: OpenPGP encrypted message
539     Content-Type: application/octet-stream; name="encrypted.asc"; charset="us-ascii"
540     <BLANKLINE>
541     -----BEGIN PGP MESSAGE-----
542     Version: GnuPG v2.0.19 (GNU/Linux)
543     <BLANKLINE>
544     ...
545     -----END PGP MESSAGE-----
546     <BLANKLINE>
547     --===============...==--
548
549     >>> course.cleanup()
550     """
551     if stream is None:
552         stream = _sys.stdin
553     for original,message,person,subject,target in _load_messages(
554         course=course, stream=stream, mailbox=mailbox, input_=input_,
555         output=output, dry_run=dry_run,
556         continue_after_invalid_message=continue_after_invalid_message,
557         respond=respond):
558         try:
559             handler = _get_handler(handlers=handlers, target=target)
560             handler(
561                 basedir=basedir, course=course, message=message,
562                 person=person, subject=subject,
563                 max_late=max_late, dry_run=dry_run)
564         except _InvalidMessage as error:
565             error.course = course
566             error.message = original
567             if person is not None and not hasattr(error, 'person'):
568                 error.person = person
569             if subject is not None and not hasattr(error, 'subject'):
570                 error.subject = subject
571             if target is not None and not hasattr(error, 'target'):
572                 error.target = target
573             _LOG.warn('invalid message {}'.format(error.message_id()))
574             if not continue_after_invalid_message:
575                 raise
576             if respond:
577                 response = _get_error_response(error)
578                 respond(response)
579         except _Response as response:
580             if respond:
581                 author = course.robot
582                 target = person
583                 msg = response.message
584                 if isinstance(response.message, _MIMEText):
585                     # Manipulate body (based on pgp_mime.append_text)
586                     original_encoding = msg.get_charset().input_charset
587                     original_payload = str(
588                         msg.get_payload(decode=True), original_encoding)
589                     new_payload = (
590                         '{},\n\n'
591                         '{}\n\n'
592                         'Yours,\n'
593                         '{}\n').format(
594                         target.alias(), original_payload, author.alias())
595                     new_encoding = _pgp_mime.guess_encoding(new_payload)
596                     if msg.get('content-transfer-encoding', None):
597                         # clear CTE so set_payload will set it properly
598                         del msg['content-transfer-encoding']
599                     msg.set_payload(new_payload, new_encoding)
600                 subject = msg['Subject']
601                 del msg['Subject']
602                 assert subject is not None, msg
603                 msg = _construct_email(
604                     author=author, targets=[person], subject=subject,
605                     message=msg)
606                 respond(response.message)
607
608
609 def _load_messages(course, stream, mailbox=None, input_=None, output=None,
610                    continue_after_invalid_message=False, respond=None,
611                    dry_run=False):
612     if mailbox is None:
613         _LOG.debug('loading message from {}'.format(stream))
614         mbox = None
615         messages = [(None,_message_from_file(stream))]
616         if output is not None:
617             ombox = _mailbox.Maildir(output, factory=None, create=True)
618     elif mailbox == 'mbox':
619         mbox = _mailbox.mbox(input_, factory=None, create=False)
620         messages = mbox.items()
621         if output is not None:
622             ombox = _mailbox.mbox(output, factory=None, create=True)
623     elif mailbox == 'maildir':
624         mbox = _mailbox.Maildir(input_, factory=None, create=False)
625         messages = []
626         for key,msg in mbox.items():
627             subpath = mbox._lookup(key)
628             if subpath.endswith('.gitignore'):
629                 _LOG.debug('skipping non-message {}'.format(subpath))
630                 continue
631             messages.append((key, msg))
632         if output is not None:
633             ombox = _mailbox.Maildir(output, factory=None, create=True)
634     else:
635         raise ValueError(mailbox)
636     for key,msg in messages:
637         try:
638             ret = _parse_message(course=course, message=msg)
639         except _InvalidMessage as error:
640             error.message = msg
641             _LOG.warn('invalid message {}'.format(error.message_id()))
642             if not continue_after_invalid_message:
643                 raise
644             if respond:
645                 response = _get_error_response(error)
646                 if response is not None:
647                     respond(response)
648             continue
649         if output is not None and dry_run is False:
650             # move message from input mailbox to output mailbox
651             ombox.add(msg)
652             if mbox is not None:
653                 del mbox[key]
654         yield ret
655
656 def _parse_message(course, message):
657     """Parse an incoming email and respond if neccessary.
658
659     Return ``(msg, person, assignment, time)`` on successful parsing.
660     Return ``None`` on failure.
661     """
662     original = message
663     person = subject = target = None
664     try:
665         person = _get_message_person(course=course, message=message)
666         if person.pgp_key:
667             message = _get_decoded_message(
668                 course=course, message=message, person=person)
669         subject = _get_message_subject(message=message)
670         target = _get_message_target(subject=subject)
671     except _InvalidMessage as error:
672         error.course = course
673         error.message = original
674         if person is not None and not hasattr(error, 'person'):
675             error.person = person
676         if subject is not None and not hasattr(error, 'subject'):
677             error.subject = subject
678         if target is not None and not hasattr(error, 'target'):
679             error.target = target
680         raise
681     return (original, message, person, subject, target)
682
683 def _get_message_person(course, message):
684     sender = message['Return-Path']  # RFC 822
685     if sender is None:
686         raise NoReturnPath(message)
687     sender = sender[1:-1]  # strip wrapping '<' and '>'
688     people = list(course.find_people(email=sender))
689     if len(people) == 0:
690         raise UnregisteredAddress(message=message, address=sender)
691     if len(people) > 1:
692         raise AmbiguousAddress(message=message, address=sender, people=people)
693     return people[0]
694
695 def _get_decoded_message(course, message, person):
696     msg = _get_verified_message(message, person.pgp_key)
697     if msg is None:
698         raise _UnsignedMessage(message=message)
699     return msg
700
701 def _get_message_subject(message):
702     """
703     >>> from email.header import Header
704     >>> from pgp_mime.email import encodedMIMEText
705     >>> message = encodedMIMEText('The answer is 42.')
706     >>> message['Message-ID'] = 'msg-id'
707     >>> _get_message_subject(message=message)
708     Traceback (most recent call last):
709       ...
710     pygrader.mailpipe.SubjectlessMessage: no subject
711     >>> del message['Subject']
712     >>> subject = Header('unicode part', 'utf-8')
713     >>> subject.append('-ascii part', 'ascii')
714     >>> message['Subject'] = subject.encode()
715     >>> _get_message_subject(message=message)
716     'unicode part-ascii part'
717     >>> del message['Subject']
718     >>> message['Subject'] = 'clean subject'
719     >>> _get_message_subject(message=message)
720     'clean subject'
721     """
722     if message['Subject'] is None:
723         raise SubjectlessMessage(subject=None, message=message)
724
725     parts = _decode_header(message['Subject'])
726     part_strings = []
727     for string,encoding in parts:
728         if encoding is None:
729             encoding = 'ascii'
730         if not isinstance(string, str):
731             string = str(string, encoding)
732         part_strings.append(string)
733     subject = ''.join(part_strings)
734     _LOG.debug('decoded header {} -> {}'.format(parts[0], subject))
735     return subject.lower().replace('#', '')
736
737 def _get_message_target(subject):
738     """
739     >>> _get_message_target(subject='no tag')
740     Traceback (most recent call last):
741       ...
742     pygrader.handler.InvalidSubjectMessage: no tag in 'no tag'
743     >>> _get_message_target(subject='[] empty tag')
744     Traceback (most recent call last):
745       ...
746     pygrader.handler.InvalidSubjectMessage: empty tag in '[] empty tag'
747     >>> _get_message_target(subject='[abc] empty tag')
748     'abc'
749     >>> _get_message_target(subject='[phys160:abc] empty tag')
750     'abc'
751     """
752     match = _TAG_REGEXP.match(subject)
753     if match is None:
754         raise _InvalidSubjectMessage(
755             subject=subject, error='no tag in {!r}'.format(subject))
756     tag = match.group(1)
757     if tag == '':
758         raise _InvalidSubjectMessage(
759             subject=subject, error='empty tag in {!r}'.format(subject))
760     target = tag.rsplit(':', 1)[-1]
761     _LOG.debug('extracted target {} -> {}'.format(subject, target))
762     return target
763
764 def _get_handler(handlers, target):
765     try:
766         handler = handlers[target]
767     except KeyError as error:
768         raise InvalidHandlerMessage(
769             target=target, handlers=handlers) from error
770     return handler
771
772 def _get_verified_message(message, pgp_key):
773     """
774
775     >>> from pgp_mime import sign, encodedMIMEText
776
777     The student composes a message...
778
779     >>> message = encodedMIMEText('1.23 joules')
780
781     ... and signs it (with the pgp-mime test key).
782
783     >>> signed = sign(message, signers=['pgp-mime-test'])
784
785     As it is being delivered, the message picks up extra headers.
786
787     >>> signed['Message-ID'] = '<01234567@home.net>'
788     >>> signed['Received'] = 'from smtp.mail.uu.edu ...'
789     >>> signed['Received'] = 'from smtp.home.net ...'
790
791     We check that the message is signed, and that it is signed by the
792     appropriate key.
793
794     >>> signed.authenticated
795     Traceback (most recent call last):
796       ...
797     AttributeError: 'MIMEMultipart' object has no attribute 'authenticated'
798     >>> our_message = _get_verified_message(signed, pgp_key='4332B6E3')
799     >>> print(our_message.as_string())  # doctest: +REPORT_UDIFF
800     Content-Type: text/plain; charset="us-ascii"
801     MIME-Version: 1.0
802     Content-Transfer-Encoding: 7bit
803     Content-Disposition: inline
804     Message-ID: <01234567@home.net>
805     Received: from smtp.mail.uu.edu ...
806     Received: from smtp.home.net ...
807     <BLANKLINE>
808     1.23 joules
809     >>> our_message.authenticated
810     True
811
812     If it is signed, but not by the right key, we get ``None``.
813
814     >>> print(_get_verified_message(signed, pgp_key='01234567'))
815     None
816
817     If it is not signed at all, we get ``None``.
818
819     >>> print(_get_verified_message(message, pgp_key='4332B6E3'))
820     None
821     """
822     mid = message['message-id']
823     try:
824         decrypted,verified,result = _pgp_mime.verify(message=message)
825     except (ValueError, AssertionError):
826         _LOG.warning('could not verify {} (not signed?)'.format(mid))
827         return None
828     _LOG.debug(str(result, 'utf-8'))
829     tree = _etree.fromstring(result.replace(b'\x00', b''))
830     match = None
831     for signature in tree.findall('.//signature'):
832         for fingerprint in signature.iterchildren('fpr'):
833             if fingerprint.text.endswith(pgp_key):
834                 match = signature
835                 break
836     if match is None:
837         _LOG.warning('{} is not signed by the expected key'.format(mid))
838         return None
839     if not verified:
840         sumhex = list(signature.iterchildren('summary'))[0].get('value')
841         summary = int(sumhex, 16)
842         if summary != 0:
843             _LOG.warning('{} has an unverified signature'.format(mid))
844             return None
845         # otherwise, we may have an untrusted key.  We'll count that
846         # as verified here, because the caller is explicity looking
847         # for signatures by this fingerprint.
848     for k,v in message.items(): # copy over useful headers
849         if k.lower() not in ['content-type',
850                              'mime-version',
851                              'content-disposition',
852                              ]:
853             decrypted[k] = v
854     decrypted.authenticated = True
855     return decrypted
856
857 def _get_error_response(error):
858     author = error.course.robot
859     target = getattr(error, 'person', None)
860     subject = str(error)
861     if isinstance(error, InvalidHandlerMessage):
862         targets = sorted(error.handlers.keys())
863         if not targets:
864             hint = (
865                 'In fact, there are no available handlers for this\n'
866                 'course!')
867         else:
868             hint = (
869                 'Perhaps you meant to use one of the following:\n'
870                 '  {}').format('\n  '.join(targets))
871         text = (
872             'We got an email from you with the following subject:\n'
873             '  {!r}\n'
874             'which does not match any submittable handler name for\n'
875             '{}.\n'
876             '{}').format(repr(error.subject), error.course.name, hint)
877     elif isinstance(error, SubjectlessMessage):
878         subject = 'no subject in {}'.format(error.message['Message-ID'])
879         text = 'We received an email message from you without a subject.'
880     elif isinstance(error, AmbiguousAddress):
881         text = (
882             'Multiple people match {} ({})'.format(
883                 error.address, ', '.join(p.name for p in error.people)))
884     elif isinstance(error, UnregisteredAddress):
885         target = _Person(name=error.address, emails=[error.address])
886         text = (
887             'Your email address is not registered with pygrader for\n'
888             '{}.  If you feel it should be, contact your professor\n'
889             'or TA.').format(error.course.name)
890     elif isinstance(error, NoReturnPath):
891         return
892     elif isinstance(error, _InvalidSubjectMessage):
893         text = (
894             'We received an email message from you with an invalid\n'
895             'subject.')
896     elif isinstance(error, _UnsignedMessage):
897         subject = 'unsigned message {}'.format(error.message['Message-ID'])
898         text = (
899             'We received an email message from you without a valid\n'
900             'PGP signature.')
901     elif isinstance(error, _InvalidAssignment):
902         text = (
903             'We received your submission for {}, but you are not\n'
904             'allowed to submit that assignment via email.'
905             ).format(error.assignment.name)
906     elif isinstance(error, _InvalidStudent):
907         text = (
908             'We got an email from you with the following subject:\n'
909             '  {!r}\n'
910             'but it matches several students:\n'
911             '  * {}').format(
912             error.subject, '\n  * '.join(s.name for s in error.students))
913     elif isinstance(error, _InvalidMessage):
914         text = subject
915     else:
916         raise NotImplementedError((type(error), error))
917     if target is None:
918         raise NotImplementedError((type(error), error))
919     return _construct_response(
920         author=author,
921         targets=[target],
922         subject=subject,
923         text=(
924             '{},\n\n'
925             '{}\n\n'
926             'Yours,\n'
927             '{}\n'.format(target.alias(), text, author.alias())),
928         original=error.message)