Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HLRC: Add get users action #36332

Merged
merged 15 commits into from
Dec 13, 2018
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
import org.elasticsearch.client.security.GetRolesResponse;
import org.elasticsearch.client.security.GetSslCertificatesRequest;
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.GetUsersResponse;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.HasPrivilegesResponse;
import org.elasticsearch.client.security.InvalidateTokenRequest;
Expand Down Expand Up @@ -79,6 +81,33 @@ public final class SecurityClient {
this.restHighLevelClient = restHighLevelClient;
}

/**
* Get a user, or list of users, in the native realm synchronously.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-user.html">
* the docs</a> for more information.
* @param request the request with the user's name
* @param options the request options (e.g., headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response from the get users call
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public GetUsersResponse getUsers(GetUsersRequest request, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, SecurityRequestConverters::getUsers, options,
GetUsersResponse::fromXContent, emptySet());
}

/**
* Get a user, or list of users, in the native realm asynchronously.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-get-user.html">
* the docs</a> for more information.
* @param request the request with the user's name
* @param options the request options (e.g., headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
*/
public void getUsersAsync(GetUsersRequest request, RequestOptions options, ActionListener<GetUsersResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(request, SecurityRequestConverters::getUsers, options,
GetUsersResponse::fromXContent, listener, emptySet());
}

/**
* Create/update a user in the native realm synchronously.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-users.html">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.PutPrivilegesRequest;
Expand Down Expand Up @@ -67,6 +68,15 @@ static Request changePassword(ChangePasswordRequest changePasswordRequest) throw
return request;
}

static Request getUsers(GetUsersRequest getUsersRequest) {
RequestConverters.EndpointBuilder builder = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_xpack/security/user");
nknize marked this conversation as resolved.
Show resolved Hide resolved
if (getUsersRequest.getUsernames().size() > 0) {
builder.addPathPart(Strings.collectionToCommaDelimitedString(getUsersRequest.getUsernames()));
}
return new Request(HttpGet.METHOD_NAME, builder.build());
}

static Request putUser(PutUserRequest putUserRequest) throws IOException {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_security/user")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.client.security;

import org.elasticsearch.client.Validatable;
import org.elasticsearch.common.util.set.Sets;

import java.util.Collections;
import java.util.Objects;
import java.util.Set;

/**
* Request object to retrieve users from the native realm
*/
public class GetUsersRequest implements Validatable {
private final Set<String> usernames;

public GetUsersRequest(final String... usernames) {
if (usernames != null) {
this.usernames = Collections.unmodifiableSet(Sets.newHashSet(usernames));
} else {
this.usernames = Collections.emptySet();
}
}

public Set<String> getUsernames() {
return usernames;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GetUsersRequest)) return false;
GetUsersRequest that = (GetUsersRequest) o;
return Objects.equals(usernames, that.usernames);
}

