Skip to content

Commit 150735c

Browse files
authored
Create API Key on behalf of other user (#52886)
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
1 parent bd60598 commit 150735c

File tree

22 files changed

+1216
-51
lines changed

22 files changed

+1216
-51
lines changed

test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,12 @@ public static String randomRealisticUnicodeOfCodepointLength(int codePoints) {
728728
return RandomizedTest.randomRealisticUnicodeOfCodepointLength(codePoints);
729729
}
730730

731+
/**
732+
* @param maxArraySize The maximum number of elements in the random array
733+
* @param stringSize The length of each String in the array
734+
* @param allowNull Whether the returned array may be null
735+
* @param allowEmpty Whether the returned array may be empty (have zero elements)
736+
*/
731737
public static String[] generateRandomStringArray(int maxArraySize, int stringSize, boolean allowNull, boolean allowEmpty) {
732738
if (allowNull && random().nextBoolean()) {
733739
return null;

test/framework/src/main/java/org/elasticsearch/test/XContentTestUtils.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ public static Map<String, Object> convertToMap(ToXContent part) throws IOExcepti
5858
return XContentHelper.convertToMap(BytesReference.bytes(builder), false, builder.contentType()).v2();
5959
}
6060

61+
public static BytesReference convertToXContent(Map<String, ?> map, XContentType xContentType) throws IOException {
62+
try (XContentBuilder builder = XContentFactory.contentBuilder(xContentType)) {
63+
builder.map(map);
64+
return BytesReference.bytes(builder);
65+
}
66+
}
67+
6168

6269
/**
6370
* Compares two maps generated from XContentObjects. The order of elements in arrays is ignored.

x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/CreateApiKeyRequestBuilder.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,15 @@ public CreateApiKeyRequestBuilder source(BytesReference source, XContentType xCo
7474
final NamedXContentRegistry registry = NamedXContentRegistry.EMPTY;
7575
try (InputStream stream = source.streamInput();
7676
XContentParser parser = xContentType.xContent().createParser(registry, LoggingDeprecationHandler.INSTANCE, stream)) {
77-
CreateApiKeyRequest createApiKeyRequest = PARSER.parse(parser, null);
77+
CreateApiKeyRequest createApiKeyRequest = parse(parser);
7878
setName(createApiKeyRequest.getName());
7979
setRoleDescriptors(createApiKeyRequest.getRoleDescriptors());
8080
setExpiration(createApiKeyRequest.getExpiration());
8181
}
8282
return this;
8383
}
84+
85+
public static CreateApiKeyRequest parse(XContentParser parser) throws IOException {
86+
return PARSER.parse(parser, null);
87+
}
8488
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.core.security.action;
8+
9+
import org.elasticsearch.action.ActionType;
10+
11+
/**
12+
* ActionType for the creation of an API key on behalf of another user
13+
* This returns the {@link CreateApiKeyResponse} because the REST output is intended to be identical to the {@link CreateApiKeyAction}.
14+
*/
15+
public final class GrantApiKeyAction extends ActionType<CreateApiKeyResponse> {
16+
17+
public static final String NAME = "cluster:admin/xpack/security/api_key/grant";
18+
public static final GrantApiKeyAction INSTANCE = new GrantApiKeyAction();
19+
20+
private GrantApiKeyAction() {
21+
super(NAME, CreateApiKeyResponse::new);
22+
}
23+
24+
}
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.core.security.action;
8+
9+
import org.elasticsearch.action.ActionRequest;
10+
import org.elasticsearch.action.ActionRequestValidationException;
11+
import org.elasticsearch.action.support.WriteRequest;
12+
import org.elasticsearch.common.io.stream.StreamInput;
13+
import org.elasticsearch.common.io.stream.StreamOutput;
14+
import org.elasticsearch.common.io.stream.Writeable;
15+
import org.elasticsearch.common.settings.SecureString;
16+
17+
import java.io.IOException;
18+
import java.util.Objects;
19+
20+
import static org.elasticsearch.action.ValidateActions.addValidationError;
21+
22+
/**
23+
* Request class used for the creation of an API key on behalf of another user.
24+
* Logically this is similar to {@link CreateApiKeyRequest}, but is for cases when the user that has permission to call this action
25+
* is different to the user for whom the API key should be created
26+
*/
27+
public final class GrantApiKeyRequest extends ActionRequest {
28+
29+
public static final String PASSWORD_GRANT_TYPE = "password";
30+
public static final String ACCESS_TOKEN_GRANT_TYPE = "access_token";
31+
32+
/**
33+
* Fields related to the end user authentication
34+
*/
35+
public static class Grant implements Writeable {
36+
private String type;
37+
private String username;
38+
private SecureString password;
39+
private SecureString accessToken;
40+
41+
public Grant() {
42+
}
43+
44+
public Grant(StreamInput in) throws IOException {
45+
this.type = in.readString();
46+
this.username = in.readOptionalString();
47+
this.password = in.readOptionalSecureString();
48+
this.accessToken = in.readOptionalSecureString();
49+
}
50+
51+
public void writeTo(StreamOutput out) throws IOException {
52+
out.writeString(type);
53+
out.writeOptionalString(username);
54+
out.writeOptionalSecureString(password);
55+
out.writeOptionalSecureString(accessToken);
56+
}
57+
58+
public String getType() {
59+
return type;
60+
}
61+
62+
public String getUsername() {
63+
return username;
64+
}
65+
66+
public SecureString getPassword() {
67+
return password;
68+
}
69+
70+
public SecureString getAccessToken() {
71+
return accessToken;
72+
}
73+
74+
public void setType(String type) {
75+
this.type = type;
76+
}
77+
78+
public void setUsername(String username) {
79+
this.username = username;
80+
}
81+
82+
public void setPassword(SecureString password) {
83+
this.password = password;
84+
}
85+
86+
public void setAccessToken(SecureString accessToken) {
87+
this.accessToken = accessToken;
88+
}
89+
}
90+
91+
private final Grant grant;
92+
private CreateApiKeyRequest apiKey;
93+
94+
public GrantApiKeyRequest() {
95+
this.grant = new Grant();
96+
this.apiKey = new CreateApiKeyRequest();
97+
}
98+
99+
public GrantApiKeyRequest(StreamInput in) throws IOException {
100+
super(in);
101+
this.grant = new Grant(in);
102+
this.apiKey = new CreateApiKeyRequest(in);
103+
}
104+
105+
@Override
106+
public void writeTo(StreamOutput out) throws IOException {
107+
super.writeTo(out);
108+
grant.writeTo(out);
109+
apiKey.writeTo(out);
110+
}
111+
112+
public WriteRequest.RefreshPolicy getRefreshPolicy() {
113+
return apiKey.getRefreshPolicy();
114+
}
115+
116+
public void setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy) {
117+
apiKey.setRefreshPolicy(refreshPolicy);
118+
}
119+
120+
public Grant getGrant() {
121+
return grant;
122+
}
123+
124+
public CreateApiKeyRequest getApiKeyRequest() {
125+
return apiKey;
126+
}
127+
128+
public void setApiKeyRequest(CreateApiKeyRequest apiKeyRequest) {
129+
this.apiKey = Objects.requireNonNull(apiKeyRequest, "Cannot set a null api_key");
130+
}
131+
132+
@Override
133+
public ActionRequestValidationException validate() {
134+
ActionRequestValidationException validationException = apiKey.validate();
135+
if (grant.type == null) {
136+
validationException = addValidationError("[grant_type] is required", validationException);
137+
} else if (grant.type.equals(PASSWORD_GRANT_TYPE)) {
138+
validationException = validateRequiredField("username", grant.username, validationException);
139+
validationException = validateRequiredField("password", grant.password, validationException);
140+
validationException = validateUnsupportedField("access_token", grant.accessToken, validationException);
141+
} else if (grant.type.equals(ACCESS_TOKEN_GRANT_TYPE)) {
142+
validationException = validateRequiredField("access_token", grant.accessToken, validationException);
143+
validationException = validateUnsupportedField("username", grant.username, validationException);
144+
validationException = validateUnsupportedField("password", grant.password, validationException);
145+
} else {
146+
validationException = addValidationError("grant_type [" + grant.type + "] is not supported", validationException);
147+
}
148+
return validationException;
149+
}
150+
151+
private ActionRequestValidationException validateRequiredField(String fieldName, CharSequence fieldValue,
152+
ActionRequestValidationException validationException) {
153+
if (fieldValue == null || fieldValue.length() == 0) {
154+
return addValidationError("[" + fieldName + "] is required for grant_type [" + grant.type + "]", validationException);
155+
}
156+
return validationException;
157+
}
158+
159+
private ActionRequestValidationException validateUnsupportedField(String fieldName, CharSequence fieldValue,
160+
ActionRequestValidationException validationException) {
161+
if (fieldValue != null && fieldValue.length() > 0) {
162+
return addValidationError("[" + fieldName + "] is not supported for grant_type [" + grant.type + "]", validationException);
163+
}
164+
return validationException;
165+
}
166+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
package org.elasticsearch.xpack.security;
8+
9+
import org.elasticsearch.client.RestHighLevelClient;
10+
import org.elasticsearch.common.settings.SecureString;
11+
import org.elasticsearch.common.settings.Settings;
12+
import org.elasticsearch.common.util.concurrent.ThreadContext;
13+
import org.elasticsearch.test.rest.ESRestTestCase;
14+
15+
import java.util.List;
16+
17+
import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
18+
19+
public abstract class SecurityInBasicRestTestCase extends ESRestTestCase {
20+
private RestHighLevelClient highLevelAdminClient;
21+
22+
@Override
23+
protected Settings restAdminSettings() {
24+
String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()));
25+
return Settings.builder()
26+
.put(ThreadContext.PREFIX + ".Authorization", token)
27+
.build();
28+
}
29+
30+
@Override
31+
protected Settings restClientSettings() {
32+
String token = basicAuthHeaderValue("security_test_user", new SecureString("security-test-password".toCharArray()));
33+
return Settings.builder()
34+
.put(ThreadContext.PREFIX + ".Authorization", token)
35+
.build();
36+
}
37+
38+
private RestHighLevelClient getHighLevelAdminClient() {
39+
if (highLevelAdminClient == null) {
40+
highLevelAdminClient = new RestHighLevelClient(
41+
adminClient(),
42+
ignore -> {
43+
},
44+
List.of()) {
45+
};
46+
}
47+
return highLevelAdminClient;
48+
}
49+
}

