Skip to content

Commit

Permalink
Merge remote-tracking branch 'elastic/master' into ccr-logstash-template
Browse files Browse the repository at this point in the history
* elastic/master:
  Remove deprecated `useDisMax` from MultiMatchQuery (elastic#36488)
  HLRC: Add get users action (elastic#36332)
  fix MultiValuesSourceFieldConfig toXContent (elastic#36525)
  Add ILM-specific security privileges (elastic#36493)
  Remove usages of `MockTcpTransport` from zen tests (elastic#36579)
  • Loading branch information
jasontedor committed Dec 13, 2018
2 parents cbaf83a + b33ff16 commit b7a26c7
Show file tree
Hide file tree
Showing 32 changed files with 876 additions and 110 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.GetUserPrivilegesRequest;
import org.elasticsearch.client.security.GetUserPrivilegesResponse;
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 @@ -81,6 +83,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("_security/user");
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 @@ -315,9 +315,11 @@ public static class ClusterPrivilegeName {
public static final String MANAGE_PIPELINE = "manage_pipeline";
public static final String MANAGE_CCR = "manage_ccr";
public static final String READ_CCR = "read_ccr";
public static final String MANAGE_ILM = "manage_ilm";
public static final String READ_ILM = "read_ilm";
public static final String[] ALL_ARRAY = new String[] { NONE, ALL, MONITOR, MONITOR_ML, MONITOR_WATCHER, MONITOR_ROLLUP, MANAGE,
MANAGE_ML, MANAGE_WATCHER, MANAGE_ROLLUP, MANAGE_INDEX_TEMPLATES, MANAGE_INGEST_PIPELINES, TRANSPORT_CLIENT,
MANAGE_SECURITY, MANAGE_SAML, MANAGE_TOKEN, MANAGE_PIPELINE, MANAGE_CCR, READ_CCR };
MANAGE_SECURITY, MANAGE_SAML, MANAGE_TOKEN, MANAGE_PIPELINE, MANAGE_CCR, READ_CCR, MANAGE_ILM, READ_ILM };
}

/**
Expand All @@ -338,8 +340,9 @@ public static class IndexPrivilegeName {
public static final String CREATE_INDEX = "create_index";
public static final String VIEW_INDEX_METADATA = "view_index_metadata";
public static final String MANAGE_FOLLOW_INDEX = "manage_follow_index";
public static final String MANAGE_ILM = "manage_ilm";
public static final String[] ALL_ARRAY = new String[] { NONE, ALL, READ, READ_CROSS, CREATE, INDEX, DELETE, WRITE, MONITOR, MANAGE,
DELETE_INDEX, CREATE_INDEX, VIEW_INDEX_METADATA, MANAGE_FOLLOW_INDEX };
DELETE_INDEX, CREATE_INDEX, VIEW_INDEX_METADATA, MANAGE_FOLLOW_INDEX, MANAGE_ILM };
}

}
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,6 +44,7 @@
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;
Expand Down Expand Up @@ -74,6 +77,22 @@ public void testPutUser() throws Exception {
highLevelClient().getLowLevelClient().performRequest(deleteUserRequest);
}

public void testGetUser() throws Exception {
final SecurityClient securityClient = highLevelClient().security();
// create user
final PutUserRequest putUserRequest = randomPutUserRequest(randomBoolean());
final PutUserResponse putUserResponse = execute(putUserRequest, securityClient::putUser, securityClient::putUserAsync);
// assert user created
assertThat(putUserResponse.isCreated(), is(true));
// get user
final GetUsersRequest getUsersRequest = new GetUsersRequest(putUserRequest.getUser().getUsername());
final GetUsersResponse getUsersResponse = execute(getUsersRequest, securityClient::getUsers, securityClient::getUsersAsync);
// assert user was correctly retrieved
ArrayList<User> users = new ArrayList<>();
users.addAll(getUsersResponse.getUsers());
assertThat(users.get(0), is(putUserRequest.getUser()));
}

public void testAuthenticate() throws Exception {
final SecurityClient securityClient = highLevelClient().security();
// test fixture: put enabled user
Expand All @@ -89,6 +108,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> users = new ArrayList<>();
users.addAll(getUsersResponse.getUsers());
assertThat(users.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,21 @@ public void testDeleteUser() {
assertNull(request.getEntity());
}

public void testGetUsers() {
final String[] users = randomArray(0, 5, String[]::new, () -> randomAlphaOfLength(5));
GetUsersRequest getUsersRequest = new GetUsersRequest(users);
Request request = SecurityRequestConverters.getUsers(getUsersRequest);
assertEquals(HttpGet.METHOD_NAME, request.getMethod());
if (users.length == 0) {
assertEquals("/_security/user", request.getEndpoint());
} else {
assertEquals("/_security/user/" + Strings.collectionToCommaDelimitedString(getUsersRequest.getUsernames()),
request.getEndpoint());
}
assertNull(request.getEntity());
assertEquals(Collections.emptyMap(), request.getParameters());
}

public void testPutRoleMapping() throws IOException {
final String username = randomAlphaOfLengthBetween(4, 7);
final String rolename = randomAlphaOfLengthBetween(4, 7);
Expand Down
Loading

0 comments on commit b7a26c7

Please sign in to comment.