Unset global capabilities after use in acceptance tests

We would like to reuse a single server per acceptance tests, which
means changes made to All-Projects need to be reverted before the next
test if not avoided entirely. Global capabilities may only be set on
All-Projects, so we need to revert them.

Consolidate various methods for allowing/removing capabilities into
AbstractDaemonTest.

Tweak Util.allow to set default ranges for those capabilities that
have them, as CapabilitiesIT was already doing.

Change-Id: I27cd2b61dc6b84e718b9de765b51bf50fa62c6c1
diff --git a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/AbstractDaemonTest.java b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/AbstractDaemonTest.java
index 6971d02..2c03c26 100644
--- a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/AbstractDaemonTest.java
+++ b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/AbstractDaemonTest.java
@@ -397,10 +397,31 @@
     saveProjectConfig(project, cfg);
   }
 
-  protected void allowGlobalCapability(String capabilityName,
-      AccountGroup.UUID id) throws Exception {
+  protected void allowGlobalCapabilities(AccountGroup.UUID id,
+      String... capabilityNames) throws Exception {
+    allowGlobalCapabilities(id, Arrays.asList(capabilityNames));
+  }
+
+  protected void allowGlobalCapabilities(AccountGroup.UUID id,
+      Iterable<String> capabilityNames) throws Exception {
     ProjectConfig cfg = projectCache.checkedGet(allProjects).getConfig();
-    Util.allow(cfg, capabilityName, id);
+    for (String capabilityName : capabilityNames) {
+      Util.allow(cfg, capabilityName, id);
+    }
+    saveProjectConfig(allProjects, cfg);
+  }
+
+  protected void removeGlobalCapabilities(AccountGroup.UUID id,
+      String... capabilityNames) throws Exception {
+    removeGlobalCapabilities(id, Arrays.asList(capabilityNames));
+  }
+
+  protected void removeGlobalCapabilities(AccountGroup.UUID id,
+      Iterable<String> capabilityNames) throws Exception {
+    ProjectConfig cfg = projectCache.checkedGet(allProjects).getConfig();
+    for (String capabilityName : capabilityNames) {
+      Util.remove(cfg, capabilityName, id);
+    }
     saveProjectConfig(allProjects, cfg);
   }
 
diff --git a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/VisibleRefFilterIT.java b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/VisibleRefFilterIT.java
index e73d41f..f018b9b6 100644
--- a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/VisibleRefFilterIT.java
+++ b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/git/VisibleRefFilterIT.java
@@ -209,31 +209,35 @@
 
   @Test
   public void subsetOfRefsVisibleWithAccessDatabase() throws Exception {
-    deny(Permission.READ, REGISTERED_USERS, "refs/heads/master");
-    allow(Permission.READ, REGISTERED_USERS, "refs/heads/branch");
-    allowGlobalCapability(GlobalCapability.ACCESS_DATABASE, REGISTERED_USERS);
+    allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.ACCESS_DATABASE);
+    try {
+      deny(Permission.READ, REGISTERED_USERS, "refs/heads/master");
+      allow(Permission.READ, REGISTERED_USERS, "refs/heads/branch");
 
-    Change c1 = db.changes().get(new Change.Id(1));
-    PatchSet ps1 = db.patchSets().get(new PatchSet.Id(c1.getId(), 1));
-    setApiUser(admin);
-    editModifier.createEdit(c1, ps1);
-    setApiUser(user);
-    editModifier.createEdit(c1, ps1);
+      Change c1 = db.changes().get(new Change.Id(1));
+      PatchSet ps1 = db.patchSets().get(new PatchSet.Id(c1.getId(), 1));
+      setApiUser(admin);
+      editModifier.createEdit(c1, ps1);
+      setApiUser(user);
+      editModifier.createEdit(c1, ps1);
 
-    assertRefs(
-        // Change 1 is visible due to accessDatabase capability, even though
-        // refs/heads/master is not.
-        "refs/changes/01/1/1",
-        "refs/changes/01/1/meta",
-        "refs/changes/02/2/1",
-        "refs/changes/02/2/meta",
-        "refs/heads/branch",
-        "refs/tags/branch-tag",
-        // See comment in subsetOfBranchesVisibleNotIncludingHead.
-        "refs/tags/master-tag",
-        // All edits are visible due to accessDatabase capability.
-        "refs/users/00/1000000/edit-1/1",
-        "refs/users/01/1000001/edit-1/1");
+      assertRefs(
+          // Change 1 is visible due to accessDatabase capability, even though
+          // refs/heads/master is not.
+          "refs/changes/01/1/1",
+          "refs/changes/01/1/meta",
+          "refs/changes/02/2/1",
+          "refs/changes/02/2/meta",
+          "refs/heads/branch",
+          "refs/tags/branch-tag",
+          // See comment in subsetOfBranchesVisibleNotIncludingHead.
+          "refs/tags/master-tag",
+          // All edits are visible due to accessDatabase capability.
+          "refs/users/00/1000000/edit-1/1",
+          "refs/users/01/1000001/edit-1/1");
+    } finally {
+      removeGlobalCapabilities(REGISTERED_USERS, GlobalCapability.ACCESS_DATABASE);
+    }
   }
 
   /**
diff --git a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/account/CapabilitiesIT.java b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/account/CapabilitiesIT.java
index 6ce96ee..3e7c2bf 100644
--- a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/account/CapabilitiesIT.java
+++ b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/account/CapabilitiesIT.java
@@ -24,51 +24,56 @@
 import static com.google.gerrit.common.data.GlobalCapability.PRIORITY;
 import static com.google.gerrit.common.data.GlobalCapability.QUERY_LIMIT;
 import static com.google.gerrit.common.data.GlobalCapability.RUN_AS;
+import static com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS;
 
+import com.google.common.base.Predicate;
+import com.google.common.collect.Iterables;
 import com.google.gerrit.acceptance.AbstractDaemonTest;
 import com.google.gerrit.acceptance.RestResponse;
-import com.google.gerrit.common.data.AccessSection;
 import com.google.gerrit.common.data.GlobalCapability;
-import com.google.gerrit.common.data.Permission;
-import com.google.gerrit.common.data.PermissionRange;
-import com.google.gerrit.common.data.PermissionRule;
-import com.google.gerrit.server.git.MetaDataUpdate;
-import com.google.gerrit.server.git.ProjectConfig;
-import com.google.gerrit.server.group.SystemGroupBackend;
 import com.google.gson.Gson;
 import com.google.gson.reflect.TypeToken;
 
 import org.apache.http.HttpStatus;
-import org.eclipse.jgit.errors.ConfigInvalidException;
 import org.junit.Test;
 
-import java.io.IOException;
-
 public class CapabilitiesIT extends AbstractDaemonTest {
 
   @Test
   public void testCapabilitiesUser() throws Exception {
-    grantAllCapabilities();
-    RestResponse r =
-        userSession.get("/accounts/self/capabilities");
-    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
-    CapabilityInfo info = (new Gson()).fromJson(r.getReader(),
-        new TypeToken<CapabilityInfo>() {}.getType());
-    for (String c : GlobalCapability.getAllNames()) {
-      if (ADMINISTRATE_SERVER.equals(c)) {
-        assertThat(info.administrateServer).isFalse();
-      } else if (BATCH_CHANGES_LIMIT.equals(c)) {
-        assertThat(info.batchChangesLimit.min).isEqualTo((short) 0);
-        assertThat(info.batchChangesLimit.max).isEqualTo((short) DEFAULT_MAX_BATCH_CHANGES_LIMIT);
-      } else if (PRIORITY.equals(c)) {
-        assertThat(info.priority).isFalse();
-      } else if (QUERY_LIMIT.equals(c)) {
-        assertThat(info.queryLimit.min).isEqualTo((short) 0);
-        assertThat(info.queryLimit.max).isEqualTo((short) DEFAULT_MAX_QUERY_LIMIT);
-      } else {
-        assert_().withFailureMessage(String.format("capability %s was not granted", c))
-          .that((Boolean) CapabilityInfo.class.getField(c).get(info)).isTrue();
+    Iterable<String> all = Iterables.filter(GlobalCapability.getAllNames(),
+        new Predicate<String>() {
+          @Override
+          public boolean apply(String in) {
+            return !ADMINISTRATE_SERVER.equals(in) && !PRIORITY.equals(in);
+          }
+        });
+
+    allowGlobalCapabilities(REGISTERED_USERS, all);
+    try {
+      RestResponse r =
+          userSession.get("/accounts/self/capabilities");
+      assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
+      CapabilityInfo info = (new Gson()).fromJson(r.getReader(),
+          new TypeToken<CapabilityInfo>() {}.getType());
+      for (String c : GlobalCapability.getAllNames()) {
+        if (ADMINISTRATE_SERVER.equals(c)) {
+          assertThat(info.administrateServer).isFalse();
+        } else if (BATCH_CHANGES_LIMIT.equals(c)) {
+          assertThat(info.batchChangesLimit.min).isEqualTo((short) 0);
+          assertThat(info.batchChangesLimit.max).isEqualTo((short) DEFAULT_MAX_BATCH_CHANGES_LIMIT);
+        } else if (PRIORITY.equals(c)) {
+          assertThat(info.priority).isFalse();
+        } else if (QUERY_LIMIT.equals(c)) {
+          assertThat(info.queryLimit.min).isEqualTo((short) 0);
+          assertThat(info.queryLimit.max).isEqualTo((short) DEFAULT_MAX_QUERY_LIMIT);
+        } else {
+          assert_().withFailureMessage(String.format("capability %s was not granted", c))
+            .that((Boolean) CapabilityInfo.class.getField(c).get(info)).isTrue();
+        }
       }
+    } finally {
+      removeGlobalCapabilities(REGISTERED_USERS, all);
     }
   }
 
@@ -101,35 +106,4 @@
       }
     }
   }
-
-  /**
-   * Grant all global capabilities except ADMINISTRATE_SERVER and PRIORITY.
-   * Set the default ranges for range permissions.
-   */
-  private void grantAllCapabilities() throws IOException,
-      ConfigInvalidException {
-    MetaDataUpdate md = metaDataUpdateFactory.create(allProjects);
-    md.setMessage("Make super user");
-    ProjectConfig config = ProjectConfig.read(md);
-    AccessSection s = config.getAccessSection(
-        AccessSection.GLOBAL_CAPABILITIES);
-    for (String c : GlobalCapability.getAllNames()) {
-      if (ADMINISTRATE_SERVER.equals(c) || PRIORITY.equals(c)) {
-        continue;
-      }
-      Permission p = s.getPermission(c, true);
-      PermissionRule rule = new PermissionRule(
-          config.resolve(SystemGroupBackend.getGroup(
-              SystemGroupBackend.REGISTERED_USERS)));
-      if (GlobalCapability.hasRange(c)) {
-        PermissionRange.WithDefaults range = GlobalCapability.getRange(c);
-        if (range != null) {
-          rule.setRange(range.getDefaultMin(), range.getDefaultMax());
-        }
-      }
-      p.add(rule);
-    }
-    config.commit(md);
-    projectCache.evict(config.getProject());
-  }
 }
