Skip to content

Commit

Permalink
Ensure CreateApiKey always creates a new document (elastic#88413)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ywangd committed Jul 11, 2022
1 parent 927ee8f commit 477ab8d
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
5 changes: 5 additions & 0 deletions docs/changelog/88413.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pr: 88413
summary: Ensure `CreateApiKey` always creates a new document
area: Security
type: bug
issues: []
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ private void createApiKeyAndIndexIt(
final IndexRequest indexRequest = client.prepareIndex(SECURITY_MAIN_ALIAS)
.setSource(builder)
.setId(request.getId())
.setOpType(DocWriteRequest.OpType.CREATE)
.setRefreshPolicy(request.getRefreshPolicy())
.request();
final BulkRequest bulkRequest = toSingleItemBulkRequest(indexRequest);
Expand All @@ -317,6 +318,7 @@ private void createApiKeyAndIndexIt(
bulkRequest,
TransportSingleItemBulkWriteAction.<IndexResponse>wrapBulkResponse(ActionListener.wrap(indexResponse -> {
assert request.getId().equals(indexResponse.getId());
assert indexResponse.getResult() == DocWriteResponse.Result.CREATED;
final ListenableFuture<CachedApiKeyHashResult> listenableFuture = new ListenableFuture<>();
listenableFuture.onResponse(new CachedApiKeyHashResult(true, apiKey));
apiKeyAuthCache.put(request.getId(), listenableFuture);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ public void testCreateApiKeyUsesBulkIndexAction() throws Exception {
assertThat(bulkRequest.requests().get(0), instanceOf(IndexRequest.class));
IndexRequest indexRequest = (IndexRequest) bulkRequest.requests().get(0);
assertThat(indexRequest.id(), is(createApiKeyRequest.getId()));
// The index request has opType create so that it will *not* override any existing document
assertThat(indexRequest.opType(), is(DocWriteRequest.OpType.CREATE));
bulkActionInvoked.set(true);
return null;
}).when(client).execute(eq(BulkAction.INSTANCE), any(BulkRequest.class), any());
Expand Down

0 comments on commit 477ab8d

Please sign in to comment.