diff --git a/src/applications/maniphest/mail/ManiphestTaskMailReceiver.php b/src/applications/maniphest/mail/ManiphestTaskMailReceiver.php index e69ae82938..220a888e8e 100644 --- a/src/applications/maniphest/mail/ManiphestTaskMailReceiver.php +++ b/src/applications/maniphest/mail/ManiphestTaskMailReceiver.php @@ -1,31 +1,29 @@ setViewer($viewer) ->withIDs(array($id)) ->needSubscriberPHIDs(true) ->needProjectPHIDs(true) - ->execute(); - - return head($results); + ->executeOne(); } protected function getTransactionReplyHandler() { return new ManiphestReplyHandler(); } } diff --git a/src/applications/metamta/receiver/__tests__/PhabricatorObjectMailReceiverTestCase.php b/src/applications/metamta/receiver/__tests__/PhabricatorObjectMailReceiverTestCase.php index a697436d21..8cef832117 100644 --- a/src/applications/metamta/receiver/__tests__/PhabricatorObjectMailReceiverTestCase.php +++ b/src/applications/metamta/receiver/__tests__/PhabricatorObjectMailReceiverTestCase.php @@ -1,129 +1,134 @@ true, ); } public function testDropUnconfiguredPublicMail() { list($task, $user, $mail) = $this->buildMail('public'); $env = PhabricatorEnv::beginScopedEnv(); $env->overrideEnvConfig('metamta.public-replies', false); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_NO_PUBLIC_MAIL, $mail->getStatus()); } -/* - - TODO: Tasks don't support policies yet. Implement this once they do. - public function testDropPolicyViolationMail() { - list($task, $user, $mail) = $this->buildMail('public'); + list($task, $user, $mail) = $this->buildMail('policy'); - // TODO: Set task policy to "no one" here. + $task + ->setViewPolicy(PhabricatorPolicies::POLICY_NOONE) + ->setOwnerPHID(null) + ->save(); + + $env = PhabricatorEnv::beginScopedEnv(); + $env->overrideEnvConfig('metamta.public-replies', true); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_POLICY_PROBLEM, $mail->getStatus()); } -*/ - public function testDropInvalidObjectMail() { list($task, $user, $mail) = $this->buildMail('404'); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_NO_SUCH_OBJECT, $mail->getStatus()); } public function testDropUserMismatchMail() { list($task, $user, $mail) = $this->buildMail('baduser'); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_USER_MISMATCH, $mail->getStatus()); } public function testDropHashMismatchMail() { list($task, $user, $mail) = $this->buildMail('badhash'); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_HASH_MISMATCH, $mail->getStatus()); } private function buildMail($style) { $user = $this->generateNewTestUser(); $task = id(new PhabricatorManiphestTaskTestDataGenerator()) ->setViewer($user) ->generateObject(); $is_public = ($style === 'public'); $is_bad_hash = ($style == 'badhash'); $is_bad_user = ($style == 'baduser'); $is_404_object = ($style == '404'); if ($is_public) { $user_identifier = 'public'; } else if ($is_bad_user) { $user_identifier = $user->getID() + 1; } else { $user_identifier = $user->getID(); } if ($is_bad_hash) { $hash = PhabricatorObjectMailReceiver::computeMailHash('x', 'y'); } else { $mail_key = PhabricatorMetaMTAMailProperties::loadMailKey($task); $hash = PhabricatorObjectMailReceiver::computeMailHash( $mail_key, $is_public ? $task->getPHID() : $user->getPHID()); } if ($is_404_object) { $task_identifier = 'T'.($task->getID() + 1); } else { $task_identifier = 'T'.$task->getID(); } $to = $task_identifier.'+'.$user_identifier.'+'.$hash.'@example.com'; $mail = new PhabricatorMetaMTAReceivedMail(); $mail->setHeaders( array( 'Message-ID' => 'test@example.com', 'From' => $user->loadPrimaryEmail()->getAddress(), 'To' => $to, )); + $mail->setBodies( + array( + 'text' => 'test', + )); + return array($task, $user, $mail); } } diff --git a/src/applications/metamta/replyhandler/PhabricatorMailReplyHandler.php b/src/applications/metamta/replyhandler/PhabricatorMailReplyHandler.php index 70b524b52f..72e23ec2c1 100644 --- a/src/applications/metamta/replyhandler/PhabricatorMailReplyHandler.php +++ b/src/applications/metamta/replyhandler/PhabricatorMailReplyHandler.php @@ -1,442 +1,411 @@ validateMailReceiver($mail_receiver); $this->mailReceiver = $mail_receiver; return $this; } final public function getMailReceiver() { return $this->mailReceiver; } public function setApplicationEmail( PhabricatorMetaMTAApplicationEmail $email) { $this->applicationEmail = $email; return $this; } public function getApplicationEmail() { return $this->applicationEmail; } final public function setActor(PhabricatorUser $actor) { $this->actor = $actor; return $this; } final public function getActor() { return $this->actor; } final public function setExcludeMailRecipientPHIDs(array $exclude) { $this->excludePHIDs = $exclude; return $this; } final public function getExcludeMailRecipientPHIDs() { return $this->excludePHIDs; } public function setUnexpandablePHIDs(array $phids) { $this->unexpandablePHIDs = $phids; return $this; } public function getUnexpandablePHIDs() { return $this->unexpandablePHIDs; } abstract public function validateMailReceiver($mail_receiver); abstract public function getPrivateReplyHandlerEmailAddress( PhabricatorUser $user); public function getReplyHandlerDomain() { return PhabricatorEnv::getEnvConfig('metamta.reply-handler-domain'); } abstract protected function receiveEmail( PhabricatorMetaMTAReceivedMail $mail); public function processEmail(PhabricatorMetaMTAReceivedMail $mail) { - $this->dropEmptyMail($mail); - return $this->receiveEmail($mail); } - private function dropEmptyMail(PhabricatorMetaMTAReceivedMail $mail) { - $body = $mail->getCleanTextBody(); - $attachments = $mail->getAttachments(); - - if (strlen($body) || $attachments) { - return; - } - - // Only send an error email if the user is talking to just Phabricator. - // We can assume if there is only one "To" address it is a Phabricator - // address since this code is running and everything. - $is_direct_mail = (count($mail->getToAddresses()) == 1) && - (count($mail->getCCAddresses()) == 0); - - if ($is_direct_mail) { - $status_code = MetaMTAReceivedMailStatus::STATUS_EMPTY; - } else { - $status_code = MetaMTAReceivedMailStatus::STATUS_EMPTY_IGNORED; - } - - throw new PhabricatorMetaMTAReceivedMailProcessingException( - $status_code, - pht( - 'Your message does not contain any body text or attachments, so '. - 'Phabricator can not do anything useful with it. Make sure comment '. - 'text appears at the top of your message: quoted replies, inline '. - 'text, and signatures are discarded and ignored.')); - } - public function supportsPrivateReplies() { return (bool)$this->getReplyHandlerDomain() && !$this->supportsPublicReplies(); } public function supportsPublicReplies() { if (!PhabricatorEnv::getEnvConfig('metamta.public-replies')) { return false; } if (!$this->getReplyHandlerDomain()) { return false; } return (bool)$this->getPublicReplyHandlerEmailAddress(); } final public function supportsReplies() { return $this->supportsPrivateReplies() || $this->supportsPublicReplies(); } public function getPublicReplyHandlerEmailAddress() { return null; } protected function getDefaultPublicReplyHandlerEmailAddress($prefix) { $receiver = $this->getMailReceiver(); $receiver_id = $receiver->getID(); $domain = $this->getReplyHandlerDomain(); // We compute a hash using the object's own PHID to prevent an attacker // from blindly interacting with objects that they haven't ever received // mail about by just sending to D1@, D2@, etc... $mail_key = PhabricatorMetaMTAMailProperties::loadMailKey($receiver); $hash = PhabricatorObjectMailReceiver::computeMailHash( $mail_key, $receiver->getPHID()); $address = "{$prefix}{$receiver_id}+public+{$hash}@{$domain}"; return $this->getSingleReplyHandlerPrefix($address); } protected function getSingleReplyHandlerPrefix($address) { $single_handle_prefix = PhabricatorEnv::getEnvConfig( 'metamta.single-reply-handler-prefix'); return ($single_handle_prefix) ? $single_handle_prefix.'+'.$address : $address; } protected function getDefaultPrivateReplyHandlerEmailAddress( PhabricatorUser $user, $prefix) { $receiver = $this->getMailReceiver(); $receiver_id = $receiver->getID(); $user_id = $user->getID(); $mail_key = PhabricatorMetaMTAMailProperties::loadMailKey($receiver); $hash = PhabricatorObjectMailReceiver::computeMailHash( $mail_key, $user->getPHID()); $domain = $this->getReplyHandlerDomain(); $address = "{$prefix}{$receiver_id}+{$user_id}+{$hash}@{$domain}"; return $this->getSingleReplyHandlerPrefix($address); } final protected function enhanceBodyWithAttachments( $body, array $attachments) { if (!$attachments) { return $body; } $files = id(new PhabricatorFileQuery()) ->setViewer($this->getActor()) ->withPHIDs($attachments) ->execute(); $output = array(); $output[] = $body; // We're going to put all the non-images first in a list, then embed // the images. $head = array(); $tail = array(); foreach ($files as $file) { if ($file->isViewableImage()) { $tail[] = $file; } else { $head[] = $file; } } if ($head) { $list = array(); foreach ($head as $file) { $list[] = ' - {'.$file->getMonogram().', layout=link}'; } $output[] = implode("\n", $list); } if ($tail) { $list = array(); foreach ($tail as $file) { $list[] = '{'.$file->getMonogram().'}'; } $output[] = implode("\n\n", $list); } $output = implode("\n\n", $output); return rtrim($output); } /** * Produce a list of mail targets for a given to/cc list. * * Each target should be sent a separate email, and contains the information * required to generate it with appropriate permissions and configuration. * * @param list List of "To" PHIDs. * @param list List of "CC" PHIDs. * @return list List of targets. */ final public function getMailTargets(array $raw_to, array $raw_cc) { list($to, $cc) = $this->expandRecipientPHIDs($raw_to, $raw_cc); list($to, $cc) = $this->loadRecipientUsers($to, $cc); list($to, $cc) = $this->filterRecipientUsers($to, $cc); if (!$to && !$cc) { return array(); } $template = id(new PhabricatorMailTarget()) ->setRawToPHIDs($raw_to) ->setRawCCPHIDs($raw_cc); // Set the public reply address as the default, if one exists. We // might replace this with a private address later. if ($this->supportsPublicReplies()) { $reply_to = $this->getPublicReplyHandlerEmailAddress(); if ($reply_to) { $template->setReplyTo($reply_to); } } $supports_private_replies = $this->supportsPrivateReplies(); $mail_all = !PhabricatorEnv::getEnvConfig('metamta.one-mail-per-recipient'); $targets = array(); if ($mail_all) { $target = id(clone $template) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->setToMap($to) ->setCCMap($cc); $targets[] = $target; } else { $map = $to + $cc; foreach ($map as $phid => $user) { // Preserve the original To/Cc information on the target. if (isset($to[$phid])) { $target_to = array($phid => $user); $target_cc = array(); } else { $target_to = array(); $target_cc = array($phid => $user); } $target = id(clone $template) ->setViewer($user) ->setToMap($target_to) ->setCCMap($target_cc); if ($supports_private_replies) { $reply_to = $this->getPrivateReplyHandlerEmailAddress($user); if ($reply_to) { $target->setReplyTo($reply_to); } } $targets[] = $target; } } return $targets; } /** * Expand lists of recipient PHIDs. * * This takes any compound recipients (like projects) and looks up all their * members. * * @param list List of To PHIDs. * @param list List of CC PHIDs. * @return pair, list> Expanded PHID lists. */ private function expandRecipientPHIDs(array $to, array $cc) { $to_result = array(); $cc_result = array(); // "Unexpandable" users have disengaged from an object (for example, // by resigning from a revision). // If such a user is still a direct recipient (for example, they're still // on the Subscribers list) they're fair game, but group targets (like // projects) will no longer include them when expanded. $unexpandable = $this->getUnexpandablePHIDs(); $unexpandable = array_fuse($unexpandable); $all_phids = array_merge($to, $cc); if ($all_phids) { $map = id(new PhabricatorMetaMTAMemberQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs($all_phids) ->execute(); foreach ($to as $phid) { foreach ($map[$phid] as $expanded) { if ($expanded !== $phid) { if (isset($unexpandable[$expanded])) { continue; } } $to_result[$expanded] = $expanded; } } foreach ($cc as $phid) { foreach ($map[$phid] as $expanded) { if ($expanded !== $phid) { if (isset($unexpandable[$expanded])) { continue; } } $cc_result[$expanded] = $expanded; } } } // Remove recipients from "CC" if they're also present in "To". $cc_result = array_diff_key($cc_result, $to_result); return array(array_values($to_result), array_values($cc_result)); } /** * Load @{class:PhabricatorUser} objects for each recipient. * * Invalid recipients are dropped from the results. * * @param list List of To PHIDs. * @param list List of CC PHIDs. * @return pair Maps from PHIDs to users. */ private function loadRecipientUsers(array $to, array $cc) { $to_result = array(); $cc_result = array(); $all_phids = array_merge($to, $cc); if ($all_phids) { // We need user settings here because we'll check translations later // when generating mail. $users = id(new PhabricatorPeopleQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs($all_phids) ->needUserSettings(true) ->execute(); $users = mpull($users, null, 'getPHID'); foreach ($to as $phid) { if (isset($users[$phid])) { $to_result[$phid] = $users[$phid]; } } foreach ($cc as $phid) { if (isset($users[$phid])) { $cc_result[$phid] = $users[$phid]; } } } return array($to_result, $cc_result); } /** * Remove recipients who do not have permission to view the mail receiver. * * @param map Map of "To" users. * @param map Map of "CC" users. * @return pair Filtered user maps. */ private function filterRecipientUsers(array $to, array $cc) { $to_result = array(); $cc_result = array(); $all_users = $to + $cc; if ($all_users) { $can_see = array(); $object = $this->getMailReceiver(); foreach ($all_users as $phid => $user) { $visible = PhabricatorPolicyFilter::hasCapability( $user, $object, PhabricatorPolicyCapability::CAN_VIEW); if ($visible) { $can_see[$phid] = true; } } foreach ($to as $phid => $user) { if (!empty($can_see[$phid])) { $to_result[$phid] = $all_users[$phid]; } } foreach ($cc as $phid => $user) { if (!empty($can_see[$phid])) { $cc_result[$phid] = $all_users[$phid]; } } } return array($to_result, $cc_result); } } diff --git a/src/applications/metamta/storage/PhabricatorMetaMTAReceivedMail.php b/src/applications/metamta/storage/PhabricatorMetaMTAReceivedMail.php index fc98d17010..271372afe5 100644 --- a/src/applications/metamta/storage/PhabricatorMetaMTAReceivedMail.php +++ b/src/applications/metamta/storage/PhabricatorMetaMTAReceivedMail.php @@ -1,387 +1,416 @@ array( 'headers' => self::SERIALIZATION_JSON, 'bodies' => self::SERIALIZATION_JSON, 'attachments' => self::SERIALIZATION_JSON, ), self::CONFIG_COLUMN_SCHEMA => array( 'relatedPHID' => 'phid?', 'authorPHID' => 'phid?', 'message' => 'text?', 'messageIDHash' => 'bytes12', 'status' => 'text32', ), self::CONFIG_KEY_SCHEMA => array( 'relatedPHID' => array( 'columns' => array('relatedPHID'), ), 'authorPHID' => array( 'columns' => array('authorPHID'), ), 'key_messageIDHash' => array( 'columns' => array('messageIDHash'), ), 'key_created' => array( 'columns' => array('dateCreated'), ), ), ) + parent::getConfiguration(); } public function setHeaders(array $headers) { // Normalize headers to lowercase. $normalized = array(); foreach ($headers as $name => $value) { $name = $this->normalizeMailHeaderName($name); if ($name == 'message-id') { $this->setMessageIDHash(PhabricatorHash::digestForIndex($value)); } $normalized[$name] = $value; } $this->headers = $normalized; return $this; } public function getHeader($key, $default = null) { $key = $this->normalizeMailHeaderName($key); return idx($this->headers, $key, $default); } private function normalizeMailHeaderName($name) { return strtolower($name); } public function getMessageID() { return $this->getHeader('Message-ID'); } public function getSubject() { return $this->getHeader('Subject'); } public function getCCAddresses() { return $this->getRawEmailAddresses(idx($this->headers, 'cc')); } public function getToAddresses() { return $this->getRawEmailAddresses(idx($this->headers, 'to')); } public function loadAllRecipientPHIDs() { $addresses = array_merge( $this->getToAddresses(), $this->getCCAddresses()); return $this->loadPHIDsFromAddresses($addresses); } public function loadCCPHIDs() { return $this->loadPHIDsFromAddresses($this->getCCAddresses()); } private function loadPHIDsFromAddresses(array $addresses) { if (empty($addresses)) { return array(); } $users = id(new PhabricatorUserEmail()) ->loadAllWhere('address IN (%Ls)', $addresses); return mpull($users, 'getUserPHID'); } public function processReceivedMail() { $sender = null; try { $this->dropMailFromPhabricator(); $this->dropMailAlreadyReceived(); + $this->dropEmptyMail(); $receiver = $this->loadReceiver(); $sender = $receiver->loadSender($this); $receiver->validateSender($this, $sender); $this->setAuthorPHID($sender->getPHID()); // Now that we've identified the sender, mark them as the author of // any attached files. $attachments = $this->getAttachments(); if ($attachments) { $files = id(new PhabricatorFileQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withPHIDs($attachments) ->execute(); foreach ($files as $file) { $file->setAuthorPHID($sender->getPHID())->save(); } } $receiver->receiveMail($this, $sender); } catch (PhabricatorMetaMTAReceivedMailProcessingException $ex) { switch ($ex->getStatusCode()) { case MetaMTAReceivedMailStatus::STATUS_DUPLICATE: case MetaMTAReceivedMailStatus::STATUS_FROM_PHABRICATOR: // Don't send an error email back in these cases, since they're // very unlikely to be the sender's fault. break; case MetaMTAReceivedMailStatus::STATUS_EMPTY_IGNORED: // This error is explicitly ignored. break; default: $this->sendExceptionMail($ex, $sender); break; } $this ->setStatus($ex->getStatusCode()) ->setMessage($ex->getMessage()) ->save(); return $this; } catch (Exception $ex) { $this->sendExceptionMail($ex, $sender); $this ->setStatus(MetaMTAReceivedMailStatus::STATUS_UNHANDLED_EXCEPTION) ->setMessage(pht('Unhandled Exception: %s', $ex->getMessage())) ->save(); throw $ex; } return $this->setMessage('OK')->save(); } public function getCleanTextBody() { $body = $this->getRawTextBody(); $parser = new PhabricatorMetaMTAEmailBodyParser(); return $parser->stripTextBody($body); } public function parseBody() { $body = $this->getRawTextBody(); $parser = new PhabricatorMetaMTAEmailBodyParser(); return $parser->parseBody($body); } public function getRawTextBody() { return idx($this->bodies, 'text'); } /** * Strip an email address down to the actual user@domain.tld part if * necessary, since sometimes it will have formatting like * '"Abraham Lincoln" '. */ private function getRawEmailAddress($address) { $matches = null; $ok = preg_match('/<(.*)>/', $address, $matches); if ($ok) { $address = $matches[1]; } return $address; } private function getRawEmailAddresses($addresses) { $raw_addresses = array(); foreach (explode(',', $addresses) as $address) { $raw_addresses[] = $this->getRawEmailAddress($address); } return array_filter($raw_addresses); } /** * If Phabricator sent the mail, always drop it immediately. This prevents * loops where, e.g., the public bug address is also a user email address * and creating a bug sends them an email, which loops. */ private function dropMailFromPhabricator() { if (!$this->getHeader('x-phabricator-sent-this-message')) { return; } throw new PhabricatorMetaMTAReceivedMailProcessingException( MetaMTAReceivedMailStatus::STATUS_FROM_PHABRICATOR, pht( "Ignoring email with '%s' header to avoid loops.", 'X-Phabricator-Sent-This-Message')); } /** * If this mail has the same message ID as some other mail, and isn't the * first mail we we received with that message ID, we drop it as a duplicate. */ private function dropMailAlreadyReceived() { $message_id_hash = $this->getMessageIDHash(); if (!$message_id_hash) { // No message ID hash, so we can't detect duplicates. This should only // happen with very old messages. return; } $messages = $this->loadAllWhere( 'messageIDHash = %s ORDER BY id ASC LIMIT 2', $message_id_hash); $messages_count = count($messages); if ($messages_count <= 1) { // If we only have one copy of this message, we're good to process it. return; } $first_message = reset($messages); if ($first_message->getID() == $this->getID()) { // If this is the first copy of the message, it is okay to process it. // We may not have been able to to process it immediately when we received // it, and could may have received several copies without processing any // yet. return; } $message = pht( 'Ignoring email with "Message-ID" hash "%s" that has been seen %d '. 'times, including this message.', $message_id_hash, $messages_count); throw new PhabricatorMetaMTAReceivedMailProcessingException( MetaMTAReceivedMailStatus::STATUS_DUPLICATE, $message); } + private function dropEmptyMail() { + $body = $this->getCleanTextBody(); + $attachments = $this->getAttachments(); + + if (strlen($body) || $attachments) { + return; + } + + // Only send an error email if the user is talking to just Phabricator. + // We can assume if there is only one "To" address it is a Phabricator + // address since this code is running and everything. + $is_direct_mail = (count($this->getToAddresses()) == 1) && + (count($this->getCCAddresses()) == 0); + + if ($is_direct_mail) { + $status_code = MetaMTAReceivedMailStatus::STATUS_EMPTY; + } else { + $status_code = MetaMTAReceivedMailStatus::STATUS_EMPTY_IGNORED; + } + + throw new PhabricatorMetaMTAReceivedMailProcessingException( + $status_code, + pht( + 'Your message does not contain any body text or attachments, so '. + 'Phabricator can not do anything useful with it. Make sure comment '. + 'text appears at the top of your message: quoted replies, inline '. + 'text, and signatures are discarded and ignored.')); + } /** * Load a concrete instance of the @{class:PhabricatorMailReceiver} which * accepts this mail, if one exists. */ private function loadReceiver() { $receivers = id(new PhutilClassMapQuery()) ->setAncestorClass('PhabricatorMailReceiver') ->setFilterMethod('isEnabled') ->execute(); $accept = array(); foreach ($receivers as $key => $receiver) { if ($receiver->canAcceptMail($this)) { $accept[$key] = $receiver; } } if (!$accept) { throw new PhabricatorMetaMTAReceivedMailProcessingException( MetaMTAReceivedMailStatus::STATUS_NO_RECEIVERS, pht( 'Phabricator can not process this mail because no application '. 'knows how to handle it. Check that the address you sent it to is '. 'correct.'. "\n\n". '(No concrete, enabled subclass of PhabricatorMailReceiver can '. 'accept this mail.)')); } if (count($accept) > 1) { $names = implode(', ', array_keys($accept)); throw new PhabricatorMetaMTAReceivedMailProcessingException( MetaMTAReceivedMailStatus::STATUS_ABUNDANT_RECEIVERS, pht( 'Phabricator is not able to process this mail because more than '. 'one application is willing to accept it, creating ambiguity. '. 'Mail needs to be accepted by exactly one receiving application.'. "\n\n". 'Accepting receivers: %s.', $names)); } return head($accept); } private function sendExceptionMail( Exception $ex, PhabricatorUser $viewer = null) { // If we've failed to identify a legitimate sender, we don't send them // an error message back. We want to avoid sending mail to unverified // addresses. See T12491. if (!$viewer) { return; } if ($ex instanceof PhabricatorMetaMTAReceivedMailProcessingException) { $status_code = $ex->getStatusCode(); $status_name = MetaMTAReceivedMailStatus::getHumanReadableName( $status_code); $title = pht('Error Processing Mail (%s)', $status_name); $description = $ex->getMessage(); } else { $title = pht('Error Processing Mail (%s)', get_class($ex)); $description = pht('%s: %s', get_class($ex), $ex->getMessage()); } // TODO: Since headers don't necessarily have unique names, this may not // really be all the headers. It would be nice to pass the raw headers // through from the upper layers where possible. // On the MimeMailParser pathway, we arrive here with a list value for // headers that appeared multiple times in the original mail. Be // accommodating until header handling gets straightened out. $headers = array(); foreach ($this->headers as $key => $values) { if (!is_array($values)) { $values = array($values); } foreach ($values as $value) { $headers[] = pht('%s: %s', $key, $value); } } $headers = implode("\n", $headers); $body = pht(<<getRawTextBody(), $headers); $mail = id(new PhabricatorMetaMTAMail()) ->setIsErrorEmail(true) ->setSubject($title) ->addTos(array($viewer->getPHID())) ->setBody($body) ->saveAndSend(); } public function newContentSource() { return PhabricatorContentSource::newForSource( PhabricatorEmailContentSource::SOURCECONST, array( 'id' => $this->getID(), )); } } diff --git a/src/applications/metamta/storage/__tests__/PhabricatorMetaMTAReceivedMailTestCase.php b/src/applications/metamta/storage/__tests__/PhabricatorMetaMTAReceivedMailTestCase.php index fbabe412c3..31a31b5ff2 100644 --- a/src/applications/metamta/storage/__tests__/PhabricatorMetaMTAReceivedMailTestCase.php +++ b/src/applications/metamta/storage/__tests__/PhabricatorMetaMTAReceivedMailTestCase.php @@ -1,124 +1,136 @@ true, ); } public function testDropSelfMail() { $mail = new PhabricatorMetaMTAReceivedMail(); $mail->setHeaders( array( 'X-Phabricator-Sent-This-Message' => 'yes', )); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_FROM_PHABRICATOR, $mail->getStatus()); } public function testDropDuplicateMail() { $mail_a = new PhabricatorMetaMTAReceivedMail(); $mail_a->setHeaders( array( 'Message-ID' => 'test@example.com', )); $mail_a->save(); $mail_b = new PhabricatorMetaMTAReceivedMail(); $mail_b->setHeaders( array( 'Message-ID' => 'test@example.com', )); $mail_b->save(); $mail_a->processReceivedMail(); $mail_b->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_DUPLICATE, $mail_b->getStatus()); } public function testDropUnreceivableMail() { $mail = new PhabricatorMetaMTAReceivedMail(); $mail->setHeaders( array( 'Message-ID' => 'test@example.com', 'To' => 'does+not+exist@example.com', )); + $mail->setBodies( + array( + 'text' => 'test', + )); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_NO_RECEIVERS, $mail->getStatus()); } public function testDropUnknownSenderMail() { $this->setManiphestCreateEmail(); $env = PhabricatorEnv::beginScopedEnv(); $env->overrideEnvConfig('phabricator.allow-email-users', false); $env->overrideEnvConfig('metamta.maniphest.default-public-author', null); $mail = new PhabricatorMetaMTAReceivedMail(); $mail->setHeaders( array( 'Message-ID' => 'test@example.com', 'To' => 'bugs@example.com', 'From' => 'does+not+exist@example.com', )); + $mail->setBodies( + array( + 'text' => 'test', + )); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_UNKNOWN_SENDER, $mail->getStatus()); } public function testDropDisabledSenderMail() { $this->setManiphestCreateEmail(); $user = $this->generateNewTestUser() ->setIsDisabled(true) ->save(); $mail = new PhabricatorMetaMTAReceivedMail(); $mail->setHeaders( array( 'Message-ID' => 'test@example.com', 'From' => $user->loadPrimaryEmail()->getAddress(), 'To' => 'bugs@example.com', )); + $mail->setBodies( + array( + 'text' => 'test', + )); $mail->save(); $mail->processReceivedMail(); $this->assertEqual( MetaMTAReceivedMailStatus::STATUS_DISABLED_SENDER, $mail->getStatus()); } private function setManiphestCreateEmail() { $maniphest_app = new PhabricatorManiphestApplication(); try { id(new PhabricatorMetaMTAApplicationEmail()) ->setApplicationPHID($maniphest_app->getPHID()) ->setAddress('bugs@example.com') ->setConfigData(array()) ->save(); } catch (AphrontDuplicateKeyQueryException $ex) {} } }