Skip to content

Commit cf8daab

Browse files
committed
Explicitly require that derived API keys have no privileges (elastic#53647)
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 9c6cc75 commit cf8daab

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
@@ -216,6 +216,16 @@ public int hashCode() {
216216
return result;
217217
}
218218

219+
220+
public boolean isEmpty() {
221+
return clusterPrivileges.length == 0
222+
&& configurableClusterPrivileges.length == 0
223+
&& indicesPrivileges.length == 0
224+
&& applicationPrivileges.length == 0
225+
&& runAs.length == 0
226+
&& metadata.size() == 0;
227+
}
228+
219229
@Override
220230
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
221231
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
@@ -51,9 +51,20 @@ protected void doExecute(CreateApiKeyRequest request, ActionListener<CreateApiKe
5151
if (authentication == null) {
5252
listener.onFailure(new IllegalStateException("authentication is required"));
5353
} else {
54+
if (Authentication.AuthenticationType.API_KEY == authentication.getAuthenticationType() && grantsAnyPrivileges(request)) {
55+
listener.onFailure(new IllegalArgumentException(
56+
"creating derived api keys requires an explicit role descriptor that is empty (has no privileges)"));
57+
return;
58+
}
5459
rolesStore.getRoleDescriptors(new HashSet<>(Arrays.asList(authentication.getUser().roles())),
5560
ActionListener.wrap(roleDescriptors -> apiKeyService.createApiKey(authentication, request, roleDescriptors, listener),
5661
listener::onFailure));
5762
}
5863
}
64+
65+
private boolean grantsAnyPrivileges(CreateApiKeyRequest request) {
66+
return request.getRoleDescriptors() == null
67+
|| request.getRoleDescriptors().isEmpty()
68+
|| false == request.getRoleDescriptors().stream().allMatch(RoleDescriptor::isEmpty);
69+
}
5970
}

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
@@ -11,6 +11,8 @@
1111
import org.elasticsearch.ElasticsearchSecurityException;
1212
import org.elasticsearch.action.DocWriteResponse;
1313
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
14+
import org.elasticsearch.action.admin.indices.refresh.RefreshAction;
15+
import org.elasticsearch.action.admin.indices.refresh.RefreshRequestBuilder;
1416
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
1517
import org.elasticsearch.action.support.PlainActionFuture;
1618
import org.elasticsearch.action.support.WriteRequest;
@@ -518,6 +520,80 @@ public void testGetApiKeysForApiKeyName() throws InterruptedException, Execution
518520
verifyGetResponse(1, responses, response, Collections.singleton(responses.get(0).getId()), null);
519521
}
520522

