Skip to content

Commit 59ca3a7

Browse files
authored
Replace health calls with authenticate calls (#50073)
In integration tests for API Keys and Tokens, we would use calls we did with the transport client to the cluster health endpoint after adding the API key or Token with `filterWithHeader()` in order to verify that the API Key or Token is valid. The response would always be successful regardless of the validity of the Token or API Key since the internal request would have the `_system` user as a fallback user and the `_system` is allowed to call the health API. When failing to validate the token or key, we would fallback to the `_system` user, see AuthenticationService#handleNullToken This commit changes our behavior to use the RestClient and call the authenticate API to verify the validity of tokens and API keys.
1 parent 2474276 commit 59ca3a7

File tree

2 files changed

+26
-21
lines changed

2 files changed

+26
-21
lines changed

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

+14-9
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@
99
import com.google.common.collect.Sets;
1010
import org.elasticsearch.ElasticsearchSecurityException;
1111
import org.elasticsearch.action.DocWriteResponse;
12-
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
1312
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
1413
import org.elasticsearch.action.support.PlainActionFuture;
1514
import org.elasticsearch.action.support.WriteRequest;
1615
import org.elasticsearch.action.update.UpdateResponse;
1716
import org.elasticsearch.client.Client;
17+
import org.elasticsearch.client.RequestOptions;
18+
import org.elasticsearch.client.RestHighLevelClient;
19+
import org.elasticsearch.client.security.AuthenticateResponse;
1820
import org.elasticsearch.common.Strings;
1921
import org.elasticsearch.common.settings.Settings;
2022
import org.elasticsearch.common.unit.TimeValue;
@@ -77,6 +79,11 @@ public Settings nodeSettings(int nodeOrdinal) {
7779
.build();
7880
}
7981

82+
@Override
83+
protected boolean addMockHttpTransport() {
84+
return false; // need real http
85+
}
86+
8087
@Before
8188
public void waitForSecurityIndexWritable() throws Exception {
8289
assertSecurityIndexActive();
@@ -125,7 +132,7 @@ private void awaitApiKeysRemoverCompletion() throws Exception {
125132
}
126133

127134
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/47958")
128-
public void testCreateApiKey() {
135+
public void testCreateApiKey() throws Exception{
129136
final Instant start = Instant.now();
130137
final RoleDescriptor descriptor = new RoleDescriptor("role", new String[] { "monitor" }, null, null);
131138
Client client = client().filterWithHeader(Collections.singletonMap("Authorization",
@@ -155,13 +162,11 @@ public void testCreateApiKey() {
155162
// use the first ApiKey for authorized action
156163
final String base64ApiKeyKeyValue = Base64.getEncoder().encodeToString(
157164
(response.getId() + ":" + response.getKey().toString()).getBytes(StandardCharsets.UTF_8));
158-
ClusterHealthResponse healthResponse = client()
159-
.filterWithHeader(Collections.singletonMap("Authorization", "ApiKey " + base64ApiKeyKeyValue))
160-
.admin()
161-
.cluster()
162-
.prepareHealth()
163-
.get();
164-
assertFalse(healthResponse.isTimedOut());
165+
// Assert that we can authenticate with the API KEY
166+
final RestHighLevelClient restClient = new TestRestHighLevelClient();
167+
AuthenticateResponse authResponse = restClient.security().authenticate(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization",
168+
"ApiKey " + base64ApiKeyKeyValue).build());
169+
assertThat(authResponse.getUser().getUsername(), equalTo(SecuritySettingsSource.TEST_SUPERUSER));
165170

166171
// use the first ApiKey for an unauthorized action
167172
ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () ->

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

+12-12
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@
5555
import java.util.stream.Collectors;
5656

5757
import static org.elasticsearch.test.SecuritySettingsSource.SECURITY_REQUEST_OPTIONS;
58-
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoTimeout;
5958
import static org.hamcrest.Matchers.containsString;
6059
import static org.hamcrest.Matchers.equalTo;
6160

@@ -256,19 +255,20 @@ public void testRefreshingToken() throws IOException {
256255
CreateTokenResponse response = restClient.security().createToken(CreateTokenRequest.passwordGrant(
257256
SecuritySettingsSource.TEST_USER_NAME, SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()), SECURITY_REQUEST_OPTIONS);
258257
assertNotNull(response.getRefreshToken());
259-
// get cluster health with token
260-
assertNoTimeout(client()
261-
.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + response.getAccessToken()))
262-
.admin().cluster().prepareHealth().get());
263-
258+
// Assert that we can authenticate with the access token
259+
AuthenticateResponse authResponse = restClient.security().authenticate(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization",
260+
"Bearer " + response.getAccessToken()).build());
261+
assertThat(authResponse.getUser().getUsername(), equalTo(SecuritySettingsSource.TEST_USER_NAME));
264262
CreateTokenResponse refreshResponse = restClient.security()
265263
.createToken(CreateTokenRequest.refreshTokenGrant(response.getRefreshToken()), SECURITY_REQUEST_OPTIONS);
266264
assertNotNull(refreshResponse.getRefreshToken());
267265
assertNotEquals(refreshResponse.getRefreshToken(), response.getRefreshToken());
268266
assertNotEquals(refreshResponse.getAccessToken(), response.getAccessToken());
269267

270-
assertNoTimeout(client().filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + refreshResponse.getAccessToken()))
271-
.admin().cluster().prepareHealth().get());
268+
// Assert that we can authenticate with the refreshed access token
269+
authResponse = restClient.security().authenticate(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization",
270+
"Bearer " + refreshResponse.getAccessToken()).build());
271+
assertThat(authResponse.getUser().getUsername(), equalTo(SecuritySettingsSource.TEST_USER_NAME));
272272
}
273273

274274
public void testRefreshingInvalidatedToken() throws IOException {
@@ -466,10 +466,10 @@ public void testAuthenticateWithWrongToken() throws Exception {
466466
CreateTokenResponse response = restClient.security().createToken(CreateTokenRequest.passwordGrant(
467467
SecuritySettingsSource.TEST_USER_NAME, SecuritySettingsSourceField.TEST_PASSWORD.toCharArray()), SECURITY_REQUEST_OPTIONS);
468468
assertNotNull(response.getRefreshToken());
469-
// First check that the correct access token works by getting cluster health with token
470-
assertNoTimeout(client()
471-
.filterWithHeader(Collections.singletonMap("Authorization", "Bearer " + response.getAccessToken()))
472-
.admin().cluster().prepareHealth().get());
469+
// Assert that we can authenticate with the access token
470+
AuthenticateResponse authResponse = restClient.security().authenticate(RequestOptions.DEFAULT.toBuilder().addHeader("Authorization",
471+
"Bearer " + response.getAccessToken()).build());
472+
assertThat(authResponse.getUser().getUsername(), equalTo(SecuritySettingsSource.TEST_USER_NAME));
473473
// Now attempt to authenticate with an invalid access token string
474474
RequestOptions wrongAuthOptions =
475475
RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", "Bearer " + randomAlphaOfLengthBetween(0, 128)).build();

0 commit comments

Comments
 (0)