@Override
public int hashCode() {
return Objects.hash(usernames);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.client.security;

import org.elasticsearch.client.security.user.User;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParser.Token;
import org.elasticsearch.common.xcontent.XContentParserUtils;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg;

/**
* Response when requesting zero or more users.
* Returns a List of {@link User} objects
*/
public class GetUsersResponse {
private final Set<User> users;
private final Set<User> enabledUsers;

public GetUsersResponse(Set<User> users, Set<User> enabledUsers) {
this.users = Collections.unmodifiableSet(users);
this.enabledUsers = Collections.unmodifiableSet(enabledUsers);
}

public Set<User> getUsers() {
return users;
}

public Set<User> getEnabledUsers() {
return enabledUsers;
}

public static GetUsersResponse fromXContent(XContentParser parser) throws IOException {
XContentParserUtils.ensureExpectedToken(Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
final Set<User> users = new HashSet<>();
final Set<User> enabledUsers = new HashSet<>();
Token token;
while ((token = parser.nextToken()) != Token.END_OBJECT) {
XContentParserUtils.ensureExpectedToken(Token.FIELD_NAME, token, parser::getTokenLocation);
ParsedUser parsedUser = USER_PARSER.parse(parser, parser.currentName());
users.add(parsedUser.user);
if (parsedUser.enabled) {
enabledUsers.add(parsedUser.user);
}
}
return new GetUsersResponse(users, enabledUsers);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GetUsersResponse)) return false;
GetUsersResponse that = (GetUsersResponse) o;
return Objects.equals(users, that.users);
}

@Override
public int hashCode() {
return Objects.hash(users);
}

public static final ParseField USERNAME = new ParseField("username");
public static final ParseField ROLES = new ParseField("roles");
public static final ParseField FULL_NAME = new ParseField("full_name");
public static final ParseField EMAIL = new ParseField("email");
public static final ParseField METADATA = new ParseField("metadata");
public static final ParseField ENABLED = new ParseField("enabled");

@SuppressWarnings("unchecked")
public static final ConstructingObjectParser<ParsedUser, String> USER_PARSER = new ConstructingObjectParser<>("user_info",
(constructorObjects) -> {
int i = 0;
final String username = (String) constructorObjects[i++];
final Collection<String> roles = (Collection<String>) constructorObjects[i++];
final Map<String, Object> metadata = (Map<String, Object>) constructorObjects[i++];
final Boolean enabled = (Boolean) constructorObjects[i++];
final String fullName = (String) constructorObjects[i++];
final String email = (String) constructorObjects[i++];
return new ParsedUser(username, roles, metadata, enabled, fullName, email);
});

static {
USER_PARSER.declareString(constructorArg(), USERNAME);
USER_PARSER.declareStringArray(constructorArg(), ROLES);
USER_PARSER.declareObject(constructorArg(), (parser, c) -> parser.map(), METADATA);
USER_PARSER.declareBoolean(constructorArg(), ENABLED);
USER_PARSER.declareStringOrNull(optionalConstructorArg(), FULL_NAME);
USER_PARSER.declareStringOrNull(optionalConstructorArg(), EMAIL);
}

protected static final class ParsedUser {
protected User user;
protected boolean enabled;

public ParsedUser(String username, Collection<String> roles, Map<String, Object> metadata, Boolean enabled, @Nullable String fullName,
@Nullable String email) {
String checkedUsername = username = Objects.requireNonNull(username, "`username` is required, cannot be null");
Collection<String> checkedRoles = Collections.unmodifiableSet(new HashSet<>(
Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")));
Map<String, Object> checkedMetadata = Collections
.unmodifiableMap(Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead."));
this.user = new User(checkedUsername, checkedRoles, checkedMetadata, fullName, email);
this.enabled = enabled;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import java.util.Objects;
import java.util.Set;


/**
* A user to be utilized with security APIs.
* Can be an existing authenticated user or it can be a new user to be enrolled to the native realm.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import org.elasticsearch.client.security.DeleteUserResponse;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.GetRolesResponse;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.GetUsersResponse;
import org.elasticsearch.client.security.PutRoleRequest;
import org.elasticsearch.client.security.PutRoleResponse;
import org.elasticsearch.client.security.PutUserRequest;
Expand All @@ -42,13 +44,15 @@
import org.elasticsearch.client.security.user.privileges.Role;
import org.elasticsearch.common.CharArrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.contains;
Expand Down Expand Up @@ -89,6 +93,15 @@ public void testAuthenticate() throws Exception {
assertThat(authenticateResponse.getUser(), is(putUserRequest.getUser()));
assertThat(authenticateResponse.enabled(), is(true));

// get user
final GetUsersRequest getUsersRequest =
new GetUsersRequest(putUserRequest.getUser().getUsername());
final GetUsersResponse getUsersResponse =
execute(getUsersRequest, securityClient::getUsers, securityClient::getUsersAsync);
ArrayList<User> usrs = new ArrayList<>();
usrs.addAll(getUsersResponse.getUsers());
nknize marked this conversation as resolved.
Show resolved Hide resolved
assertThat(usrs.get(0), is(putUserRequest.getUser()));

// delete user
final DeleteUserRequest deleteUserRequest =
new DeleteUserRequest(putUserRequest.getUser().getUsername(), putUserRequest.getRefreshPolicy());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.PutPrivilegesRequest;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutRoleRequest;
Expand Down Expand Up @@ -101,6 +102,19 @@ public void testDeleteUser() {
assertNull(request.getEntity());
}

public void testGetUsers() {
final String[] users = new String[] {"test"};
nknize marked this conversation as resolved.
Show resolved Hide resolved
GetUsersRequest getUsersRequest = new GetUsersRequest(users);
final RefreshPolicy refreshPolicy = randomFrom(RefreshPolicy.values());
final Map<String, String> expectedParams = getExpectedParamsFromRefreshPolicy(refreshPolicy);
Request request = SecurityRequestConverters.getUsers(getUsersRequest);
assertEquals(HttpGet.METHOD_NAME, request.getMethod());
assertEquals("/_xpack/security/user/test", request.getEndpoint());
nknize marked this conversation as resolved.
Show resolved Hide resolved
assertEquals(expectedParams, request.getParameters());
assertNull(request.getEntity());

nknize marked this conversation as resolved.
Show resolved Hide resolved
}

public void testPutRoleMapping() throws IOException {
final String username = randomAlphaOfLengthBetween(4, 7);
final String rolename = randomAlphaOfLengthBetween(4, 7);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.GetRolesResponse;
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.GetUsersResponse;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.HasPrivilegesResponse;
import org.elasticsearch.client.security.InvalidateTokenRequest;
Expand Down Expand Up @@ -106,6 +108,17 @@

public class SecurityDocumentationIT extends ESRestHighLevelClientTestCase {

public void testGetUsers() throws Exception {
RestHighLevelClient client = highLevelClient();
addUser(client, "testUser", "testPassword");

{
GetUsersRequest getUsersRequest = new GetUsersRequest();
GetUsersResponse getUsersResponse = client.security().getUsers(getUsersRequest, RequestOptions.DEFAULT);
assertNotNull(getUsersResponse.getUsers());
}
}

nknize marked this conversation as resolved.
Show resolved Hide resolved
public void testPutUser() throws Exception {
RestHighLevelClient client = highLevelClient();

Expand Down
Loading