Skip to content

Commit

Permalink
Create API Key on behalf of other user (#52886)
Browse files Browse the repository at this point in the history
This change adds a "grant API key action"

   POST /_security/api_key/grant

that creates a new API key using the privileges of one user ("the
system user") to execute the action, but creates the API key with
the roles of the second user ("the end user").

This allows a system (such as Kibana) to create API keys representing
the identity and access of an authenticated user without requiring
that user to have permission to create API keys on their own.

This also creates a new QA project for security on trial licenses and runs
the API key tests there
  • Loading branch information
tvernum committed Mar 12, 2020
1 parent bd60598 commit 150735c
Show file tree
Hide file tree
Showing 22 changed files with 1,216 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,12 @@ public static String randomRealisticUnicodeOfCodepointLength(int codePoints) {
return RandomizedTest.randomRealisticUnicodeOfCodepointLength(codePoints);
}

/**
* @param maxArraySize The maximum number of elements in the random array
* @param stringSize The length of each String in the array
* @param allowNull Whether the returned array may be null
* @param allowEmpty Whether the returned array may be empty (have zero elements)
*/
public static String[] generateRandomStringArray(int maxArraySize, int stringSize, boolean allowNull, boolean allowEmpty) {
if (allowNull && random().nextBoolean()) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ public static Map<String, Object> convertToMap(ToXContent part) throws IOExcepti
return XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2();
}

public static BytesReference convertToXContent(Map<String, ?> map, XContentType xContentType) throws IOException {
try (XContentBuilder builder = XContentFactory.contentBuilder(xContentType)) {
builder.map(map);
return BytesReference.bytes(builder);
}
}


/**
* Compares two maps generated from XContentObjects. The order of elements in arrays is ignored.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,15 @@ public CreateApiKeyRequestBuilder source(BytesReference source, XContentType xCo
final NamedXContentRegistry registry = NamedXContentRegistry.EMPTY;
try (InputStream stream = source.streamInput();
XContentParser parser = xContentType.xContent().createParser(registry, LoggingDeprecationHandler.INSTANCE, stream)) {
CreateApiKeyRequest createApiKeyRequest = PARSER.parse(parser, null);
CreateApiKeyRequest createApiKeyRequest = parse(parser);
setName(createApiKeyRequest.getName());
setRoleDescriptors(createApiKeyRequest.getRoleDescriptors());
setExpiration(createApiKeyRequest.getExpiration());
}
return this;
}

public static CreateApiKeyRequest parse(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.core.security.action;

import org.elasticsearch.action.ActionType;

/**
* ActionType for the creation of an API key on behalf of another user
* This returns the {@link CreateApiKeyResponse} because the REST output is intended to be identical to the {@link CreateApiKeyAction}.
*/
public final class GrantApiKeyAction extends ActionType<CreateApiKeyResponse> {

public static final String NAME = "cluster:admin/xpack/security/api_key/grant";
public static final GrantApiKeyAction INSTANCE = new GrantApiKeyAction();

private GrantApiKeyAction() {
super(NAME, CreateApiKeyResponse::new);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.core.security.action;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.settings.SecureString;

import java.io.IOException;
import java.util.Objects;

import static org.elasticsearch.action.ValidateActions.addValidationError;

/**
* Request class used for the creation of an API key on behalf of another user.
* Logically this is similar to {@link CreateApiKeyRequest}, but is for cases when the user that has permission to call this action
* is different to the user for whom the API key should be created
*/
public final class GrantApiKeyRequest extends ActionRequest {

public static final String PASSWORD_GRANT_TYPE = "password";
public static final String ACCESS_TOKEN_GRANT_TYPE = "access_token";

/**
* Fields related to the end user authentication
*/
public static class Grant implements Writeable {
private String type;
private String username;
private SecureString password;
private SecureString accessToken;

public Grant() {
}

public Grant(StreamInput in) throws IOException {
this.type = in.readString();
this.username = in.readOptionalString();
this.password = in.readOptionalSecureString();
this.accessToken = in.readOptionalSecureString();
}

public void writeTo(StreamOutput out) throws IOException {
out.writeString(type);
out.writeOptionalString(username);
out.writeOptionalSecureString(password);
out.writeOptionalSecureString(accessToken);
}

public String getType() {
return type;
}

public String getUsername() {
return username;
}

public SecureString getPassword() {
return password;
}

public SecureString getAccessToken() {
return accessToken;
}

public void setType(String type) {
this.type = type;
}

public void setUsername(String username) {
this.username = username;
}

public void setPassword(SecureString password) {
this.password = password;
}

public void setAccessToken(SecureString accessToken) {
this.accessToken = accessToken;
}
}

private final Grant grant;
private CreateApiKeyRequest apiKey;

public GrantApiKeyRequest() {
this.grant = new Grant();
this.apiKey = new CreateApiKeyRequest();
}

public GrantApiKeyRequest(StreamInput in) throws IOException {
super(in);
this.grant = new Grant(in);
this.apiKey = new CreateApiKeyRequest(in);
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
grant.writeTo(out);
apiKey.writeTo(out);
}

public WriteRequest.RefreshPolicy getRefreshPolicy() {
return apiKey.getRefreshPolicy();
}

public void setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy) {
apiKey.setRefreshPolicy(refreshPolicy);
}

public Grant getGrant() {
return grant;
}

public CreateApiKeyRequest getApiKeyRequest() {
return apiKey;
}

public void setApiKeyRequest(CreateApiKeyRequest apiKeyRequest) {
this.apiKey = Objects.requireNonNull(apiKeyRequest, "Cannot set a null api_key");
}

@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = apiKey.validate();
if (grant.type == null) {
validationException = addValidationError("[grant_type] is required", validationException);
} else if (grant.type.equals(PASSWORD_GRANT_TYPE)) {
validationException = validateRequiredField("username", grant.username, validationException);
validationException = validateRequiredField("password", grant.password, validationException);
validationException = validateUnsupportedField("access_token", grant.accessToken, validationException);
} else if (grant.type.equals(ACCESS_TOKEN_GRANT_TYPE)) {
validationException = validateRequiredField("access_token", grant.accessToken, validationException);
validationException = validateUnsupportedField("username", grant.username, validationException);
validationException = validateUnsupportedField("password", grant.password, validationException);
} else {
validationException = addValidationError("grant_type [" + grant.type + "] is not supported", validationException);
}
return validationException;
}

private ActionRequestValidationException validateRequiredField(String fieldName, CharSequence fieldValue,
ActionRequestValidationException validationException) {
if (fieldValue == null || fieldValue.length() == 0) {
return addValidationError("[" + fieldName + "] is required for grant_type [" + grant.type + "]", validationException);
}
return validationException;
}

private ActionRequestValidationException validateUnsupportedField(String fieldName, CharSequence fieldValue,
ActionRequestValidationException validationException) {
if (fieldValue != null && fieldValue.length() > 0) {
return addValidationError("[" + fieldName + "] is not supported for grant_type [" + grant.type + "]", validationException);
}
return validationException;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.security;

import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.rest.ESRestTestCase;

import java.util.List;

import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;

public abstract class SecurityInBasicRestTestCase extends ESRestTestCase {
private RestHighLevelClient highLevelAdminClient;

@Override
protected Settings restAdminSettings() {
String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()));
return Settings.builder()
.put(ThreadContext.PREFIX + ".Authorization", token)
.build();
}

@Override
protected Settings restClientSettings() {
String token = basicAuthHeaderValue("security_test_user", new SecureString("security-test-password".toCharArray()));
return Settings.builder()
.put(ThreadContext.PREFIX + ".Authorization", token)
.build();
}

private RestHighLevelClient getHighLevelAdminClient() {
if (highLevelAdminClient == null) {
highLevelAdminClient = new RestHighLevelClient(
adminClient(),
ignore -> {
},
List.of()) {
};
}
return highLevelAdminClient;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.settings.SecureString;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.test.rest.ESRestTestCase;
import org.elasticsearch.test.rest.yaml.ObjectPath;
import org.elasticsearch.xpack.security.authc.InternalRealms;

Expand All @@ -24,29 +20,12 @@
import java.util.Base64;
import java.util.Map;

import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;

public class SecurityWithBasicLicenseIT extends ESRestTestCase {

@Override
protected Settings restAdminSettings() {
String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()));
return Settings.builder()
.put(ThreadContext.PREFIX + ".Authorization", token)
.build();
}

@Override
protected Settings restClientSettings() {
String token = basicAuthHeaderValue("security_test_user", new SecureString("security-test-password".toCharArray()));
return Settings.builder()
.put(ThreadContext.PREFIX + ".Authorization", token)
.build();
}
public class SecurityWithBasicLicenseIT extends SecurityInBasicRestTestCase {

public void testWithBasicLicense() throws Exception {
checkLicenseType("basic");
Expand Down
28 changes: 28 additions & 0 deletions x-pack/plugin/security/qa/security-trial/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
apply plugin: 'elasticsearch.testclusters'
apply plugin: 'elasticsearch.standalone-rest-test'
apply plugin: 'elasticsearch.rest-test'

dependencies {
testCompile project(path: xpackModule('core'), configuration: 'default')
testCompile project(path: xpackModule('security'), configuration: 'testArtifacts')
testCompile project(path: xpackModule('core'), configuration: 'testArtifacts')
}

testClusters.integTest {
testDistribution = 'DEFAULT'
numberOfNodes = 2

setting 'xpack.ilm.enabled', 'false'
setting 'xpack.ml.enabled', 'false'
setting 'xpack.license.self_generated.type', 'trial'
setting 'xpack.security.enabled', 'true'
setting 'xpack.security.ssl.diagnose.trust', 'true'
setting 'xpack.security.http.ssl.enabled', 'false'
setting 'xpack.security.transport.ssl.enabled', 'false'
setting 'xpack.security.authc.token.enabled', 'true'
setting 'xpack.security.authc.api_key.enabled', 'true'

extraConfigFile 'roles.yml', file('src/test/resources/roles.yml')
user username: "admin_user", password: "admin-password"
user username: "security_test_user", password: "security-test-password", role: "security_test_role"
}
Loading

0 comments on commit 150735c

Please sign in to comment.