Draft: Add OAuth2 support for Gmail and Microsoft

Closed Stan Hu requested to merge sh-support-oauth2 into master

Google and Microsoft will stop support basic authentication for IMAP sometime in 2021, which will cause MailRoom to stop functioning when this happens.

This merge request adds support for the XOAUTH2 protocol, which uses the OAuth2 protocol to retrieve a temporary access token that can be used to read emails. More details here:

  1. https://developers.google.com/gmail/imap/xoauth2-protocol
  2. https://docs.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth

This merge request requires a manual registration step for a user to login and grant authorization. Once the user approves, a temporary access_token is used to read the IMAP mailbox. A long-lasting refresh_token is used to refresh the token periodically. These credentials are stored in a token file specified by the admin.

Note that service accounts are not used here because they require overly permissive permissions. A service account needs to be able to read any account in the Google Apps or Active Directory domain.

For Gmail, the registration process is a bit nicer than the Microsoft registration, since Gmail provides a scope that tells the browser to show a page where the user can cut and paste an OAuth2 authorization code.

Microsoft does not appear to offer this feature, so a user is asked to paste the full redirected URI that should have resulted in a 404 in the brower. MailRoom parses this URI for the query parameter code.

Relates to gitlab-org/gitlab#214900 (closed)

Upstream issue: https://github.com/tpitale/mail_room/issues/113

Edited by Stan Hu