diff --git a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/change/SuggestReviewersIT.java b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/change/SuggestReviewersIT.java
index dbedb7c..3b8e4ef 100644
--- a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/change/SuggestReviewersIT.java
+++ b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/change/SuggestReviewersIT.java
@@ -149,7 +149,8 @@
         changeId, user2.fullName, 2);
     assertThat(reviewers).isEmpty();
 
-    grantCapability(GlobalCapability.VIEW_ALL_ACCOUNTS, group1);
+    allowGlobalCapabilities(group1.getGroupUUID(),
+        GlobalCapability.VIEW_ALL_ACCOUNTS);
     reviewers = suggestReviewers(new RestSession(server, user1),
         changeId, user2.fullName, 2);
     assertThat(reviewers).hasSize(1);
diff --git a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/CacheOperationsIT.java b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/CacheOperationsIT.java
index 06f2426..7e68a03 100644
--- a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/CacheOperationsIT.java
+++ b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/CacheOperationsIT.java
@@ -22,18 +22,12 @@
 import com.google.gerrit.acceptance.AbstractDaemonTest;
 import com.google.gerrit.acceptance.RestResponse;
 import com.google.gerrit.common.data.GlobalCapability;
-import com.google.gerrit.reviewdb.client.AccountGroup;
 import com.google.gerrit.server.config.ListCaches.CacheInfo;
 import com.google.gerrit.server.config.PostCaches;
