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@c1f4a961fd
This commit is contained in:
Alexander Reelsen 2014-08-28 15:10:24 +02:00
parent 52ba1ceff3
commit c9379b3875
2 changed files with 23 additions and 1 deletions

View File

@ -323,7 +323,11 @@ public class ESUsersTool extends CliTool {
Map<String, String[]> 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;

View File

@ -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<String> 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");