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 support for put privileges API #35679

Merged
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
import org.elasticsearch.client.security.HasPrivilegesResponse;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.InvalidateTokenResponse;
import org.elasticsearch.client.security.PutPrivilegesRequest;
import org.elasticsearch.client.security.PutPrivilegesResponse;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutRoleMappingResponse;
import org.elasticsearch.client.security.PutUserRequest;
Expand Down Expand Up @@ -603,6 +605,38 @@ public void getPrivilegesAsync(final GetPrivilegesRequest request, final Request
options, GetPrivilegesResponse::fromXContent, listener, emptySet());
}

/**
* Create or update application privileges.
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-privileges.html">
* the docs</a> for more.
*
* @param request the request to create or update application privileges
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @return the response from the create or update application privileges call
* @throws IOException in case there is a problem sending the request or parsing back the response
*/
public PutPrivilegesResponse putPrivileges(final PutPrivilegesRequest request, final RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(request, SecurityRequestConverters::putPrivileges, options,
PutPrivilegesResponse::fromXContent, emptySet());
}

/**
* Asynchronously create or update application privileges.<br>
* See <a href=
* "https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-privileges.html">
* the docs</a> for more.
*
* @param request the request to create or update application privileges
* @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 putPrivilegesAsync(final PutPrivilegesRequest request, final RequestOptions options,
final ActionListener<PutPrivilegesResponse> listener) {
restHighLevelClient.performRequestAsyncAndParseEntity(request, SecurityRequestConverters::putPrivileges, options,
PutPrivilegesResponse::fromXContent, listener, emptySet());
}

/**
* Removes application privilege(s)
* See <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-delete-privilege.html">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,18 @@
import org.elasticsearch.client.security.ClearRolesCacheRequest;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.DeletePrivilegesRequest;
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.DeleteUserRequest;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.DisableUserRequest;
import org.elasticsearch.client.security.EnableUserRequest;
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.PutPrivilegesRequest;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.SetUserEnabledRequest;
import org.elasticsearch.common.Strings;
Expand Down Expand Up @@ -213,6 +214,14 @@ static Request getPrivileges(GetPrivilegesRequest getPrivilegesRequest) {
return new Request(HttpGet.METHOD_NAME, endpoint);
}

static Request putPrivileges(final PutPrivilegesRequest putPrivilegesRequest) throws IOException {
Request request = new Request(HttpPut.METHOD_NAME, "/_xpack/security/privilege");
request.setEntity(createEntity(putPrivilegesRequest, REQUEST_BODY_CONTENT_TYPE));
RequestConverters.Params params = new RequestConverters.Params(request);
params.withRefreshPolicy(putPrivilegesRequest.getRefreshPolicy());
return request;
}

static Request deletePrivileges(DeletePrivilegesRequest deletePrivilegeRequest) {
String endpoint = new RequestConverters.EndpointBuilder()
.addPathPartAsIs("_xpack/security/privilege")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* 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.client.security.user.privileges.ApplicationPrivilege;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
* Request object for creating/updating application privileges.
*/
public final class PutPrivilegesRequest implements Validatable, ToXContentObject {

private final Map<String, List<ApplicationPrivilege>> privileges;
private final RefreshPolicy refreshPolicy;

public PutPrivilegesRequest(final List<ApplicationPrivilege> privileges, @Nullable final RefreshPolicy refreshPolicy) {
if (privileges == null || privileges.isEmpty()) {
throw new IllegalArgumentException("privileges are required");
}
this.privileges = Collections.unmodifiableMap(privileges.stream()
.collect(Collectors.groupingBy(ApplicationPrivilege::getApplication, TreeMap::new, Collectors.toList())));
this.refreshPolicy = refreshPolicy == null ? RefreshPolicy.IMMEDIATE : refreshPolicy;
}

/**
* @return a map of application name to list of
* {@link ApplicationPrivilege}s
*/
public Map<String, List<ApplicationPrivilege>> getPrivileges() {
bizybot marked this conversation as resolved.
Show resolved Hide resolved
return privileges;
}

public RefreshPolicy getRefreshPolicy() {
return refreshPolicy;
}

@Override
public int hashCode() {
return Objects.hash(privileges, refreshPolicy);
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || (this.getClass() != o.getClass())) {
return false;
}
final PutPrivilegesRequest that = (PutPrivilegesRequest) o;
return privileges.equals(that.privileges) && (refreshPolicy == that.refreshPolicy);
}