-import com.google.gerrit.server.git.MetaDataUpdate;
-import com.google.gerrit.server.git.ProjectConfig;
-import com.google.gerrit.server.group.SystemGroupBackend;
-import com.google.gerrit.server.project.Util;
 
 import org.apache.http.HttpStatus;
 import org.junit.Test;
 
-import java.io.IOException;
 import java.util.Arrays;
 
 public class CacheOperationsIT extends AbstractDaemonTest {
@@ -123,30 +117,20 @@
 
   @Test
   public void flushWebSessions_Forbidden() throws Exception {
-    ProjectConfig cfg = projectCache.checkedGet(allProjects).getConfig();
-    AccountGroup.UUID registeredUsers =
-        SystemGroupBackend.getGroup(REGISTERED_USERS).getUUID();
-    Util.allow(cfg, GlobalCapability.VIEW_CACHES, registeredUsers);
-    Util.allow(cfg, GlobalCapability.FLUSH_CACHES, registeredUsers);
-    saveProjectConfig(cfg);
-
-    RestResponse r = userSession.post("/config/server/caches/",
-        new PostCaches.Input(FLUSH, Arrays.asList("projects")));
-    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
-    r.consume();
-
-    r = userSession.post("/config/server/caches/",
-        new PostCaches.Input(FLUSH, Arrays.asList("web_sessions")));
-    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_FORBIDDEN);
-  }
-
-  private void saveProjectConfig(ProjectConfig cfg) throws IOException {
-    MetaDataUpdate md = metaDataUpdateFactory.create(allProjects);
+    allowGlobalCapabilities(REGISTERED_USERS,
+        GlobalCapability.FLUSH_CACHES, GlobalCapability.VIEW_CACHES);
     try {
-      cfg.commit(md);
+      RestResponse r = userSession.post("/config/server/caches/",
+          new PostCaches.Input(FLUSH, Arrays.asList("projects")));
+      assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
+      r.consume();
+
+      r = userSession.post("/config/server/caches/",
+          new PostCaches.Input(FLUSH, Arrays.asList("web_sessions")));
+      assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_FORBIDDEN);
     } finally {
-      md.close();
+      removeGlobalCapabilities(REGISTERED_USERS,
+          GlobalCapability.FLUSH_CACHES, GlobalCapability.VIEW_CACHES);
     }
