diff --git a/src/main/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersTool.java b/src/main/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersTool.java index 042f4f95b81..39fadea3163 100644 --- a/src/main/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersTool.java +++ b/src/main/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersTool.java @@ -323,7 +323,11 @@ public class ESUsersTool extends CliTool { Map userRolesToWrite = Maps.newHashMapWithExpectedSize(userRoles.size()); userRolesToWrite.putAll(userRoles); - userRolesToWrite.put(username, Sets.newLinkedHashSet(roles).toArray(new String[]{})); + if (roles.size() == 0) { + userRolesToWrite.remove(username); + } else { + userRolesToWrite.put(username, Sets.newLinkedHashSet(roles).toArray(new String[]{})); + } FileUserRolesStore.writeFile(userRolesToWrite, file); return ExitStatus.OK; diff --git a/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java b/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java index d35cc981a6c..4f05e6c8d9d 100644 --- a/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java +++ b/src/test/java/org/elasticsearch/shield/authc/esusers/tool/ESUsersToolTests.java @@ -419,6 +419,24 @@ public class ESUsersToolTests extends CliToolTestCase { assertThat(userRoles.get("user"), arrayContaining("user", "bar", "newrole")); } + @Test + public void testRoles_Cmd_removingLastRoleRemovesEntryFromRolesFile() throws Exception { + File usersFile = writeFile("admin:hash\nuser:hash"); + File usersRoleFile = writeFile("admin: admin\nuser:user,foo,bar\n"); + Settings settings = ImmutableSettings.builder() + .put("shield.authc.esusers.files.users", usersFile) + .put("shield.authc.esusers.files.users_roles", usersRoleFile) + .build(); + + ESUsersTool.Roles cmd = new ESUsersTool.Roles(new MockTerminal(), "user", Strings.EMPTY_ARRAY, new String[]{"user", "foo", "bar"}); + CliTool.ExitStatus status = execute(cmd, settings); + + assertThat(status, is(CliTool.ExitStatus.OK)); + + List usersRoleFileLines = Files.readLines(usersRoleFile, Charsets.UTF_8); + assertThat(usersRoleFileLines, not(hasItem(startsWith("user:")))); + } + @Test public void testRoles_Cmd_userNotFound() throws Exception { File usersFile = writeFile("admin:hash\nuser:hash");