x-pack/plugin/security/qa/security-basic/src/test/java/org/elasticsearch/xpack/security/SecurityWithBasicLicenseIT.java

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,6 @@
1111
import org.elasticsearch.client.Response;
1212
import org.elasticsearch.client.ResponseException;
1313
import org.elasticsearch.common.collect.Tuple;
14-
import org.elasticsearch.common.settings.SecureString;
15-
import org.elasticsearch.common.settings.Settings;
16-
import org.elasticsearch.common.util.concurrent.ThreadContext;
17-
import org.elasticsearch.test.rest.ESRestTestCase;
1814
import org.elasticsearch.test.rest.yaml.ObjectPath;
1915
import org.elasticsearch.xpack.security.authc.InternalRealms;
2016

@@ -24,29 +20,12 @@
2420
import java.util.Base64;
2521
import java.util.Map;
2622

27-
import static org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken.basicAuthHeaderValue;
2823
import static org.hamcrest.Matchers.contains;
2924
import static org.hamcrest.Matchers.containsString;
3025
import static org.hamcrest.Matchers.equalTo;
3126
import static org.hamcrest.Matchers.notNullValue;
3227

33-
public class SecurityWithBasicLicenseIT extends ESRestTestCase {
34-
35-
@Override
36-
protected Settings restAdminSettings() {
37-
String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray()));
38-
return Settings.builder()
39-
.put(ThreadContext.PREFIX + ".Authorization", token)
40-
.build();
41-
}
42-
43-
@Override
44-
protected Settings restClientSettings() {
45-
String token = basicAuthHeaderValue("security_test_user", new SecureString("security-test-password".toCharArray()));
46-
return Settings.builder()
47-
.put(ThreadContext.PREFIX + ".Authorization", token)
48-
.build();
49-
}
28+
public class SecurityWithBasicLicenseIT extends SecurityInBasicRestTestCase {
5029

5130
public void testWithBasicLicense() throws Exception {
5231
checkLicenseType("basic");
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
apply plugin: 'elasticsearch.testclusters'
2+
apply plugin: 'elasticsearch.standalone-rest-test'
3+
apply plugin: 'elasticsearch.rest-test'
4+
5+
dependencies {
6+
testCompile project(path: xpackModule('core'), configuration: 'default')
7+
testCompile project(path: xpackModule('security'), configuration: 'testArtifacts')
8+
testCompile project(path: xpackModule('core'), configuration: 'testArtifacts')
9+
}
10+
11+
testClusters.integTest {
12+
testDistribution = 'DEFAULT'
13+
numberOfNodes = 2
14+
15+
setting 'xpack.ilm.enabled', 'false'
16+
setting 'xpack.ml.enabled', 'false'
17+
setting 'xpack.license.self_generated.type', 'trial'
18+
setting 'xpack.security.enabled', 'true'
19+
setting 'xpack.security.ssl.diagnose.trust', 'true'
20+
setting 'xpack.security.http.ssl.enabled', 'false'
21+
setting 'xpack.security.transport.ssl.enabled', 'false'
22+
setting 'xpack.security.authc.token.enabled', 'true'
23+
setting 'xpack.security.authc.api_key.enabled', 'true'
24+
25+
extraConfigFile 'roles.yml', file('src/test/resources/roles.yml')
26+
user username: "admin_user", password: "admin-password"
27+
user username: "security_test_user", password: "security-test-password", role: "security_test_role"
28+
}

0 commit comments

Comments
 (0)