-    projectCache.evict(allProjects);
   }
 }
diff --git a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/FlushCacheIT.java b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/FlushCacheIT.java
index bfb93f1..bb63928 100644
--- a/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/FlushCacheIT.java
+++ b/gerrit-acceptance-tests/src/test/java/com/google/gerrit/acceptance/rest/config/FlushCacheIT.java
@@ -20,18 +20,11 @@
 import com.google.gerrit.acceptance.AbstractDaemonTest;
 import com.google.gerrit.acceptance.RestResponse;
 import com.google.gerrit.common.data.GlobalCapability;
-import com.google.gerrit.reviewdb.client.AccountGroup;
 import com.google.gerrit.server.config.ListCaches.CacheInfo;
-import com.google.gerrit.server.git.MetaDataUpdate;
-import com.google.gerrit.server.git.ProjectConfig;
-import com.google.gerrit.server.group.SystemGroupBackend;
-import com.google.gerrit.server.project.Util;
 
 import org.apache.http.HttpStatus;
 import org.junit.Test;
 
-import java.io.IOException;
-
 public class FlushCacheIT extends AbstractDaemonTest {
 
   @Test
@@ -75,28 +68,18 @@
 
   @Test
   public void flushWebSessionsCache_Forbidden() throws Exception {
-    ProjectConfig cfg = projectCache.checkedGet(allProjects).getConfig();
-    AccountGroup.UUID registeredUsers =
-        SystemGroupBackend.getGroup(REGISTERED_USERS).getUUID();
-    Util.allow(cfg, GlobalCapability.VIEW_CACHES, registeredUsers);
-    Util.allow(cfg, GlobalCapability.FLUSH_CACHES, registeredUsers);
-    saveProjectConfig(cfg);
-
-    RestResponse r = userSession.post("/config/server/caches/accounts/flush");
-    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
-    r.consume();
-
-    r = userSession.post("/config/server/caches/web_sessions/flush");
-    assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_FORBIDDEN);
-  }
-
-  private void saveProjectConfig(ProjectConfig cfg) throws IOException {
-    MetaDataUpdate md = metaDataUpdateFactory.create(allProjects);
+    allowGlobalCapabilities(REGISTERED_USERS,
+        GlobalCapability.VIEW_CACHES, GlobalCapability.FLUSH_CACHES);
     try {
-      cfg.commit(md);
+      RestResponse r = userSession.post("/config/server/caches/accounts/flush");
+      assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
+      r.consume();
+
+      r = userSession.post("/config/server/caches/web_sessions/flush");
+      assertThat(r.getStatusCode()).isEqualTo(HttpStatus.SC_FORBIDDEN);
     } finally {
-      md.close();
+      removeGlobalCapabilities(REGISTERED_USERS,
+          GlobalCapability.VIEW_CACHES, GlobalCapability.FLUSH_CACHES);
     }
-    projectCache.evict(allProjects);
   }
 }
