From c9379b38755f800e6665f087161f6a19fd05c29c Mon Sep 17 00:00:00 2001 From: Alexander Reelsen Date: Thu, 28 Aug 2014 15:10:24 +0200 Subject: [PATCH] CliTool: Do not leave invalid lines in roles file Removing all roles from a user result in an invalid line left in the roles file. This commit simply removes the user from the roles file in that case. Original commit: elastic/x-pack-elasticsearch@c1f4a961fded11aeab1ddedf6d2b4df67a037fec --- .../shield/authc/esusers/tool/ESUsersTool.java | 6 +++++- .../authc/esusers/tool/ESUsersToolTests.java | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) 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");