Validate emails when parsing find-owner code owner configuration files

Emails in code owner configurations must be resolveable to Gerrit
accounts. This means any email that is invalid for Gerrit accounts, is
also invalid as code owner (if an email cannot be added to a Gerrit
account, it can never be resolved to a Gerrit account and hence it makes
no sense to allow it as code owner). Since emails for Gerrit accounts
are validated by OutgoingEmailValidator we should use the same validator
for code owner emails although it's not only checking if the email is
valid, but also if the email is allowed to receive email notifications.

Alternatively we considered to use
org.apache.commons.validator.routines.EmailValidator, which is used by
OutgoingEmailValidator internally, but this is not possible since it is
a singleton with some static initialization and hence we can't use an
EmailValidator instance that is different from the one that is used in
OutgoingEmailValidator. This means we must use OutgoingEmailValidator,
as this class takes care to do the static setup which must be done
before the first use of the EmailValidator singleton instance.

Signed-off-by: Edwin Kempin <ekempin@google.com>
Change-Id: I6669dd56459bdd1af4a0d6031446f3b56ee413ec
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java
index 156bee3..f156365 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParser.java
@@ -16,7 +16,11 @@
 
 import com.google.common.base.Splitter;
 import com.google.common.collect.Streams;
+import com.google.common.flogger.FluentLogger;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.server.mail.send.OutgoingEmailValidator;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
 
 /**
  * Parser for {@code OWNERS} files as they are used by the {@code find-owners} plugin.
@@ -31,41 +35,54 @@
  *   <li>code owner emails: a line can be the email of a code owner
  * </ul>
  *
- * <p>Invalid lines are silently ignored.
+ * <p>Invalid lines and invalid emails are silently ignored.
  */
-final class CodeOwnerConfigParser {
+@Singleton
+class CodeOwnerConfigParser {
+  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
+
+  /**
+   * To validate emails we use the same validator that Gerrit core is using to validate emails for
+   * Gerrit accounts.
+   *
+   * <p>Emails in code owner configurations must be resolveable to Gerrit accounts. This means any
+   * email that is invalid for Gerrit accounts, is also invalid as code owner (if an email cannot be
+   * added to a Gerrit account, it can never be resolved to a Gerrit account and hence it makes no
+   * sense to allow it as code owner).
+   */
+  private final OutgoingEmailValidator emailValidator;
+
+  @Inject
+  CodeOwnerConfigParser(OutgoingEmailValidator emailValidator) {
+    this.emailValidator = emailValidator;
+  }
   /**
    * Parses a {@link CodeOwnerConfig} from a string that represents the content of an {@code OWNERS}
    * file.
    *
-   * <p>Invalid lines are silently ignored.
+   * <p>Invalid lines and invalid emails are silently ignored.
    *
    * @param codeOwnerConfigKey the key of the code owner config that should be parsed
    * @param codeOwnerConfigFileContent string that represents the content of an {@code OWNERS} file
    * @return the parsed {@link CodeOwnerConfig}
    */
-  static CodeOwnerConfig parse(
-      CodeOwnerConfig.Key codeOwnerConfigKey, String codeOwnerConfigFileContent) {
+  CodeOwnerConfig parse(CodeOwnerConfig.Key codeOwnerConfigKey, String codeOwnerConfigFileContent) {
     CodeOwnerConfig.Builder codeOwnerConfig = CodeOwnerConfig.builder(codeOwnerConfigKey);
 
     Streams.stream(Splitter.on('\n').split(codeOwnerConfigFileContent))
         .map(String::trim)
-        .filter(CodeOwnerConfigParser::isEmail)
+        .filter(this::isEmail)
         .distinct()
         .forEach(codeOwnerConfig::addCodeOwnerEmail);
 
     return codeOwnerConfig.build();
   }
 
-  private static boolean isEmail(String trimmedLine) {
-    // TODO(ekempin): Make this check smarter.
-    return trimmedLine.contains("@");
+  private boolean isEmail(String trimmedLine) {
+    if (!emailValidator.isValid(trimmedLine)) {
+      logger.atInfo().log("Skipping line that is not an email: %s", trimmedLine);
+      return false;
+    }
+    return true;
   }
-
-  /**
-   * Private constructor to prevent instantiation of this class.
-   *
-   * <p>The class only contains static methods, hence the class never needs to be instantiated.
-   */
-  private CodeOwnerConfigParser() {}
 }
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java
index e8ea740..2944966 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java
@@ -16,17 +16,28 @@
 
 import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerConfigSubject.assertThat;
 
+import com.google.gerrit.acceptance.LightweightPluginDaemonTest;
+import com.google.gerrit.acceptance.TestPlugin;
 import com.google.gerrit.entities.Project;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import org.junit.Before;
 import org.junit.Test;
 
 /** Tests for {@link CodeOwnerConfigParser}. */
-public class CodeOwnerConfigParserTest {
+@TestPlugin(name = "code-owners", sysModule = "com.google.gerrit.plugins.codeowners.Module")
+public class CodeOwnerConfigParserTest extends LightweightPluginDaemonTest {
   // Emails for testing, sorted alphabetically.
   private static final String EMAIL_1 = "admin@test.com";
   private static final String EMAIL_2 = "jdoe@test.com";
   private static final String EMAIL_3 = "jroe@test.com";
 
+  private CodeOwnerConfigParser codeOwnerConfigParser;
+
+  @Before
+  public void setUpCodeOwnersPlugin() throws Exception {
+    codeOwnerConfigParser = plugin.getSysInjector().getInstance(CodeOwnerConfigParser.class);
+  }
+
   @Test
   public void emptyCodeOwnerConfig() throws Exception {
     CodeOwnerConfig codeOwnerConfig = parse("");
@@ -90,7 +101,12 @@
     assertThat(codeOwnerConfig).hasCodeOwnersEmailsThat().containsExactly(EMAIL_1, EMAIL_2);
   }
 
-  // TODO: add tests with invalid emails, e.g. "@test.com", "admin@", "admin@test@com".
+  @Test
+  public void codeOwnerConfigWithInvalidEmails_InvalidEmailsAreIgnored() throws Exception {
+    CodeOwnerConfig codeOwnerConfig =
+        parse(String.format("%s\n@test.com\nadmin@\nadmin@test@com\n%s", EMAIL_1, EMAIL_2));
+    assertThat(codeOwnerConfig).hasCodeOwnersEmailsThat().containsExactly(EMAIL_1, EMAIL_2);
+  }
 
   @Test
   public void codeOwnerConfigWithInvalidLines_InvalidLinesAreIgnored() throws Exception {
@@ -108,6 +124,6 @@
   private CodeOwnerConfig parse(String codeOwnerConfig) {
     CodeOwnerConfig.Key codeOwnerConfigKey =
         CodeOwnerConfig.Key.create(Project.nameKey("project"), "master", "/");
-    return CodeOwnerConfigParser.parse(codeOwnerConfigKey, codeOwnerConfig);
+    return codeOwnerConfigParser.parse(codeOwnerConfigKey, codeOwnerConfig);
   }
 }