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 @@ -75,6 +77,34 @@ 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 nuser's name
nknize marked this conversation as resolved.
Show resolved Hide resolved
* @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 nuser's name
nknize marked this conversation as resolved.
Show resolved Hide resolved
* @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 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 @@ -32,6 +32,7 @@
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.DeleteUserRequest;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.PutRoleMappingRequest;
Expand Down Expand Up @@ -65,6 +66,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("_xpack/security/user")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public final class AuthenticateResponse {
private static final ConstructingObjectParser<AuthenticateResponse, Void> PARSER = new ConstructingObjectParser<>(
"client_security_authenticate_response",
a -> new AuthenticateResponse(new User((String) a[0], ((List<String>) a[1]), (Map<String, Object>) a[2],
(String) a[3], (String) a[4]), (Boolean) a[5], (RealmInfo) a[6], (RealmInfo) a[7]));
(Boolean) a[5], (String) a[3], (String) a[4]), (Boolean) a[5], (RealmInfo) a[6], (RealmInfo) a[7]));
static {
final ConstructingObjectParser<RealmInfo, Void> realmInfoParser = new ConstructingObjectParser<>("realm_info",
a -> new RealmInfo((String) a[0], (String) a[1]));
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,70 @@
/*
* 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.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParser.Token;
import org.elasticsearch.common.xcontent.XContentParserUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
* Response when requesting zero or more users.
* Returns a List of {@link User} objects
*/
public class GetUsersResponse {
private final List<User> users;
nknize marked this conversation as resolved.
Show resolved Hide resolved

public GetUsersResponse(List<User> users) {
this.users = Collections.unmodifiableList(users);
}

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

public static GetUsersResponse fromXContent(XContentParser parser) throws IOException {
XContentParserUtils.ensureExpectedToken(Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
final List<User> users = new ArrayList<>();
Token token;
while ((token = parser.nextToken()) != Token.END_OBJECT) {
XContentParserUtils.ensureExpectedToken(Token.FIELD_NAME, token, parser::getTokenLocation);
users.add(User.PARSER.parse(parser, parser.currentName()));
}
return new GetUsersResponse(users);
}

@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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
package org.elasticsearch.client.security.user;

import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;

import java.util.Collection;
import java.util.Collections;
Expand All @@ -29,16 +31,48 @@
import java.util.Objects;
import java.util.Set;

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

/**
* 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.
*/
public final class User {

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<User, String> 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 User(username, roles, metadata, enabled, fullName, email);
});

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

private final String username;
private final Set<String> roles;
private final Map<String, Object> metadata;
private final boolean enabled;
@Nullable private final String fullName;
@Nullable private final String email;

Expand All @@ -51,13 +85,14 @@ public final class User {
* @param fullName the full name of the user that may be used for display purposes
* @param email the email address of the user
*/
public User(String username, Collection<String> roles, Map<String, Object> metadata, @Nullable String fullName,
public User(String username, Collection<String> roles, Map<String, Object> metadata, Boolean enabled, @Nullable String fullName,
@Nullable String email) {
this.username = username = Objects.requireNonNull(username, "`username` is required, cannot be null");
this.roles = Collections.unmodifiableSet(new HashSet<>(
Objects.requireNonNull(roles, "`roles` is required, cannot be null. Pass an empty Collection instead.")));
this.metadata = Collections
.unmodifiableMap(Objects.requireNonNull(metadata, "`metadata` is required, cannot be null. Pass an empty map instead."));
this.enabled = enabled.booleanValue();
this.fullName = fullName;
this.email = email;
}
Expand All @@ -69,7 +104,7 @@ public User(String username, Collection<String> roles, Map<String, Object> metad
* @param roles the roles that this user is assigned
*/
public User(String username, Collection<String> roles) {
this(username, roles, Collections.emptyMap(), null, null);
this(username, roles, Collections.emptyMap(), true, null, null);
}

/**
Expand All @@ -96,6 +131,11 @@ public Map<String, Object> getMetadata() {
return metadata;
}

/** @return Whether or not this user is enabled */
public boolean getEnabled() {
return enabled;
}

/**
* @return The full name of this user. May be {@code null}.
*/
Expand All @@ -116,6 +156,7 @@ public String toString() {
sb.append("User[username=").append(username);
sb.append(",roles=[").append(Strings.collectionToCommaDelimitedString(roles)).append("]");
sb.append(",metadata=").append(metadata);
sb.append(",enabled=").append(enabled);
sb.append(",fullName=").append(fullName);
sb.append(",email=").append(email);
sb.append("]");
Expand All @@ -130,13 +171,14 @@ public boolean equals(Object o) {
return Objects.equals(username, that.username)
&& Objects.equals(roles, that.roles)
&& Objects.equals(metadata, that.metadata)
&& enabled == that.enabled
&& Objects.equals(fullName, that.fullName)
&& Objects.equals(email, that.email);
}

@Override
public int hashCode() {
return Objects.hash(username, roles, metadata, fullName, email);
return Objects.hash(username, roles, metadata, enabled, fullName, email);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.elasticsearch.client.security.AuthenticateResponse;
import org.elasticsearch.client.security.DeleteUserRequest;
import org.elasticsearch.client.security.DeleteUserResponse;
import org.elasticsearch.client.security.GetUsersRequest;
import org.elasticsearch.client.security.GetUsersResponse;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.PutUserResponse;
import org.elasticsearch.client.security.RefreshPolicy;
Expand All @@ -36,6 +38,7 @@
import java.util.List;
import java.util.Map;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.containsString;

Expand Down Expand Up @@ -75,6 +78,13 @@ 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);
assertThat(getUsersResponse.getUsers().get(0), is(putUserRequest.getUser()));

// delete user
final DeleteUserRequest deleteUserRequest =
new DeleteUserRequest(putUserRequest.getUser().getUsername(), putUserRequest.getRefreshPolicy());
Expand Down Expand Up @@ -103,6 +113,7 @@ private static User randomUser(String username) {
final List<String> roles = Arrays.asList(generateRandomStringArray(3, 3, false, true));
final String fullName = randomFrom(random(), null, randomAlphaOfLengthBetween(0, 3));
final String email = randomFrom(random(), null, randomAlphaOfLengthBetween(0, 3));
final boolean enabled = randomBoolean();
final Map<String, Object> metadata;
metadata = new HashMap<>();
if (randomBoolean()) {
Expand All @@ -115,7 +126,7 @@ private static User randomUser(String username) {
} else {
metadata.put("string_list", Arrays.asList(generateRandomStringArray(4, 4, false, true)));
}
return new User(username, roles, metadata, fullName, email);
return new User(username, roles, metadata, enabled, fullName, email);
}

private static PutUserRequest randomPutUserRequest(boolean enabled) {
Expand Down
Loading