Skip to content

Commit 230e946

Browse files
authored
Ensure CreateApiKey always creates a new document (#88413)
The OpType of the indexRequest used for creating new API keys does not have its OpType configured. This means it defaults to OpType.INDEX which allows it to replace an existing document. This PR fixes it by explicity set OpType to CREATE so that it always create a new document (or throw error if ID conflict does happen). Since API key ID is time-based random base64 UUID, it is unlikely for this to happen in practice and we are not aware of any related bug report.
1 parent 74a1e3e commit 230e946

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

docs/changelog/88413.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pr: 88413
2+
summary: Ensure `CreateApiKey` always creates a new document
3+
area: Security
4+
type: bug
5+
issues: []

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ApiKeyService.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ private void createApiKeyAndIndexIt(
325325
final IndexRequest indexRequest = client.prepareIndex(SECURITY_MAIN_ALIAS)
326326
.setSource(builder)
327327
.setId(request.getId())
328+
.setOpType(DocWriteRequest.OpType.CREATE)
328329
.setRefreshPolicy(request.getRefreshPolicy())
329330
.request();
330331
final BulkRequest bulkRequest = toSingleItemBulkRequest(indexRequest);
@@ -338,6 +339,7 @@ private void createApiKeyAndIndexIt(
338339
bulkRequest,
339340
TransportSingleItemBulkWriteAction.<IndexResponse>wrapBulkResponse(ActionListener.wrap(indexResponse -> {
340341
assert request.getId().equals(indexResponse.getId());
342+
assert indexResponse.getResult() == DocWriteResponse.Result.CREATED;
341343
final ListenableFuture<CachedApiKeyHashResult> listenableFuture = new ListenableFuture<>();
342344
listenableFuture.onResponse(new CachedApiKeyHashResult(true, apiKey));
343345
apiKeyAuthCache.put(request.getId(), listenableFuture);

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,8 @@ public void testCreateApiKeyUsesBulkIndexAction() throws Exception {
209209
assertThat(bulkRequest.requests().get(0), instanceOf(IndexRequest.class));
210210
IndexRequest indexRequest = (IndexRequest) bulkRequest.requests().get(0);
211211
assertThat(indexRequest.id(), is(createApiKeyRequest.getId()));
212+
// The index request has opType create so that it will *not* override any existing document
213+
assertThat(indexRequest.opType(), is(DocWriteRequest.OpType.CREATE));
212214
bulkActionInvoked.set(true);
213215
return null;
214216
}).when(client).execute(eq(BulkAction.INSTANCE), any(BulkRequest.class), any());

0 commit comments

Comments
 (0)