Add command to register existing user as service user

Before installing the serviceuser plugin technical users might already
exist, e.g. in LDAP or in Gerrit itself. It might be desirable to
register those users as service users to avoid having multiple account
types for the same purpose.

This change adds a SSH command that allows to register an existing
user as a serviceuser by adding the serviceuser specific data to the
serviceuser.db file in the All-Projects repository.

To be able to execute this command, the caller has to either be an
administrator or be the user that should be registered as a service
user and have the 'create serviceuser' capability. This was done to
prevent users from registering other users, which they don't own, as
serviceusers, which would allow them to basically get all access rights
the serviceuser has.

The command allows for setting the creator manually and to also set
the owner group.

Change-Id: I447bc702565d2836ef12072fd5656be343428cf3
diff --git a/src/main/java/com/googlesource/gerrit/plugins/serviceuser/RegisterServiceUser.java b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/RegisterServiceUser.java
new file mode 100644
index 0000000..f01b56f
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/RegisterServiceUser.java
@@ -0,0 +1,203 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.serviceuser;
+
+import static com.google.gerrit.server.permissions.GlobalPermission.ADMINISTRATE_SERVER;
+import static com.googlesource.gerrit.plugins.serviceuser.CreateServiceUser.KEY_CREATED_AT;
+import static com.googlesource.gerrit.plugins.serviceuser.CreateServiceUser.KEY_CREATED_BY;
+import static com.googlesource.gerrit.plugins.serviceuser.CreateServiceUser.KEY_CREATOR_ID;
+import static com.googlesource.gerrit.plugins.serviceuser.CreateServiceUser.KEY_OWNER;
+import static com.googlesource.gerrit.plugins.serviceuser.CreateServiceUser.USER;
+
+import com.google.common.base.Function;
+import com.google.common.base.Strings;
+import com.google.common.collect.Lists;
+import com.google.gerrit.entities.Account;
+import com.google.gerrit.entities.Project;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.annotations.RequiresCapability;
+import com.google.gerrit.extensions.common.AccountInfo;
+import com.google.gerrit.extensions.restapi.AuthException;
+import com.google.gerrit.extensions.restapi.BadRequestException;
+import com.google.gerrit.extensions.restapi.IdString;
+import com.google.gerrit.extensions.restapi.MethodNotAllowedException;
+import com.google.gerrit.extensions.restapi.Response;
+import com.google.gerrit.extensions.restapi.RestApiException;
+import com.google.gerrit.extensions.restapi.RestCollectionCreateView;
+import com.google.gerrit.server.CurrentUser;
+import com.google.gerrit.server.GerritPersonIdent;
+import com.google.gerrit.server.IdentifiedUser;
+import com.google.gerrit.server.account.AccountLoader;
+import com.google.gerrit.server.account.AccountResolver;
+import com.google.gerrit.server.account.AccountResolver.UnresolvableAccountException;
+import com.google.gerrit.server.config.ConfigResource;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.gerrit.server.git.meta.MetaDataUpdate;
+import com.google.gerrit.server.group.GroupResolver;
+import com.google.gerrit.server.permissions.PermissionBackend;
+import com.google.gerrit.server.permissions.PermissionBackendException;
+import com.google.gerrit.server.project.ProjectCache;
+import com.google.gerrit.server.project.ProjectLevelConfig;
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.googlesource.gerrit.plugins.serviceuser.GetServiceUser.ServiceUserInfo;
+import com.googlesource.gerrit.plugins.serviceuser.RegisterServiceUser.Input;
+import java.io.IOException;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.Config;
+import org.eclipse.jgit.lib.PersonIdent;
+
+@RequiresCapability(CreateServiceUserCapability.ID)
+@Singleton
+class RegisterServiceUser
+    implements RestCollectionCreateView<ConfigResource, ServiceUserResource, Input> {
+
+  static class Input {
+    String username;
+    String creator;
+    String owner;
+  }
+
+  private final AccountResolver accountResolver;
+  private final GroupResolver groupResolver;
+  private final PluginConfig cfg;
+  private final List<String> blockedNames;
+  private final Provider<CurrentUser> userProvider;
+  private final MetaDataUpdate.User metaDataUpdateFactory;
+  private final Project.NameKey allProjects;
+  private final ProjectLevelConfig storage;
+  private final DateFormat rfc2822DateFormatter;
+  private final AccountLoader.Factory accountLoader;
+  private final PermissionBackend permissionBackend;
+
+  @Inject
+  RegisterServiceUser(
+      AccountResolver accountResolver,
+      GroupResolver groupResolver,
+      PluginConfigFactory cfgFactory,
+      @PluginName String pluginName,
+      Provider<CurrentUser> userProvider,
+      @GerritPersonIdent PersonIdent gerritIdent,
+      MetaDataUpdate.User metaDataUpdateFactory,
+      ProjectCache projectCache,
+      AccountLoader.Factory accountLoader,
+      PermissionBackend permissionBackend) {
+    this.accountResolver = accountResolver;
+    this.groupResolver = groupResolver;
+    this.cfg = cfgFactory.getFromGerritConfig(pluginName);
+    this.blockedNames =
+        Lists.transform(
+            Arrays.asList(cfg.getStringList("block")),
+            new Function<String, String>() {
+              @Override
+              public String apply(String blockedName) {
+                return blockedName.toLowerCase();
+              }
+            });
+    this.userProvider = userProvider;
+    this.metaDataUpdateFactory = metaDataUpdateFactory;
+    this.storage = projectCache.getAllProjects().getConfig(pluginName + ".db");
+    this.allProjects = projectCache.getAllProjects().getProject().getNameKey();
+    this.rfc2822DateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
+    this.rfc2822DateFormatter.setCalendar(
+        Calendar.getInstance(gerritIdent.getTimeZone(), Locale.US));
+    this.accountLoader = accountLoader;
+    this.permissionBackend = permissionBackend;
+  }
+
+  @Override
+  public Response<ServiceUserInfo> apply(ConfigResource parentResource, IdString id, Input input)
+      throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
+    CurrentUser requestingUser = userProvider.get();
+    if (requestingUser == null || !requestingUser.isIdentifiedUser()) {
+      throw new AuthException("authentication required");
+    }
+
+    if (input == null) {
+      input = new Input();
+    }
+
+    IdentifiedUser user;
+    try {
+      user = accountResolver.resolve(input.username).asUniqueUser();
+    } catch (UnresolvableAccountException e) {
+      throw new BadRequestException("Username does not exist");
+    }
+
+    if (!requestingUser.getAccountId().equals(user.getAccountId())
+        && !permissionBackend.user(requestingUser).testOrFalse(ADMINISTRATE_SERVER)) {
+      throw new MethodNotAllowedException("Forbidden");
+    }
+
+    Config db = storage.get();
+    if (db.getSubsections(USER).contains(input.username)) {
+      return Response.none();
+    }
+
+    if (blockedNames.contains(input.username.toLowerCase())) {
+      throw new BadRequestException(
+          "The username '" + input.username + "' is not allowed as name for service users.");
+    }
+
+    String creator;
+    Account.Id creatorId;
+    if (Strings.isNullOrEmpty(input.creator)) {
+      creator = requestingUser.getUserName().orElse(null);
+      creatorId = requestingUser.asIdentifiedUser().getAccountId();
+    } else {
+      creator = input.creator;
+      creatorId = accountResolver.resolve(input.creator).asUniqueUser().getAccountId();
+    }
+    String creationDate = rfc2822DateFormatter.format(new Date());
+
+    String owner = null;
+    if (!Strings.isNullOrEmpty(input.owner)) {
+      try {
+        owner = groupResolver.parse(input.owner).getGroupUUID().toString();
+      } catch (UnresolvableAccountException e) {
+        throw new BadRequestException("The group '" + input.owner + "' does not exist");
+      }
+    }
+
+    db.setInt(USER, input.username, KEY_CREATOR_ID, creatorId.get());
+    if (creator != null) {
+      db.setString(USER, input.username, KEY_CREATED_BY, creator);
+    }
+    if (owner != null) {
+      db.setString(USER, input.username, KEY_OWNER, owner);
+    }
+    db.setString(USER, input.username, KEY_CREATED_AT, creationDate);
+
+    MetaDataUpdate md = metaDataUpdateFactory.create(allProjects);
+    md.setMessage("Create service user '" + input.username + "'\n");
+    storage.commit(md);
+
+    ServiceUserInfo info = new ServiceUserInfo(new AccountInfo(user.getAccountId().get()));
+    AccountLoader al = accountLoader.create(true);
+    info.createdBy = al.get(creatorId);
+    al.fill();
+    info.createdAt = creationDate;
+    return Response.created(info);
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/serviceuser/RegisterServiceUserCommand.java b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/RegisterServiceUserCommand.java
new file mode 100644
index 0000000..fb8503c
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/RegisterServiceUserCommand.java
@@ -0,0 +1,67 @@
+// Copyright (C) 2021 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.googlesource.gerrit.plugins.serviceuser;
+
+import com.google.gerrit.extensions.annotations.RequiresCapability;
+import com.google.gerrit.extensions.restapi.IdString;
+import com.google.gerrit.extensions.restapi.RestApiException;
+import com.google.gerrit.server.config.ConfigResource;
+import com.google.gerrit.server.permissions.PermissionBackendException;
+import com.google.gerrit.sshd.CommandMetaData;
+import com.google.gerrit.sshd.SshCommand;
+import com.google.inject.Inject;
+import java.io.IOException;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.kohsuke.args4j.Argument;
+import org.kohsuke.args4j.Option;
+
+@RequiresCapability(CreateServiceUserCapability.ID)
+@CommandMetaData(name = "register", description = "Register Service User")
+class RegisterServiceUserCommand extends SshCommand {
+
+  @Argument(index = 0, required = true, metaVar = "USERNAME", usage = "name of the service user")
+  private String username;
+
+  @Option(
+      name = "--creator",
+      required = false,
+      metaVar = "CREATOR",
+      usage = "name of the creator of the service user")
+  private String creator;
+
+  @Option(
+      name = "--owner",
+      required = false,
+      metaVar = "OWNER",
+      usage = "group that owns the service user")
+  private String owner;
+
+  @Inject private RegisterServiceUser registerServiceUser;
+
+  @Override
+  protected void run()
+      throws IOException, UnloggedFailure, ConfigInvalidException, PermissionBackendException {
+    RegisterServiceUser.Input input = new RegisterServiceUser.Input();
+    input.username = username;
+    input.creator = creator;
+    input.owner = owner;
+
+    try {
+      registerServiceUser.apply(new ConfigResource(), IdString.fromDecoded(username), input);
+    } catch (RestApiException e) {
+      throw die(e.getMessage());
+    }
+  }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/serviceuser/SshModule.java b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/SshModule.java
index f775e4c..40a1509 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/serviceuser/SshModule.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/serviceuser/SshModule.java
@@ -21,5 +21,6 @@
   @Override
   protected void configureCommands() {
     command(CreateServiceUserCommand.class);
+    command(RegisterServiceUserCommand.class);
   }
 }
diff --git a/src/main/resources/Documentation/cmd-register.md b/src/main/resources/Documentation/cmd-register.md
new file mode 100644
index 0000000..3378a2c
--- /dev/null
+++ b/src/main/resources/Documentation/cmd-register.md
@@ -0,0 +1,50 @@
+@PLUGIN@ register
+=================
+
+NAME
+----
+@PLUGIN@ register - Registers an existing user as a service user
+
+SYNOPSIS
+--------
+```
+ssh -p @SSH_PORT@ @SSH_HOST@ @PLUGIN@ register
+  --creator <CREATOR>
+  --owner <OWNER>
+  <USERNAME>
+```
+
+DESCRIPTION
+-----------
+Registers an existing user as a service user.
+
+ACCESS
+------
+Caller must be a member of a group that is granted the
+'Create Service User' capability (provided by this plugin) or the
+'Administrate Server' capability. If not possessing the 'Administrate
+Server' capability, the user to be registered as a service user must
+also be the caller.
+
+SCRIPTING
+---------
+This command is intended to be used in scripts.
+
+OPTIONS
+-------
+
+`--creator`
+:   Username of the user that will be set as the creator of the
+    serviceuser. Defaults to the caller.
+
+`--owner`
+:   ID or name of the group that will own the service user. Defaults
+    to no owner group being set.
+
+EXAMPLES
+--------
+Register a service user:
+
+```
+  $ ssh -p @SSH_PORT@ @SSH_HOST@ @PLUGIN@ register --creator admin --owner Administrators username
+```