Add validation for SSH-key before account creation

If an invalid SSH-key was used, when creating a service user, the account
creation could fail. However, an account was created, which was in the
following not registered as a service user, basically remaining unused
and blocking usernames.

This change adds a validation, checking for the common beginnings of
public keys created by OpenSSH or following RFC standards.

Change-Id: Ifdc7b74a5b723c2e2b913c6eecf70accd09b88b3
diff --git a/src/main/java/com/googlesource/gerrit/plugins/serviceuser/CreateServiceUser.java b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/CreateServiceUser.java
index 0229585..713ab41 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/serviceuser/CreateServiceUser.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/CreateServiceUser.java
@@ -47,7 +47,9 @@
 import com.google.inject.Singleton;
 import com.googlesource.gerrit.plugins.serviceuser.CreateServiceUser.Input;
 import com.googlesource.gerrit.plugins.serviceuser.GetServiceUser.ServiceUserInfo;
+import java.io.BufferedReader;
 import java.io.IOException;
+import java.io.StringReader;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Arrays;
@@ -135,10 +137,18 @@
     if (input.username != null && !username.equals(input.username)) {
       throw new BadRequestException("username must match URL");
     }
+
     if (Strings.isNullOrEmpty(input.sshKey)) {
       throw new BadRequestException("sshKey not set");
     }
 
+    final BufferedReader br = new BufferedReader(new StringReader(input.sshKey));
+    String line = br.readLine();
+    if (line == null
+        || !(line.equals("---- BEGIN SSH2 PUBLIC KEY ----") || line.startsWith("ssh-rsa"))) {
+      throw new BadRequestException("sshKey invalid.");
+    }
+
     if (blockedNames.contains(username.toLowerCase())) {
       throw new BadRequestException(
           "The username '" + username + "' is not allowed as name for service users.");