Skip to content

Commit 7f21ade

Browse files
authored
Explicitly require that derived API keys have no privileges (#53647) (#53648)
The current implicit behaviour is that when an API keys is used to create another API key, the child key is created without any privilege. This implicit behaviour is surprising and is a source of confusion for users. This change makes that behaviour explicit.
1 parent 74dbdb9 commit 7f21ade

File tree

4 files changed

+150
-0
lines changed

4 files changed

+150
-0
lines changed

x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/RoleDescriptor.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,16 @@ public int hashCode() {
217217
return result;
218218
}
219219

220+
221+
public boolean isEmpty() {
222+
return clusterPrivileges.length == 0
223+
&& configurableClusterPrivileges.length == 0
224+
&& indicesPrivileges.length == 0
225+
&& applicationPrivileges.length == 0
226+
&& runAs.length == 0
227+
&& metadata.size() == 0;
228+
}
229+
220230
@Override
221231
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
222232
return toXContent(builder, params, false);

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ protected void doExecute(Task task, CreateApiKeyRequest request, ActionListener<
5454
if (authentication == null) {
5555
listener.onFailure(new IllegalStateException("authentication is required"));
5656
} else {
57+
if (Authentication.AuthenticationType.API_KEY == authentication.getAuthenticationType() && grantsAnyPrivileges(request)) {
58+
listener.onFailure(new IllegalArgumentException(
59+
"creating derived api keys requires an explicit role descriptor that is empty (has no privileges)"));
60+
return;
61+
}
5762
rolesStore.getRoleDescriptors(new HashSet<>(Arrays.asList(authentication.getUser().roles())),
5863
ActionListener.wrap(roleDescriptors -> {
5964
for (RoleDescriptor rd : roleDescriptors) {
@@ -69,4 +74,10 @@ protected void doExecute(Task task, CreateApiKeyRequest request, ActionListener<
6974
listener::onFailure));
7075
}
7176
}
77+
78+
private boolean grantsAnyPrivileges(CreateApiKeyRequest request) {
79+
return request.getRoleDescriptors() == null
80+
|| request.getRoleDescriptors().isEmpty()
81+
|| false == request.getRoleDescriptors().stream().allMatch(RoleDescriptor::isEmpty);
82+
}
7283
}

x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyIntegTests.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import org.elasticsearch.ElasticsearchSecurityException;
1111
import org.elasticsearch.action.DocWriteResponse;
1212
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
13+
import org.elasticsearch.action.admin.indices.refresh.RefreshAction;
14+
import org.elasticsearch.action.admin.indices.refresh.RefreshRequestBuilder;
1315
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
1416
import org.elasticsearch.action.support.PlainActionFuture;
1517
import org.elasticsearch.action.support.WriteRequest;
@@ -771,6 +773,80 @@ public void testApiKeyWithManageOwnPrivilegeIsAbleToInvalidateItselfButNotAnyOth
771773
assertThat(invalidateResponse.getErrors().size(), equalTo(0));
772774
}
773775

776+
public void testDerivedKeys() throws ExecutionException, InterruptedException {
777+
final Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
778+
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
779+
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
780+
781+
final CreateApiKeyResponse response = new SecurityClient(client)
782+
.prepareCreateApiKey()
783+
.setName("key-1")
784+
.setRoleDescriptors(Collections.singletonList(
785+
new RoleDescriptor("role", new String[] { "manage_api_key" }, null, null)))
786+
.get();
787+
788+
assertEquals("key-1", response.getName());
789+
assertNotNull(response.getId());
790+
assertNotNull(response.getKey());
791+
792+
// use the first ApiKey for authorized action
793+
final String base64ApiKeyKeyValue = Base64.getEncoder().encodeToString(
794+
(response.getId() + ":" + response.getKey().toString()).getBytes(StandardCharsets.UTF_8));
795+
final SecurityClient clientKey1 = new SecurityClient(
796+
client().filterWithHeader(Collections.singletonMap("Authorization", "ApiKey " + base64ApiKeyKeyValue)));
797+
798+
final String expectedMessage = "creating derived api keys requires an explicit role descriptor that is empty";
799+
800+
final IllegalArgumentException e1 = expectThrows(IllegalArgumentException.class,
801+
() -> clientKey1.prepareCreateApiKey().setName("key-2").get());
802+
assertThat(e1.getMessage(), containsString(expectedMessage));
803+
804+
final IllegalArgumentException e2 = expectThrows(IllegalArgumentException.class,
805+
() -> clientKey1.prepareCreateApiKey().setName("key-3")
806+
.setRoleDescriptors(Collections.emptyList()).get());
807+
assertThat(e2.getMessage(), containsString(expectedMessage));
808+
809+
final IllegalArgumentException e3 = expectThrows(IllegalArgumentException.class,
810+
() -> clientKey1.prepareCreateApiKey().setName("key-4")
811+
.setRoleDescriptors(Collections.singletonList(
812+
new RoleDescriptor("role", new String[] {"manage_own_api_key"}, null, null)
813+
)).get());
814+
assertThat(e3.getMessage(), containsString(expectedMessage));
815+
816+
final List<RoleDescriptor> roleDescriptors = randomList(2, 10,
817+
() -> new RoleDescriptor("role", null, null, null));
818+
roleDescriptors.set(randomInt(roleDescriptors.size() - 1),
819+
new RoleDescriptor("role", new String[] {"manage_own_api_key"}, null, null));
820+
821+
final IllegalArgumentException e4 = expectThrows(IllegalArgumentException.class,
822+
() -> clientKey1.prepareCreateApiKey().setName("key-5")
823+
.setRoleDescriptors(roleDescriptors).get());
824+
assertThat(e4.getMessage(), containsString(expectedMessage));
825+
826+
final CreateApiKeyResponse key100Response = clientKey1.prepareCreateApiKey().setName("key-100")
827+
.setRoleDescriptors(Collections.singletonList(
828+
new RoleDescriptor("role", null, null, null)
829+
)).get();
830+
assertEquals("key-100", key100Response.getName());
831+
assertNotNull(key100Response.getId());
832+
assertNotNull(key100Response.getKey());
833+
834+
// Check at the end to allow sometime for the operation to happen. Since an erroneous creation is
835+
// asynchronous so that the document is not available immediately.
836+
assertApiKeyNotCreated(client,"key-2");
837+
assertApiKeyNotCreated(client,"key-3");
838+
assertApiKeyNotCreated(client,"key-4");
839+
assertApiKeyNotCreated(client,"key-5");
840+
}
841+
842+
private void assertApiKeyNotCreated(Client client, String keyName) throws ExecutionException, InterruptedException {
843+
new RefreshRequestBuilder(client, RefreshAction.INSTANCE).setIndices(SECURITY_MAIN_ALIAS).execute().get();
844+
PlainActionFuture<GetApiKeyResponse> getApiKeyResponseListener = new PlainActionFuture<>();
845+
new SecurityClient(client).getApiKey(
846+
GetApiKeyRequest.usingApiKeyName(keyName, false), getApiKeyResponseListener);
847+
assertEquals(0, getApiKeyResponseListener.get().getApiKeyInfos().length);
848+
}
849+
774850
private void verifyGetResponse(int expectedNumberOfApiKeys, List<CreateApiKeyResponse> responses,
775851
GetApiKeyResponse response, Set<String> validApiKeyIds, List<String> invalidatedApiKeyIds) {
776852
verifyGetResponse(SecuritySettingsSource.TEST_SUPERUSER, expectedNumberOfApiKeys, responses, response, validApiKeyIds,

x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/RoleDescriptorTests.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@
3232
import java.io.IOException;
3333
import java.util.Arrays;
3434
import java.util.Collections;
35+
import java.util.HashMap;
3536
import java.util.LinkedHashSet;
37+
import java.util.List;
3638
import java.util.Map;
3739

3840
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@@ -325,4 +327,55 @@ public void testParseIndicesPrivilegesFailsWhenExceptFieldsAreNotSubsetOfGranted
325327
assertThat(epe, TestMatchers.throwableWithMessage(containsString("f2")));
326328
assertThat(epe, TestMatchers.throwableWithMessage(containsString("f3")));
327329
}
330+
331+
public void testIsEmpty() {
332+
assertTrue(new RoleDescriptor(
333+
randomAlphaOfLengthBetween(1, 10), null, null, null, null, null, null, null)
334+
.isEmpty());
335+
336+
assertTrue(new RoleDescriptor(
337+
randomAlphaOfLengthBetween(1, 10),
338+
new String[0],
339+
new RoleDescriptor.IndicesPrivileges[0],
340+
new RoleDescriptor.ApplicationResourcePrivileges[0],
341+
new ConfigurableClusterPrivilege[0],
342+
new String[0],
343+
new HashMap<>(),
344+
new HashMap<>())
345+
.isEmpty());
346+
347+
final List<Boolean> booleans = Arrays.asList(
348+
randomBoolean(),
349+
randomBoolean(),
350+
randomBoolean(),
351+
randomBoolean(),
352+
randomBoolean(),
353+
randomBoolean());
354+
355+
final RoleDescriptor roleDescriptor = new RoleDescriptor(
356+
randomAlphaOfLengthBetween(1, 10),
357+
booleans.get(0) ? new String[0] : new String[] { "foo" },
358+
booleans.get(1) ?
359+
new RoleDescriptor.IndicesPrivileges[0] :
360+
new RoleDescriptor.IndicesPrivileges[] {
361+
RoleDescriptor.IndicesPrivileges.builder().indices("idx").privileges("foo").build() },
362+
booleans.get(2) ?
363+
new RoleDescriptor.ApplicationResourcePrivileges[0] :
364+
new RoleDescriptor.ApplicationResourcePrivileges[] {
365+
RoleDescriptor.ApplicationResourcePrivileges.builder()
366+
.application("app").privileges("foo").resources("res").build() },
367+
booleans.get(3) ?
368+
new ConfigurableClusterPrivilege[0] :
369+
new ConfigurableClusterPrivilege[] {
370+
new ConfigurableClusterPrivileges.ManageApplicationPrivileges(Collections.singleton("foo")) },
371+
booleans.get(4) ? new String[0] : new String[] { "foo" },
372+
booleans.get(5) ? new HashMap<>() : Collections.singletonMap("foo", "bar"),
373+
Collections.singletonMap("foo", "bar"));
374+
375+
if (booleans.stream().anyMatch(e -> e.equals(false))) {
376+
assertFalse(roleDescriptor.isEmpty());
377+
} else {
378+
assertTrue(roleDescriptor.isEmpty());
379+
}
380+
}
328381
}

0 commit comments

Comments
 (0)