diff --git a/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java b/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java
index 46223f1..24ee81e 100644
--- a/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java
+++ b/gerrit-server/src/test/java/com/google/gerrit/server/project/Util.java
@@ -21,9 +21,11 @@
 import com.google.common.cache.CacheBuilder;
 import com.google.common.collect.Lists;
 import com.google.gerrit.common.data.AccessSection;
+import com.google.gerrit.common.data.GlobalCapability;
 import com.google.gerrit.common.data.GroupReference;
 import com.google.gerrit.common.data.LabelType;
 import com.google.gerrit.common.data.LabelValue;
+import com.google.gerrit.common.data.PermissionRange;
 import com.google.gerrit.common.data.PermissionRule;
 import com.google.gerrit.reviewdb.client.AccountGroup;
 import com.google.gerrit.reviewdb.client.AccountProjectWatch;
@@ -138,6 +140,22 @@
     project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
         .getPermission(capabilityName, true)
         .add(rule);
+      if (GlobalCapability.hasRange(capabilityName)) {
+        PermissionRange.WithDefaults range =
+            GlobalCapability.getRange(capabilityName);
+        if (range != null) {
+          rule.setRange(range.getDefaultMin(), range.getDefaultMax());
+        }
+      }
+    return rule;
+  }
+
+  public static PermissionRule remove(ProjectConfig project,
+      String capabilityName, AccountGroup.UUID group) {
+    PermissionRule rule = newRule(project, group);
+    project.getAccessSection(AccessSection.GLOBAL_CAPABILITIES, true)
+        .getPermission(capabilityName, true)
+        .remove(rule);
     return rule;
   }