523+
public void testDerivedKeys() throws ExecutionException, InterruptedException {
524+
final Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
525+
UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_SUPERUSER,
526+
SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)));
527+
528+
final CreateApiKeyResponse response = new SecurityClient(client)
529+
.prepareCreateApiKey()
530+
.setName("key-1")
531+
.setRoleDescriptors(Collections.singletonList(
532+
new RoleDescriptor("role", new String[] { "manage_api_key" }, null, null)))
533+
.get();
534+
535+
assertEquals("key-1", response.getName());
536+
assertNotNull(response.getId());
537+
assertNotNull(response.getKey());
538+
539+
// use the first ApiKey for authorized action
540+
final String base64ApiKeyKeyValue = Base64.getEncoder().encodeToString(
541+
(response.getId() + ":" + response.getKey().toString()).getBytes(StandardCharsets.UTF_8));
542+
final SecurityClient clientKey1 = new SecurityClient(
543+
client().filterWithHeader(Collections.singletonMap("Authorization", "ApiKey " + base64ApiKeyKeyValue)));
544+
545+
final String expectedMessage = "creating derived api keys requires an explicit role descriptor that is empty";
546+
547+
final IllegalArgumentException e1 = expectThrows(IllegalArgumentException.class,
548+
() -> clientKey1.prepareCreateApiKey().setName("key-2").get());
549+
assertThat(e1.getMessage(), containsString(expectedMessage));
550+
551+
final IllegalArgumentException e2 = expectThrows(IllegalArgumentException.class,
552+
() -> clientKey1.prepareCreateApiKey().setName("key-3")
553+
.setRoleDescriptors(Collections.emptyList()).get());
554+
assertThat(e2.getMessage(), containsString(expectedMessage));
555+
556+
final IllegalArgumentException e3 = expectThrows(IllegalArgumentException.class,
557+
() -> clientKey1.prepareCreateApiKey().setName("key-4")
558+
.setRoleDescriptors(Collections.singletonList(
559+
new RoleDescriptor("role", new String[] {"manage_own_api_key"}, null, null)
560+
)).get());
561+
assertThat(e3.getMessage(), containsString(expectedMessage));
562+
563+
final List<RoleDescriptor> roleDescriptors = randomList(2, 10,
564+
() -> new RoleDescriptor("role", null, null, null));
565+
roleDescriptors.set(randomInt(roleDescriptors.size() - 1),
566+
new RoleDescriptor("role", new String[] {"manage_own_api_key"}, null, null));
567+
568+
final IllegalArgumentException e4 = expectThrows(IllegalArgumentException.class,
569+
() -> clientKey1.prepareCreateApiKey().setName("key-5")
570+
.setRoleDescriptors(roleDescriptors).get());
571+
assertThat(e4.getMessage(), containsString(expectedMessage));
572+
573+
final CreateApiKeyResponse key100Response = clientKey1.prepareCreateApiKey().setName("key-100")
574+
.setRoleDescriptors(Collections.singletonList(
575+
new RoleDescriptor("role", null, null, null)
576+
)).get();
577+
assertEquals("key-100", key100Response.getName());
578+
assertNotNull(key100Response.getId());
579+
assertNotNull(key100Response.getKey());
580+
581+
// Check at the end to allow sometime for the operation to happen. Since an erroneous creation is
582+
// asynchronous so that the document is not available immediately.
583+
assertApiKeyNotCreated(client,"key-2");
584+
assertApiKeyNotCreated(client,"key-3");
585+
assertApiKeyNotCreated(client,"key-4");
586+
assertApiKeyNotCreated(client,"key-5");
587+
}
588+
589+
private void assertApiKeyNotCreated(Client client, String keyName) throws ExecutionException, InterruptedException {
590+
new RefreshRequestBuilder(client, RefreshAction.INSTANCE).setIndices(SECURITY_MAIN_ALIAS).execute().get();
591+
PlainActionFuture<GetApiKeyResponse> getApiKeyResponseListener = new PlainActionFuture<>();
592+
new SecurityClient(client).getApiKey(
593+
GetApiKeyRequest.usingApiKeyName(keyName, false), getApiKeyResponseListener);
594+
assertEquals(0, getApiKeyResponseListener.get().getApiKeyInfos().length);
595+
}
596+
521597
private void verifyGetResponse(int noOfApiKeys, List<CreateApiKeyResponse> responses, GetApiKeyResponse response,
522598
Set<String> validApiKeyIds,
523599
List<String> invalidatedApiKeyIds) {

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
@@ -27,7 +27,9 @@
2727

2828
import java.util.Arrays;
2929
import java.util.Collections;
30+
import java.util.HashMap;
3031
import java.util.LinkedHashSet;
32+
import java.util.List;
3133
import java.util.Map;
3234

3335
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@@ -277,4 +279,55 @@ public void testParseIgnoresTransientMetadata() throws Exception {
277279
assertEquals(1, parsed.getTransientMetadata().size());
278280
assertEquals(true, parsed.getTransientMetadata().get("enabled"));
279281
}
282+
283+
public void testIsEmpty() {
284+
assertTrue(new RoleDescriptor(
285+
randomAlphaOfLengthBetween(1, 10), null, null, null, null, null, null, null)
286+
.isEmpty());
287+
288+
assertTrue(new RoleDescriptor(
289+
randomAlphaOfLengthBetween(1, 10),
290+
new String[0],
291+
new RoleDescriptor.IndicesPrivileges[0],
292+
new RoleDescriptor.ApplicationResourcePrivileges[0],
293+
new ConfigurableClusterPrivilege[0],
294+
new String[0],
295+
new HashMap<>(),
296+
new HashMap<>())
297+
.isEmpty());
298+
299+
final List<Boolean> booleans = Arrays.asList(
300+
randomBoolean(),
301+
randomBoolean(),
302+
randomBoolean(),
303+
randomBoolean(),
304+
randomBoolean(),
305+
randomBoolean());
306+
307+
final RoleDescriptor roleDescriptor = new RoleDescriptor(
308+
randomAlphaOfLengthBetween(1, 10),
309+
booleans.get(0) ? new String[0] : new String[] { "foo" },
310+
booleans.get(1) ?
311+
new RoleDescriptor.IndicesPrivileges[0] :
312+
new RoleDescriptor.IndicesPrivileges[] {
313+
RoleDescriptor.IndicesPrivileges.builder().indices("idx").privileges("foo").build() },
314+
booleans.get(2) ?
315+
new RoleDescriptor.ApplicationResourcePrivileges[0] :
316+
new RoleDescriptor.ApplicationResourcePrivileges[] {
317+
RoleDescriptor.ApplicationResourcePrivileges.builder()
318+
.application("app").privileges("foo").resources("res").build() },
319+
booleans.get(3) ?
320+
new ConfigurableClusterPrivilege[0] :
321+
new ConfigurableClusterPrivilege[] {
322+
new ConfigurableClusterPrivileges.ManageApplicationPrivileges(Collections.singleton("foo")) },
323+
booleans.get(4) ? new String[0] : new String[] { "foo" },
324+
booleans.get(5) ? new HashMap<>() : Collections.singletonMap("foo", "bar"),
325+
Collections.singletonMap("foo", "bar"));
326+
327+
if (booleans.stream().anyMatch(e -> e.equals(false))) {
328+
assertFalse(roleDescriptor.isEmpty());
329+
} else {
330+
assertTrue(roleDescriptor.isEmpty());
331+
}
332+
}
280333
}

0 commit comments

Comments
 (0)