@Override
public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException {
builder.startObject();
for (Entry<String, List<ApplicationPrivilege>> entry : privileges.entrySet()) {
builder.field(entry.getKey());
builder.startObject();
for (ApplicationPrivilege applicationPrivilege : entry.getValue()) {
builder.field(applicationPrivilege.getName());
applicationPrivilege.toXContent(builder, params);
}
builder.endObject();
}
return builder.endObject();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* 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.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
* Response when creating/updating one or more application privileges to the
* security index.
*/
public final class PutPrivilegesResponse {

/*
* Map of application name to a map of privilege name to boolean denoting
* created or update status.
*/
private final Map<String, Map<String, Boolean>> applicationPrivilegesCreatedOrUpdated;

public PutPrivilegesResponse(final Map<String, Map<String, Boolean>> applicationPrivilegesCreatedOrUpdated) {
this.applicationPrivilegesCreatedOrUpdated = Collections.unmodifiableMap(applicationPrivilegesCreatedOrUpdated);
}

/**
* Get response status for the request to create or update application
* privileges.
*
* @param applicationName application name as specified in the request
* @param privilegeName privilege name as specified in the request
* @return {@code true} if the privilege was created, {@code false} if the
* privilege was updated
* @throws IllegalArgumentException thrown for unknown application name or
* privilege name.
*/
public boolean wasCreated(final String applicationName, final String privilegeName) {
if (Strings.hasText(applicationName) == false) {
jkakavas marked this conversation as resolved.
Show resolved Hide resolved
throw new IllegalArgumentException("application name is required");
}
if (Strings.hasText(privilegeName) == false) {
throw new IllegalArgumentException("privilege name is required");
}
if (applicationPrivilegesCreatedOrUpdated.get(applicationName) == null
|| applicationPrivilegesCreatedOrUpdated.get(applicationName).get(privilegeName) == null) {
throw new IllegalArgumentException("application name or privilege name not found in the response");
}
return applicationPrivilegesCreatedOrUpdated.get(applicationName).get(privilegeName);
}

@SuppressWarnings("unchecked")
public static PutPrivilegesResponse fromXContent(final XContentParser parser) throws IOException {
tvernum marked this conversation as resolved.
Show resolved Hide resolved
final Map<String, Map<String, Boolean>> applicationPrivilegesCreatedOrUpdated = new HashMap<>();
XContentParser.Token token = parser.currentToken();
if (token == null) {
token = parser.nextToken();
}
final Map<String, Object> appNameToPrivStatus = parser.map();
for (Entry<String, Object> entry : appNameToPrivStatus.entrySet()) {
if (entry.getValue() instanceof Map) {
final Map<String, Boolean> privilegeToStatus = applicationPrivilegesCreatedOrUpdated.computeIfAbsent(entry.getKey(),
(a) -> new HashMap<>());
if (entry.getValue() instanceof Map) {
bizybot marked this conversation as resolved.
Show resolved Hide resolved
Map<String, Object> createdOrUpdated = (Map<String, Object>) entry.getValue();
createdOrUpdated.forEach((k, v) -> privilegeToStatus.put(k, ((Map<String, Boolean>) v).get("created")));
} else {
throw new ParsingException(parser.getTokenLocation(), "Failed to parse object, unexpected structure");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "Failed to parse object, unexpected structure");
}
}
return new PutPrivilegesResponse(applicationPrivilegesCreatedOrUpdated);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
Expand All @@ -44,7 +46,7 @@
* actions and metadata are completely managed by the client and can contain arbitrary
* string values.
*/
public final class ApplicationPrivilege {
public final class ApplicationPrivilege implements ToXContentObject {

private static final ParseField APPLICATION = new ParseField("application");
private static final ParseField NAME = new ParseField("name");
Expand Down Expand Up @@ -171,4 +173,16 @@ public ApplicationPrivilege build() {
}
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject()
.field(APPLICATION.getPreferredName(), application)
.field(NAME.getPreferredName(), name)
.field(ACTIONS.getPreferredName(), actions);
if (metadata != null && metadata.isEmpty() == false) {
builder.field(METADATA.getPreferredName(), metadata);
}
return builder.endObject();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@

package org.elasticsearch.client;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.elasticsearch.client.security.ChangePasswordRequest;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.DeletePrivilegesRequest;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
Expand All @@ -32,19 +33,22 @@
import org.elasticsearch.client.security.EnableUserRequest;
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.ChangePasswordRequest;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.PutPrivilegesRequest;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.RefreshPolicy;
import org.elasticsearch.client.security.support.expressiondsl.RoleMapperExpression;
import org.elasticsearch.client.security.support.expressiondsl.expressions.AnyRoleMapperExpression;
import org.elasticsearch.client.security.support.expressiondsl.fields.FieldRoleMapperExpression;
import org.elasticsearch.client.security.user.User;
import org.elasticsearch.client.security.user.privileges.ApplicationPrivilege;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.util.set.Sets;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -318,6 +322,27 @@ public void testGetAllPrivileges() throws Exception {
assertNull(request.getEntity());
}

public void testPutPrivileges() throws Exception {
int noOfApplicationPrivileges = randomIntBetween(2, 4);
final List<ApplicationPrivilege> privileges = new ArrayList<>();
for (int count = 0; count < noOfApplicationPrivileges; count++) {
privileges.add(ApplicationPrivilege.builder()
.application(randomAlphaOfLength(4))
.privilege(randomAlphaOfLengthBetween(3, 5))
.actions(Sets.newHashSet(generateRandomStringArray(3, 5, false, false)))
.metadata(Collections.singletonMap("k1", "v1"))
.build());
}
final RefreshPolicy refreshPolicy = randomFrom(RefreshPolicy.values());
final Map<String, String> expectedParams = getExpectedParamsFromRefreshPolicy(refreshPolicy);
final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, refreshPolicy);
final Request request = SecurityRequestConverters.putPrivileges(putPrivilegesRequest);
assertEquals(HttpPut.METHOD_NAME, request.getMethod());
assertEquals("/_xpack/security/privilege", request.getEndpoint());
assertEquals(expectedParams, request.getParameters());
assertToXContentBody(putPrivilegesRequest, request.getEntity());
}

public void testDeletePrivileges() {
final String application = randomAlphaOfLengthBetween(1, 12);
final List<String> privileges = randomSubsetOf(randomIntBetween(1, 3), "read", "write", "all");
Expand Down