1 # Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
3 # This file is part of pygrader.
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
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.
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/>.
17 "Incoming email processing."
19 from __future__ import absolute_import
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
28 import pgp_mime as _pgp_mime
29 from lxml import etree as _etree
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
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
46 _TAG_REGEXP = _re.compile('^.*\[([^]]*)\].*$')
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)
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
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
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)
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(
84 kwargs.get('target', None))
85 super(InvalidHandlerMessage, self).__init__(**kwargs)
87 self.handlers = handlers
90 def mailpipe(basedir, course, stream=None, mailbox=None, input_=None,
91 output=None, continue_after_invalid_message=False, max_late=0,
94 'submit': _handle_submission,
95 }, respond=None, dry_run=False, **kwargs):
96 """Run from procmail to sort incomming submissions
98 For example, you can setup your ``.procmailrc`` like this::
103 DEFAULT=$MAILDIR/mbox
104 LOGFILE=$MAILDIR/procmail.log
106 PYGRADE_MAILPIPE="pg.py -d $HOME/grades/phys160"
108 # Grab all incoming homeworks emails. This rule eats matching emails
109 # (i.e. no further procmail processing).
111 * ^Subject:.*\[phys160:submit]
112 | "$PYGRADE_MAILPIPE" mailpipe
114 If you don't want procmail to eat the message, you can use the
115 ``c`` flag (carbon copy) by starting your rule off with ``:0 c``.
117 >>> from io import StringIO
118 >>> from pgp_mime.email import encodedMIMEText
119 >>> from .handler import InvalidMessage, Response
120 >>> from .test.course import StubCourse
122 >>> course = StubCourse()
123 >>> def respond(message):
124 ... print('respond with:\\n{}'.format(message.as_string()))
125 >>> def process(message):
127 ... basedir=course.basedir, course=course.course,
128 ... stream=StringIO(message.as_string()),
129 ... output=course.mailbox,
130 ... continue_after_invalid_message=True,
132 >>> message = encodedMIMEText('The answer is 42.')
133 >>> message['Message-ID'] = '<123.456@home.net>'
134 >>> message['Received'] = (
135 ... 'from smtp.home.net (smtp.home.net [123.456.123.456]) '
136 ... 'by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF '
137 ... 'for <wking@tremily.us>; Sun, 09 Oct 2011 11:50:46 -0400 (EDT)')
138 >>> message['From'] = 'Billy B <bb@greyhavens.net>'
139 >>> message['To'] = 'phys101 <phys101@tower.edu>'
140 >>> message['Subject'] = '[submit] assignment 1'
142 Messages with unrecognized ``Return-Path``\s are silently dropped:
144 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
145 >>> course.print_tree() # doctest: +REPORT_UDIFF, +ELLIPSIS
152 Response to a message from an unregistered person:
154 >>> message['Return-Path'] = '<invalid.return.path@home.net>'
155 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
157 Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
159 Content-Disposition: inline
161 From: Robot101 <phys101@tower.edu>
162 Reply-to: Robot101 <phys101@tower.edu>
163 To: "invalid.return.path@home.net" <invalid.return.path@home.net>
164 Subject: unregistered address invalid.return.path@home.net
166 --===============...==
167 Content-Type: multipart/mixed; boundary="===============...=="
170 --===============...==
171 Content-Type: text/plain; charset="us-ascii"
173 Content-Transfer-Encoding: 7bit
174 Content-Disposition: inline
176 invalid.return.path@home.net,
178 Your email address is not registered with pygrader for
179 Physics 101. If you feel it should be, contact your professor
185 --===============...==
186 Content-Type: message/rfc822
189 Content-Type: text/plain; charset="us-ascii"
191 Content-Transfer-Encoding: 7bit
192 Content-Disposition: inline
193 Message-ID: <123.456@home.net>
194 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)
195 From: Billy B <bb@greyhavens.net>
196 To: phys101 <phys101@tower.edu>
197 Subject: [submit] assignment 1
198 Return-Path: <invalid.return.path@home.net>
201 --===============...==--
202 --===============...==
204 Content-Transfer-Encoding: 7bit
205 Content-Description: OpenPGP digital signature
206 Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
208 -----BEGIN PGP SIGNATURE-----
209 Version: GnuPG v2.0.19 (GNU/Linux)
212 -----END PGP SIGNATURE-----
214 --===============...==--
216 If we add a valid ``Return-Path``, we get the expected delivery:
218 >>> del message['Return-Path']
219 >>> message['Return-Path'] = '<bb@greyhavens.net>'
220 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
222 Content-Type: text/plain; charset="us-ascii"
224 Content-Disposition: inline
225 Content-Transfer-Encoding: 7bit
229 We received your submission for Assignment 1 on Sun, 09 Oct 2011 15:50:46 -0000.
235 >>> course.print_tree() # doctest: +REPORT_UDIFF, +ELLIPSIS
237 Bilbo_Baggins/Assignment_1
238 Bilbo_Baggins/Assignment_1/mail
239 Bilbo_Baggins/Assignment_1/mail/cur
240 Bilbo_Baggins/Assignment_1/mail/new
241 Bilbo_Baggins/Assignment_1/mail/new/...:2,S
242 Bilbo_Baggins/Assignment_1/mail/tmp
250 The last ``Received`` is used to timestamp the message:
252 >>> del message['Message-ID']
253 >>> message['Message-ID'] = '<abc.def@home.net>'
254 >>> del message['Received']
255 >>> message['Received'] = (
256 ... 'from smtp.mail.uu.edu (localhost.localdomain [127.0.0.1]) '
257 ... 'by smtp.mail.uu.edu (Postfix) with SMTP id 68CB45C8453 '
258 ... 'for <wking@tremily.us>; Mon, 10 Oct 2011 12:50:46 -0400 (EDT)')
259 >>> message['Received'] = (
260 ... 'from smtp.home.net (smtp.home.net [123.456.123.456]) '
261 ... 'by smtp.mail.uu.edu (Postfix) with ESMTP id 5BA225C83EF '
262 ... 'for <wking@tremily.us>; Mon, 09 Oct 2011 11:50:46 -0400 (EDT)')
263 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
265 Content-Type: text/plain; charset="us-ascii"
267 Content-Disposition: inline
268 Content-Transfer-Encoding: 7bit
272 We received your submission for Assignment 1 on Mon, 10 Oct 2011 16:50:46 -0000.
277 >>> course.print_tree() # doctest: +REPORT_UDIFF, +ELLIPSIS
279 Bilbo_Baggins/Assignment_1
280 Bilbo_Baggins/Assignment_1/late
281 Bilbo_Baggins/Assignment_1/mail
282 Bilbo_Baggins/Assignment_1/mail/cur
283 Bilbo_Baggins/Assignment_1/mail/new
284 Bilbo_Baggins/Assignment_1/mail/new/...:2,S
285 Bilbo_Baggins/Assignment_1/mail/new/...:2,S
286 Bilbo_Baggins/Assignment_1/mail/tmp
295 You can send receipts to the acknowledge incoming messages, which
296 includes warnings about dropped messages (except for messages
297 without ``Return-Path`` and messages where the ``Return-Path``
298 email belongs to multiple ``People``. The former should only
299 occur with malicious emails, and the latter with improper pygrader
302 Response to a successful submission:
304 >>> del message['Message-ID']
305 >>> message['Message-ID'] = '<hgi.jlk@home.net>'
306 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
308 Content-Type: text/plain; charset="us-ascii"
310 Content-Disposition: inline
311 Content-Transfer-Encoding: 7bit
315 We received your submission for Assignment 1 on Mon, 10 Oct 2011 16:50:46 -0000.
321 Response to a submission on an unsubmittable assignment:
323 >>> del message['Subject']
324 >>> message['Subject'] = '[submit] attendance 1'
325 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
327 Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
329 Content-Disposition: inline
331 From: Robot101 <phys101@tower.edu>
332 Reply-to: Robot101 <phys101@tower.edu>
333 To: Bilbo Baggins <bb@shire.org>
334 Subject: Received invalid Attendance 1 submission
336 --===============...==
337 Content-Type: multipart/mixed; boundary="===============...=="
340 --===============...==
341 Content-Type: text/plain; charset="us-ascii"
343 Content-Transfer-Encoding: 7bit
344 Content-Disposition: inline
348 We received your submission for Attendance 1, but you are not
349 allowed to submit that assignment via email.
354 --===============...==
355 Content-Type: message/rfc822
358 Content-Type: text/plain; charset="us-ascii"
360 Content-Transfer-Encoding: 7bit
361 Content-Disposition: inline
362 From: Billy B <bb@greyhavens.net>
363 To: phys101 <phys101@tower.edu>
364 Return-Path: <bb@greyhavens.net>
365 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)
366 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)
367 Message-ID: <hgi.jlk@home.net>
368 Subject: [submit] attendance 1
371 --===============...==--
372 --===============...==
374 Content-Transfer-Encoding: 7bit
375 Content-Description: OpenPGP digital signature
376 Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
378 -----BEGIN PGP SIGNATURE-----
379 Version: GnuPG v2.0.19 (GNU/Linux)
382 -----END PGP SIGNATURE-----
384 --===============...==--
386 Response to a bad subject:
388 >>> del message['Subject']
389 >>> message['Subject'] = 'need help for the first homework'
390 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
392 Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
394 Content-Disposition: inline
396 From: Robot101 <phys101@tower.edu>
397 Reply-to: Robot101 <phys101@tower.edu>
398 To: Bilbo Baggins <bb@shire.org>
399 Subject: no tag in 'need help for the first homework'
401 --===============...==
402 Content-Type: multipart/mixed; boundary="===============...=="
405 --===============...==
406 Content-Type: text/plain; charset="us-ascii"
408 Content-Transfer-Encoding: 7bit
409 Content-Disposition: inline
413 We received an email message from you with an invalid
419 --===============...==
420 Content-Type: message/rfc822
423 Content-Type: text/plain; charset="us-ascii"
425 Content-Transfer-Encoding: 7bit
426 Content-Disposition: inline
427 From: Billy B <bb@greyhavens.net>
428 To: phys101 <phys101@tower.edu>
429 Return-Path: <bb@greyhavens.net>
430 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)
431 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)
432 Message-ID: <hgi.jlk@home.net>
433 Subject: need help for the first homework
436 --===============...==--
437 --===============...==
439 Content-Transfer-Encoding: 7bit
440 Content-Description: OpenPGP digital signature
441 Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
443 -----BEGIN PGP SIGNATURE-----
444 Version: GnuPG v2.0.19 (GNU/Linux)
447 -----END PGP SIGNATURE-----
449 --===============...==--
451 Response to a missing subject:
453 >>> del message['Subject']
454 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
456 Content-Type: multipart/signed; protocol="application/pgp-signature"; micalg="pgp-sha1"; boundary="===============...=="
458 Content-Disposition: inline
460 From: Robot101 <phys101@tower.edu>
461 Reply-to: Robot101 <phys101@tower.edu>
462 To: Bilbo Baggins <bb@shire.org>
463 Subject: no subject in <hgi.jlk@home.net>
465 --===============...==
466 Content-Type: multipart/mixed; boundary="===============...=="
469 --===============...==
470 Content-Type: text/plain; charset="us-ascii"
472 Content-Transfer-Encoding: 7bit
473 Content-Disposition: inline
477 We received an email message from you without a subject.
482 --===============...==
483 Content-Type: message/rfc822
486 Content-Type: text/plain; charset="us-ascii"
488 Content-Transfer-Encoding: 7bit
489 Content-Disposition: inline
490 From: Billy B <bb@greyhavens.net>
491 To: phys101 <phys101@tower.edu>
492 Return-Path: <bb@greyhavens.net>
493 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)
494 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)
495 Message-ID: <hgi.jlk@home.net>
498 --===============...==--
499 --===============...==
501 Content-Transfer-Encoding: 7bit
502 Content-Description: OpenPGP digital signature
503 Content-Type: application/pgp-signature; name="signature.asc"; charset="us-ascii"
505 -----BEGIN PGP SIGNATURE-----
506 Version: GnuPG v2.0.19 (GNU/Linux)
509 -----END PGP SIGNATURE-----
511 --===============...==--
513 Response to an insecure message from a person with a PGP key:
515 >>> student = course.course.person(email='bb@greyhavens.net')
516 >>> student.pgp_key = '4332B6E3'
517 >>> del message['Subject']
518 >>> process(message) # doctest: +REPORT_UDIFF, +ELLIPSIS
520 Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; micalg="pgp-sha1"; boundary="===============...=="
522 Content-Disposition: inline
524 From: Robot101 <phys101@tower.edu>
525 Reply-to: Robot101 <phys101@tower.edu>
526 To: Bilbo Baggins <bb@shire.org>
527 Subject: unsigned message <hgi.jlk@home.net>
529 --===============...==
531 Content-Transfer-Encoding: 7bit
532 Content-Type: application/pgp-encrypted; charset="us-ascii"
536 --===============...==
538 Content-Transfer-Encoding: 7bit
539 Content-Description: OpenPGP encrypted message
540 Content-Type: application/octet-stream; name="encrypted.asc"; charset="us-ascii"
542 -----BEGIN PGP MESSAGE-----
543 Version: GnuPG v2.0.19 (GNU/Linux)
546 -----END PGP MESSAGE-----
548 --===============...==--
554 for original,message,person,subject,target in _load_messages(
555 course=course, stream=stream, mailbox=mailbox, input_=input_,
556 output=output, dry_run=dry_run,
557 continue_after_invalid_message=continue_after_invalid_message,
560 handler = _get_handler(handlers=handlers, target=target)
562 basedir=basedir, course=course, message=message,
563 person=person, subject=subject,
564 max_late=max_late, dry_run=dry_run)
565 except _InvalidMessage as error:
566 if not continue_after_invalid_message:
569 error.course = course
570 error.message = original
571 if person is not None and not hasattr(error, 'person'):
572 error.person = person
573 if subject is not None and not hasattr(error, 'subject'):
574 error.subject = subject
575 if target is not None and not hasattr(error, 'target'):
576 error.target = target
577 response = _get_error_response(error)
579 except _Response as response:
581 author = course.robot
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)
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']
602 assert subject is not None, msg
603 msg = _construct_email(
604 author=author, targets=[person], subject=subject,
606 respond(response.message)
609 def _load_messages(course, stream, mailbox=None, input_=None, output=None,
610 continue_after_invalid_message=False, respond=None,
614 messages = [(None,_message_from_file(stream))]
615 if output is not None:
616 ombox = _mailbox.Maildir(output, factory=None, create=True)
617 elif mailbox == 'mbox':
618 mbox = _mailbox.mbox(input_, factory=None, create=False)
619 messages = mbox.items()
620 if output is not None:
621 ombox = _mailbox.mbox(output, factory=None, create=True)
622 elif mailbox == 'maildir':
623 mbox = _mailbox.Maildir(input_, factory=None, create=False)
624 messages = mbox.items()
625 if output is not None:
626 ombox = _mailbox.Maildir(output, factory=None, create=True)
628 raise ValueError(mailbox)
629 for key,msg in messages:
631 ret = _parse_message(course=course, message=msg)
632 except _InvalidMessage as error:
633 if not continue_after_invalid_message:
636 response = _get_error_response(error)
637 if response is not None:
640 if output is not None and dry_run is False:
641 # move message from input mailbox to output mailbox
647 def _parse_message(course, message):
648 """Parse an incoming email and respond if neccessary.
650 Return ``(msg, person, assignment, time)`` on successful parsing.
651 Return ``None`` on failure.
654 person = subject = target = None
656 person = _get_message_person(course=course, message=message)
658 message = _get_decoded_message(
659 course=course, message=message, person=person)
660 subject = _get_message_subject(message=message)
661 target = _get_message_target(subject=subject)
662 except _InvalidMessage as error:
663 error.course = course
664 error.message = original
665 if person is not None and not hasattr(error, 'person'):
666 error.person = person
667 if subject is not None and not hasattr(error, 'subject'):
668 error.subject = subject
669 if target is not None and not hasattr(error, 'target'):
670 error.target = target
672 return (original, message, person, subject, target)
674 def _get_message_person(course, message):
675 sender = message['Return-Path'] # RFC 822
677 raise NoReturnPath(message)
678 sender = sender[1:-1] # strip wrapping '<' and '>'
679 people = list(course.find_people(email=sender))
681 raise UnregisteredAddress(message=message, address=sender)
683 raise AmbiguousAddress(message=message, address=sender, people=people)
686 def _get_decoded_message(course, message, person):
687 msg = _get_verified_message(message, person.pgp_key)
689 raise _UnsignedMessage(message=message)
692 def _get_message_subject(message):
694 >>> from email.header import Header
695 >>> from pgp_mime.email import encodedMIMEText
696 >>> message = encodedMIMEText('The answer is 42.')
697 >>> message['Message-ID'] = 'msg-id'
698 >>> _get_message_subject(message=message)
699 Traceback (most recent call last):
701 pygrader.mailpipe.SubjectlessMessage: no subject
702 >>> del message['Subject']
703 >>> subject = Header('unicode part', 'utf-8')
704 >>> subject.append('-ascii part', 'ascii')
705 >>> message['Subject'] = subject.encode()
706 >>> _get_message_subject(message=message)
707 'unicode part-ascii part'
708 >>> del message['Subject']
709 >>> message['Subject'] = 'clean subject'
710 >>> _get_message_subject(message=message)
713 if message['Subject'] is None:
714 raise SubjectlessMessage(subject=None, message=message)
716 parts = _decode_header(message['Subject'])
718 for string,encoding in parts:
721 if not isinstance(string, str):
722 string = str(string, encoding)
723 part_strings.append(string)
724 subject = ''.join(part_strings)
725 _LOG.debug('decoded header {} -> {}'.format(parts[0], subject))
726 return subject.lower().replace('#', '')
728 def _get_message_target(subject):
730 >>> _get_message_target(subject='no tag')
731 Traceback (most recent call last):
733 pygrader.handler.InvalidSubjectMessage: no tag in 'no tag'
734 >>> _get_message_target(subject='[] empty tag')
735 Traceback (most recent call last):
737 pygrader.handler.InvalidSubjectMessage: empty tag in '[] empty tag'
738 >>> _get_message_target(subject='[abc] empty tag')
740 >>> _get_message_target(subject='[phys160:abc] empty tag')
743 match = _TAG_REGEXP.match(subject)
745 raise _InvalidSubjectMessage(
746 subject=subject, error='no tag in {!r}'.format(subject))
749 raise _InvalidSubjectMessage(
750 subject=subject, error='empty tag in {!r}'.format(subject))
751 target = tag.rsplit(':', 1)[-1]
752 _LOG.debug('extracted target {} -> {}'.format(subject, target))
755 def _get_handler(handlers, target):
757 handler = handlers[target]
759 response_subject = 'no handler for {}'.format(target)
760 _LOG.warning(_color_string(string=response_subject))
761 raise InvalidHandlerMessage(target=target, handlers=handlers)
764 def _get_verified_message(message, pgp_key):
767 >>> from pgp_mime import sign, encodedMIMEText
769 The student composes a message...
771 >>> message = encodedMIMEText('1.23 joules')
773 ... and signs it (with the pgp-mime test key).
775 >>> signed = sign(message, signers=['pgp-mime-test'])
777 As it is being delivered, the message picks up extra headers.
779 >>> signed['Message-ID'] = '<01234567@home.net>'
780 >>> signed['Received'] = 'from smtp.mail.uu.edu ...'
781 >>> signed['Received'] = 'from smtp.home.net ...'
783 We check that the message is signed, and that it is signed by the
786 >>> signed.authenticated
787 Traceback (most recent call last):
789 AttributeError: 'MIMEMultipart' object has no attribute 'authenticated'
790 >>> our_message = _get_verified_message(signed, pgp_key='4332B6E3')
791 >>> print(our_message.as_string()) # doctest: +REPORT_UDIFF
792 Content-Type: text/plain; charset="us-ascii"
794 Content-Transfer-Encoding: 7bit
795 Content-Disposition: inline
796 Message-ID: <01234567@home.net>
797 Received: from smtp.mail.uu.edu ...
798 Received: from smtp.home.net ...
801 >>> our_message.authenticated
804 If it is signed, but not by the right key, we get ``None``.
806 >>> print(_get_verified_message(signed, pgp_key='01234567'))
809 If it is not signed at all, we get ``None``.
811 >>> print(_get_verified_message(message, pgp_key='4332B6E3'))
814 mid = message['message-id']
816 decrypted,verified,result = _pgp_mime.verify(message=message)
817 except (ValueError, AssertionError):
818 _LOG.warning('could not verify {} (not signed?)'.format(mid))
820 _LOG.debug(str(result, 'utf-8'))
821 tree = _etree.fromstring(result.replace(b'\x00', b''))
823 for signature in tree.findall('.//signature'):
824 for fingerprint in signature.iterchildren('fpr'):
825 if fingerprint.text.endswith(pgp_key):
829 _LOG.warning('{} is not signed by the expected key'.format(mid))
832 sumhex = list(signature.iterchildren('summary'))[0].get('value')
833 summary = int(sumhex, 16)
835 _LOG.warning('{} has an unverified signature'.format(mid))
837 # otherwise, we may have an untrusted key. We'll count that
838 # as verified here, because the caller is explicity looking
839 # for signatures by this fingerprint.
840 for k,v in message.items(): # copy over useful headers
841 if k.lower() not in ['content-type',
843 'content-disposition',
846 decrypted.authenticated = True
849 def _get_error_response(error):
850 author = error.course.robot
851 target = getattr(error, 'person', None)
853 if isinstance(error, InvalidHandlerMessage):
854 targets = sorted(error.handlers.keys())
857 'In fact, there are no available handlers for this\n'
861 'Perhaps you meant to use one of the following:\n'
862 ' {}').format('\n '.join(targets))
864 'We got an email from you with the following subject:\n'
866 'which does not match any submittable handler name for\n'
868 '{}').format(repr(error.subject), error.course.name, hint)
869 elif isinstance(error, SubjectlessMessage):
870 subject = 'no subject in {}'.format(error.message['Message-ID'])
871 text = 'We received an email message from you without a subject.'
872 elif isinstance(error, AmbiguousAddress):
874 'Multiple people match {} ({})'.format(
875 error.address, ', '.join(p.name for p in error.people)))
876 elif isinstance(error, UnregisteredAddress):
877 target = _Person(name=error.address, emails=[error.address])
879 'Your email address is not registered with pygrader for\n'
880 '{}. If you feel it should be, contact your professor\n'
881 'or TA.').format(error.course.name)
882 elif isinstance(error, NoReturnPath):
884 elif isinstance(error, _InvalidSubjectMessage):
886 'We received an email message from you with an invalid\n'
888 elif isinstance(error, _UnsignedMessage):
889 subject = 'unsigned message {}'.format(error.message['Message-ID'])
891 'We received an email message from you without a valid\n'
893 elif isinstance(error, _InvalidAssignment):
895 'We received your submission for {}, but you are not\n'
896 'allowed to submit that assignment via email.'
897 ).format(error.assignment.name)
898 elif isinstance(error, _InvalidStudent):
900 'We got an email from you with the following subject:\n'
902 'but it matches several students:\n'
904 error.subject, '\n * '.join(s.name for s in error.students))
905 elif isinstance(error, _InvalidMessage):
908 raise NotImplementedError((type(error), error))
910 raise NotImplementedError((type(error), error))
911 return _construct_response(
919 '{}\n'.format(target.alias(), text, author.alias())),
920 original=error.message)