diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java index 7b66a95609b05..5eb9fb9b41a22 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java @@ -124,6 +124,7 @@ import java.util.function.Consumer; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; +import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.SecurityTestsUtils.assertAuthenticationException; import static org.elasticsearch.test.TestMatchers.throwableWithMessage; @@ -1955,6 +1956,37 @@ public void testInvalidToken() throws Exception { final User user = new User("_username", "r1"); when(firstRealm.token(threadContext)).thenReturn(token); when(firstRealm.supports(token)).thenReturn(true); + + when(securityIndex.defensiveCopy()).thenReturn(securityIndex); + // An invalid token might decode to something that looks like a UUID + // Randomise it being invalid because the index doesn't exist, or the document doesn't exist + if (randomBoolean()) { + when(securityIndex.isAvailable(any())).thenReturn(false); + when(securityIndex.getUnavailableReason(any())).thenReturn(new ElasticsearchException(getTestName())); + } else { + when(securityIndex.isAvailable(any())).thenReturn(true); + doAnswer(inv -> { + final GetRequest request = inv.getArgument(0); + final ActionListener listener = inv.getArgument(1); + listener.onResponse( + new GetResponse( + new GetResult( + request.index(), + request.id(), + UNASSIGNED_SEQ_NO, + UNASSIGNED_PRIMARY_TERM, + 0, + false, + null, + Map.of(), + Map.of() + ) + ) + ); + return null; + }).when(client).get(any(GetRequest.class), any()); + } + mockAuthenticate(firstRealm, token, user); final int numBytes = randomIntBetween(TokenService.MINIMUM_BYTES, TokenService.MINIMUM_BYTES + 32); final byte[] randomBytes = new byte[numBytes];