From f9cd1ad6acf2f55c0b320f59483521625198ae1c Mon Sep 17 00:00:00 2001 From: Sarat Vemulapalli Date: Mon, 14 Dec 2020 19:33:50 -0800 Subject: [PATCH 1/3] Adding support for Security Test Framework --- .../ad/AnomalyDetectorRestTestCase.java | 194 ++++++++++++-- .../ad/rest/AnomalyDetectorRestApiIT.java | 97 ++++--- .../ad/rest/SecureADRestIT.java | 243 ++++++++++++++++++ 3 files changed, 476 insertions(+), 58 deletions(-) create mode 100644 src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java diff --git a/src/test/java/com/amazon/opendistroforelasticsearch/ad/AnomalyDetectorRestTestCase.java b/src/test/java/com/amazon/opendistroforelasticsearch/ad/AnomalyDetectorRestTestCase.java index 20abd433..c76a20b1 100644 --- a/src/test/java/com/amazon/opendistroforelasticsearch/ad/AnomalyDetectorRestTestCase.java +++ b/src/test/java/com/amazon/opendistroforelasticsearch/ad/AnomalyDetectorRestTestCase.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; import java.util.Map; import org.apache.http.HttpEntity; @@ -28,6 +29,7 @@ import org.apache.http.message.BasicHeader; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; +import org.elasticsearch.client.RestClient; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; @@ -47,6 +49,7 @@ import com.amazon.opendistroforelasticsearch.ad.util.RestHandlerUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.gson.JsonArray; public abstract class AnomalyDetectorRestTestCase extends ODFERestTestCase { @@ -60,7 +63,7 @@ protected Settings restClientSettings() { return super.restClientSettings(); } - protected AnomalyDetector createRandomAnomalyDetector(Boolean refresh, Boolean withMetadata) throws IOException { + protected AnomalyDetector createRandomAnomalyDetector(Boolean refresh, Boolean withMetadata, RestClient client) throws IOException { Map uiMetadata = null; if (withMetadata) { uiMetadata = TestHelpers.randomUiMetadata(); @@ -69,7 +72,7 @@ protected AnomalyDetector createRandomAnomalyDetector(Boolean refresh, Boolean w String indexName = detector.getIndices().get(0); TestHelpers .makeRequest( - client(), + client, "POST", "/" + indexName + "/_doc/" + randomAlphaOfLength(5) + "?refresh=true", ImmutableMap.of(), @@ -77,17 +80,17 @@ protected AnomalyDetector createRandomAnomalyDetector(Boolean refresh, Boolean w null, false ); - AnomalyDetector createdDetector = createAnomalyDetector(detector, refresh); + AnomalyDetector createdDetector = createAnomalyDetector(detector, refresh, client); if (withMetadata) { - return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")); + return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.USER_AGENT, "Kibana"), client); } - return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); + return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"), client); } - protected AnomalyDetector createAnomalyDetector(AnomalyDetector detector, Boolean refresh) throws IOException { + protected AnomalyDetector createAnomalyDetector(AnomalyDetector detector, Boolean refresh, RestClient client) throws IOException { Response response = TestHelpers - .makeRequest(client(), "POST", TestHelpers.AD_BASE_DETECTORS_URI, ImmutableMap.of(), toHttpEntity(detector), null); + .makeRequest(client, "POST", TestHelpers.AD_BASE_DETECTORS_URI, ImmutableMap.of(), toHttpEntity(detector), null); assertEquals("Create anomaly detector failed", RestStatus.CREATED, restStatus(response)); Map detectorJson = jsonXContent @@ -113,23 +116,38 @@ protected AnomalyDetector createAnomalyDetector(AnomalyDetector detector, Boolea ); } - public AnomalyDetector getAnomalyDetector(String detectorId) throws IOException { - return (AnomalyDetector) getAnomalyDetector(detectorId, false)[0]; + protected Response startAnomalyDetector(String detectorId, RestClient client) throws IOException { + return TestHelpers + .makeRequest(client, "POST", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detectorId + "/_start", ImmutableMap.of(), "", null); + } + + protected Response stopAnomalyDetector(String detectorId, RestClient client) throws IOException { + return TestHelpers + .makeRequest(client, "POST", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detectorId + "/_stop", ImmutableMap.of(), "", null); + } + + protected Response deleteAnomalyDetector(String detectorId, RestClient client) throws IOException { + return TestHelpers.makeRequest(client, "DELETE", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detectorId, ImmutableMap.of(), "", null); + } + + public AnomalyDetector getAnomalyDetector(String detectorId, RestClient client) throws IOException { + return (AnomalyDetector) getAnomalyDetector(detectorId, false, client)[0]; } - public AnomalyDetector getAnomalyDetector(String detectorId, BasicHeader header) throws IOException { - return (AnomalyDetector) getAnomalyDetector(detectorId, header, false)[0]; + public AnomalyDetector getAnomalyDetector(String detectorId, BasicHeader header, RestClient client) throws IOException { + return (AnomalyDetector) getAnomalyDetector(detectorId, header, false, client)[0]; } - public ToXContentObject[] getAnomalyDetector(String detectorId, boolean returnJob) throws IOException { + public ToXContentObject[] getAnomalyDetector(String detectorId, boolean returnJob, RestClient client) throws IOException { BasicHeader header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - return getAnomalyDetector(detectorId, header, returnJob); + return getAnomalyDetector(detectorId, header, returnJob, client); } - public ToXContentObject[] getAnomalyDetector(String detectorId, BasicHeader header, boolean returnJob) throws IOException { + public ToXContentObject[] getAnomalyDetector(String detectorId, BasicHeader header, boolean returnJob, RestClient client) + throws IOException { Response response = TestHelpers .makeRequest( - client(), + client, "GET", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detectorId + "?job=" + returnJob, null, @@ -221,10 +239,10 @@ public void updateClusterSettings(String settingKey, Object value) throws Except assertEquals(RestStatus.OK, RestStatus.fromCode(response.getStatusLine().getStatusCode())); } - public Response getDetectorProfile(String detectorId, boolean all, String customizedProfile) throws IOException { + public Response getDetectorProfile(String detectorId, boolean all, String customizedProfile, RestClient client) throws IOException { return TestHelpers .makeRequest( - client(), + client, "GET", TestHelpers.AD_BASE_DETECTORS_URI + "/" + detectorId + "/" + RestHandlerUtils.PROFILE + customizedProfile + "?_all=" + all, null, @@ -234,11 +252,11 @@ public Response getDetectorProfile(String detectorId, boolean all, String custom } public Response getDetectorProfile(String detectorId) throws IOException { - return getDetectorProfile(detectorId, false, ""); + return getDetectorProfile(detectorId, false, "", client()); } public Response getDetectorProfile(String detectorId, boolean all) throws IOException { - return getDetectorProfile(detectorId, all, ""); + return getDetectorProfile(detectorId, all, "", client()); } public Response getSearchDetectorCount() throws IOException { @@ -264,4 +282,142 @@ public Response getSearchDetectorMatch(String name) throws IOException { ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) ); } + + public Response createUser(String name, String password, ArrayList backendRoles) throws IOException { + JsonArray backendRolesString = new JsonArray(); + for (int i = 0; i < backendRoles.size(); i++) { + backendRolesString.add(backendRoles.get(i)); + } + return TestHelpers + .makeRequest( + client(), + "PUT", + "/_opendistro/_security/api/internalusers/" + name, + null, + toHttpEntity( + " {\n" + + "\"password\": \"" + + password + + "\",\n" + + "\"backend_roles\": " + + backendRolesString + + ",\n" + + "\"attributes\": {\n" + + "}} " + ), + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } + + public Response createRoleMapping(String role, ArrayList users) throws IOException { + JsonArray usersString = new JsonArray(); + for (int i = 0; i < users.size(); i++) { + usersString.add(users.get(i)); + } + return TestHelpers + .makeRequest( + client(), + "PUT", + "/_opendistro/_security/api/rolesmapping/" + role, + null, + toHttpEntity( + "{\n" + " \"backend_roles\" : [ ],\n" + " \"hosts\" : [ ],\n" + " \"users\" : " + usersString + "\n" + "}" + ), + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } + + public Response createIndexRole(String role, String index) throws IOException { + return TestHelpers + .makeRequest( + client(), + "PUT", + "/_opendistro/_security/api/roles/" + role, + null, + toHttpEntity( + "{\n" + + "\"cluster_permissions\": [\n" + + "],\n" + + "\"index_permissions\": [\n" + + "{\n" + + "\"index_patterns\": [\n" + + "\"" + + index + + "\"\n" + + "],\n" + + "\"dls\": \"\",\n" + + "\"fls\": [],\n" + + "\"masked_fields\": [],\n" + + "\"allowed_actions\": [\n" + + "\"crud\",\n" + + "\"indices:admin/create\"\n" + + "]\n" + + "}\n" + + "],\n" + + "\"tenant_permissions\": []\n" + + "}" + ), + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } + + public Response deleteUser(String user) throws IOException { + return TestHelpers + .makeRequest( + client(), + "DELETE", + "/_opendistro/_security/api/internalusers/" + user, + null, + "", + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } + + public Response deleteRoleMapping(String user) throws IOException { + return TestHelpers + .makeRequest( + client(), + "DELETE", + "/_opendistro/_security/api/rolesmapping/" + user, + null, + "", + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } + + public Response enableFilterBy() throws IOException { + return TestHelpers + .makeRequest( + client(), + "PUT", + "_cluster/settings", + null, + toHttpEntity( + "{\n" + + " \"persistent\": {\n" + + " \"opendistro.anomaly_detection.filter_by_backend_roles\" : \"true\"\n" + + " }\n" + + "}" + ), + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } + + public Response disableFilterBy() throws IOException { + return TestHelpers + .makeRequest( + client(), + "PUT", + "_cluster/settings", + null, + toHttpEntity( + "{\n" + + " \"persistent\": {\n" + + " \"opendistro.anomaly_detection.filter_by_backend_roles\" : \"false\"\n" + + " }\n" + + "}" + ), + ImmutableList.of(new BasicHeader(HttpHeaders.USER_AGENT, "Kibana")) + ); + } } diff --git a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java index f6cf1256..9872bdbb 100644 --- a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java +++ b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java @@ -30,6 +30,7 @@ import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.junit.Assert; import com.amazon.opendistroforelasticsearch.ad.AnomalyDetectorPlugin; import com.amazon.opendistroforelasticsearch.ad.AnomalyDetectorRestTestCase; @@ -78,7 +79,7 @@ public void testCreateAnomalyDetectorWithEmptyIndices() throws Exception { } public void testCreateAnomalyDetectorWithDuplicateName() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); AnomalyDetector detectorDuplicateName = new AnomalyDetector( AnomalyDetector.NO_ID, @@ -141,26 +142,26 @@ public void testCreateAnomalyDetector() throws Exception { } public void testGetAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); - Exception ex = expectThrows(ResponseException.class, () -> getAnomalyDetector(detector.getDetectorId())); + Exception ex = expectThrows(ResponseException.class, () -> getAnomalyDetector(detector.getDetectorId(), client())); assertThat(ex.getMessage(), containsString(CommonErrorMessages.DISABLED_ERR_MSG)); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, true); - AnomalyDetector createdDetector = getAnomalyDetector(detector.getDetectorId()); + AnomalyDetector createdDetector = getAnomalyDetector(detector.getDetectorId(), client()); assertEquals("Incorrect Location header", detector, createdDetector); } public void testGetNotExistingAnomalyDetector() throws Exception { - createRandomAnomalyDetector(true, true); - TestHelpers.assertFailWith(ResponseException.class, null, () -> getAnomalyDetector(randomAlphaOfLength(5))); + createRandomAnomalyDetector(true, true, client()); + TestHelpers.assertFailWith(ResponseException.class, null, () -> getAnomalyDetector(randomAlphaOfLength(5), client())); } public void testUpdateAnomalyDetectorA() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); String newDescription = randomAlphaOfLength(5); @@ -216,15 +217,15 @@ public void testUpdateAnomalyDetectorA() throws Exception { assertEquals("Updated anomaly detector id doesn't match", detector.getDetectorId(), responseBody.get("_id")); assertEquals("Version not incremented", (detector.getVersion().intValue() + 1), (int) responseBody.get("_version")); - AnomalyDetector updatedDetector = getAnomalyDetector(detector.getDetectorId()); + AnomalyDetector updatedDetector = getAnomalyDetector(detector.getDetectorId(), client()); assertNotEquals("Anomaly detector last update time not changed", updatedDetector.getLastUpdateTime(), detector.getLastUpdateTime()); assertEquals("Anomaly detector description not updated", newDescription, updatedDetector.getDescription()); } public void testUpdateAnomalyDetectorNameToExisting() throws Exception { - AnomalyDetector detector1 = createRandomAnomalyDetector(true, true); + AnomalyDetector detector1 = createRandomAnomalyDetector(true, true, client()); - AnomalyDetector detector2 = createRandomAnomalyDetector(true, true); + AnomalyDetector detector2 = createRandomAnomalyDetector(true, true, client()); AnomalyDetector newDetector1WithDetector2Name = new AnomalyDetector( detector1.getDetectorId(), @@ -262,7 +263,7 @@ public void testUpdateAnomalyDetectorNameToExisting() throws Exception { } public void testUpdateAnomalyDetectorNameToNew() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); AnomalyDetector detectorWithNewName = new AnomalyDetector( detector.getDetectorId(), @@ -293,7 +294,7 @@ public void testUpdateAnomalyDetectorNameToNew() throws Exception { null ); - AnomalyDetector resultDetector = getAnomalyDetector(detectorWithNewName.getDetectorId()); + AnomalyDetector resultDetector = getAnomalyDetector(detectorWithNewName.getDetectorId(), client()); assertEquals("Detector name updating failed", detectorWithNewName.getName(), resultDetector.getName()); assertEquals("Updated anomaly detector id doesn't match", detectorWithNewName.getDetectorId(), resultDetector.getDetectorId()); assertNotEquals( @@ -304,7 +305,7 @@ public void testUpdateAnomalyDetectorNameToNew() throws Exception { } public void testUpdateAnomalyDetectorWithNotExistingIndex() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); String newDescription = randomAlphaOfLength(5); @@ -346,7 +347,7 @@ public void testUpdateAnomalyDetectorWithNotExistingIndex() throws Exception { } public void testSearchAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); SearchSourceBuilder search = (new SearchSourceBuilder()).query(QueryBuilders.termQuery("_id", detector.getDetectorId())); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); @@ -396,7 +397,7 @@ public void testStatsAnomalyDetector() throws Exception { } public void testPreviewAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); AnomalyDetectorExecutionInput input = new AnomalyDetectorExecutionInput( detector.getDetectorId(), Instant.now().minusSeconds(60 * 10), @@ -435,7 +436,7 @@ public void testPreviewAnomalyDetector() throws Exception { } public void testPreviewAnomalyDetectorWhichNotExist() throws Exception { - createRandomAnomalyDetector(true, false); + createRandomAnomalyDetector(true, false, client()); AnomalyDetectorExecutionInput input = new AnomalyDetectorExecutionInput( randomAlphaOfLength(5), Instant.now().minusSeconds(60 * 10), @@ -480,7 +481,7 @@ public void testExecuteAnomalyDetectorWithNullDetectorId() throws Exception { } public void testPreviewAnomalyDetectorWithDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); AnomalyDetectorExecutionInput input = new AnomalyDetectorExecutionInput( detector.getDetectorId(), Instant.now().minusSeconds(60 * 10), @@ -501,7 +502,7 @@ public void testPreviewAnomalyDetectorWithDetector() throws Exception { } public void testPreviewAnomalyDetectorWithDetectorAndNoFeatures() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); AnomalyDetectorExecutionInput input = new AnomalyDetectorExecutionInput( detector.getDetectorId(), Instant.now().minusSeconds(60 * 10), @@ -584,7 +585,7 @@ public void testSearchAnomalyResult() throws Exception { } public void testDeleteAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); @@ -633,7 +634,7 @@ public void testDeleteAnomalyDetectorWhichNotExist() throws Exception { } public void testDeleteAnomalyDetectorWithNoAdJob() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response response = TestHelpers .makeRequest( client(), @@ -647,7 +648,7 @@ public void testDeleteAnomalyDetectorWithNoAdJob() throws Exception { } public void testDeleteAnomalyDetectorWithRunningAdJob() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response startAdJobResponse = TestHelpers .makeRequest( @@ -678,7 +679,7 @@ public void testDeleteAnomalyDetectorWithRunningAdJob() throws Exception { } public void testUpdateAnomalyDetectorWithRunningAdJob() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response startAdJobResponse = TestHelpers .makeRequest( @@ -730,7 +731,7 @@ public void testUpdateAnomalyDetectorWithRunningAdJob() throws Exception { } public void testGetDetectorWithAdJob() throws IOException { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response startAdJobResponse = TestHelpers .makeRequest( @@ -744,18 +745,18 @@ public void testGetDetectorWithAdJob() throws IOException { assertEquals("Fail to start AD job", RestStatus.OK, restStatus(startAdJobResponse)); - ToXContentObject[] results = getAnomalyDetector(detector.getDetectorId(), true); + ToXContentObject[] results = getAnomalyDetector(detector.getDetectorId(), true, client()); assertEquals("Incorrect Location header", detector, results[0]); assertEquals("Incorrect detector job name", detector.getDetectorId(), ((AnomalyDetectorJob) results[1]).getName()); assertTrue(((AnomalyDetectorJob) results[1]).isEnabled()); - results = getAnomalyDetector(detector.getDetectorId(), false); + results = getAnomalyDetector(detector.getDetectorId(), false, client()); assertEquals("Incorrect Location header", detector, results[0]); assertEquals("Should not return detector job", null, results[1]); } public void testStartAdJobWithExistingDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); @@ -818,7 +819,7 @@ public void testStartAdJobWithNonexistingDetectorIndex() throws Exception { } public void testStartAdJobWithNonexistingDetector() throws Exception { - createRandomAnomalyDetector(true, false); + createRandomAnomalyDetector(true, false, client()); TestHelpers .assertFailWith( ResponseException.class, @@ -837,7 +838,7 @@ public void testStartAdJobWithNonexistingDetector() throws Exception { public void testStopAdJob() throws Exception { updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, true); - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response startAdJobResponse = TestHelpers .makeRequest( client(), @@ -908,7 +909,7 @@ public void testStopNonExistingAdJobIndex() throws Exception { } public void testStopNonExistingAdJob() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response startAdJobResponse = TestHelpers .makeRequest( client(), @@ -937,7 +938,7 @@ public void testStopNonExistingAdJob() throws Exception { } public void testStartDisabledAdjob() throws IOException { - AnomalyDetector detector = createRandomAnomalyDetector(true, false); + AnomalyDetector detector = createRandomAnomalyDetector(true, false, client()); Response startAdJobResponse = TestHelpers .makeRequest( client(), @@ -977,7 +978,7 @@ public void testStartAdjobWithNullFeatures() throws Exception { AnomalyDetector detectorWithoutFeature = TestHelpers.randomAnomalyDetector(null, null, Instant.now()); String indexName = detectorWithoutFeature.getIndices().get(0); TestHelpers.createIndex(client(), indexName, toHttpEntity("{\"name\": \"test\"}")); - AnomalyDetector detector = createAnomalyDetector(detectorWithoutFeature, true); + AnomalyDetector detector = createAnomalyDetector(detectorWithoutFeature, true, client()); TestHelpers .assertFailWith( ResponseException.class, @@ -998,7 +999,7 @@ public void testStartAdjobWithEmptyFeatures() throws Exception { AnomalyDetector detectorWithoutFeature = TestHelpers.randomAnomalyDetector(ImmutableList.of(), null, Instant.now()); String indexName = detectorWithoutFeature.getIndices().get(0); TestHelpers.createIndex(client(), indexName, toHttpEntity("{\"name\": \"test\"}")); - AnomalyDetector detector = createAnomalyDetector(detectorWithoutFeature, true); + AnomalyDetector detector = createAnomalyDetector(detectorWithoutFeature, true, client()); TestHelpers .assertFailWith( ResponseException.class, @@ -1016,7 +1017,7 @@ public void testStartAdjobWithEmptyFeatures() throws Exception { } public void testDefaultProfileAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false); @@ -1030,16 +1031,16 @@ public void testDefaultProfileAnomalyDetector() throws Exception { } public void testAllProfileAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); Response profileResponse = getDetectorProfile(detector.getDetectorId(), true); assertEquals("Incorrect profile status", RestStatus.OK, restStatus(profileResponse)); } public void testCustomizedProfileAnomalyDetector() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); - Response profileResponse = getDetectorProfile(detector.getDetectorId(), true, "/models/"); + Response profileResponse = getDetectorProfile(detector.getDetectorId(), true, "/models/", client()); assertEquals("Incorrect profile status", RestStatus.OK, restStatus(profileResponse)); } @@ -1051,7 +1052,7 @@ public void testSearchAnomalyDetectorCountNoIndex() throws Exception { } public void testSearchAnomalyDetectorCount() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); Response countResponse = getSearchDetectorCount(); Map responseMap = entityAsMap(countResponse); Integer count = (Integer) responseMap.get("count"); @@ -1066,7 +1067,7 @@ public void testSearchAnomalyDetectorMatchNoIndex() throws Exception { } public void testSearchAnomalyDetectorNoMatch() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); Response matchResponse = getSearchDetectorMatch(detector.getName()); Map responseMap = entityAsMap(matchResponse); boolean nameExists = (boolean) responseMap.get("match"); @@ -1074,10 +1075,28 @@ public void testSearchAnomalyDetectorNoMatch() throws Exception { } public void testSearchAnomalyDetectorMatch() throws Exception { - AnomalyDetector detector = createRandomAnomalyDetector(true, true); + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); Response matchResponse = getSearchDetectorMatch(detector.getName() + "newDetector"); Map responseMap = entityAsMap(matchResponse); boolean nameExists = (boolean) responseMap.get("match"); assertEquals(nameExists, false); } + + public void testDeleteAnomalyDetectorWhileRunning() throws Exception { + try { + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); + Assert.assertNotNull(detector.getDetectorId()); + Response response = startAnomalyDetector(detector.getDetectorId(), client()); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 200 OK"); + + // Deleting detector should fail while its running + response = deleteAnomalyDetector(detector.getDetectorId(), client()); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 400 Bad Request"); + Assert.assertTrue(false); // Should always raise exception and never end up here + } catch (IOException e) { + if (!e.getMessage().contains("Detector job is running")) { + Assert.assertTrue(false); + } + } + } } diff --git a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java new file mode 100644 index 00000000..4d2e6485 --- /dev/null +++ b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java @@ -0,0 +1,243 @@ +/* + * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +package com.amazon.opendistroforelasticsearch.ad.rest; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; + +import org.apache.http.HttpHost; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.RestClient; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; + +import com.amazon.opendistroforelasticsearch.ad.AnomalyDetectorRestTestCase; +import com.amazon.opendistroforelasticsearch.ad.model.AnomalyDetector; +import com.amazon.opendistroforelasticsearch.commons.rest.SecureRestClientBuilder; + +public class SecureADRestIT extends AnomalyDetectorRestTestCase { + String aliceUser = "alice"; + RestClient aliceClient; + String bobUser = "bob"; + RestClient bobClient; + String catUser = "cat"; + RestClient catClient; + String dogUser = "dog"; + RestClient dogClient; + + @Before + public void setupSecureTests() throws IOException { + if (!isHttps()) + return; + createIndexRole("index_all_access", "*"); + createUser(aliceUser, aliceUser, new ArrayList<>(Arrays.asList("odfe"))); + aliceClient = new SecureRestClientBuilder(getClusterHosts().toArray(new HttpHost[0]), isHttps(), aliceUser, aliceUser) + .setSocketTimeout(60000) + .build(); + + createUser(bobUser, bobUser, new ArrayList<>(Arrays.asList("odfe"))); + bobClient = new SecureRestClientBuilder(getClusterHosts().toArray(new HttpHost[0]), isHttps(), bobUser, bobUser) + .setSocketTimeout(60000) + .build(); + + createUser(catUser, catUser, new ArrayList<>(Arrays.asList("aes"))); + catClient = new SecureRestClientBuilder(getClusterHosts().toArray(new HttpHost[0]), isHttps(), catUser, catUser) + .setSocketTimeout(60000) + .build(); + + createUser(dogUser, dogUser, new ArrayList<>(Arrays.asList())); + dogClient = new SecureRestClientBuilder(getClusterHosts().toArray(new HttpHost[0]), isHttps(), dogUser, dogUser) + .setSocketTimeout(60000) + .build(); + + createRoleMapping("anomaly_read_access", new ArrayList<>(Arrays.asList(bobUser))); + createRoleMapping("anomaly_full_access", new ArrayList<>(Arrays.asList(aliceUser, catUser, dogUser))); + createRoleMapping("index_all_access", new ArrayList<>(Arrays.asList(aliceUser, bobUser, catUser, dogUser))); + } + + @After + public void deleteUserSetup() throws IOException { + if (!isHttps()) + return; + aliceClient.close(); + bobClient.close(); + catClient.close(); + dogClient.close(); + deleteUser(aliceUser); + deleteUser(bobUser); + deleteUser(catUser); + deleteUser(dogUser); + } + + public void testCreateAnomalyDetectorWithWriteAccess() { + if (!isHttps()) + return; + try { + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + Assert.assertNotNull(aliceDetector.getDetectorId()); + } catch (IOException e) { + Assert.assertTrue("User Alice could not create detector", false); + } + } + + public void testCreateAnomalyDetectorWithReadAccess() { + if (!isHttps()) + return; + try { + // User Bob has AD read access, should not be able to create a detector + AnomalyDetector bobDetector = createRandomAnomalyDetector(false, false, bobClient); + Assert.assertNull(bobDetector.getDetectorId()); + } catch (IOException e) { + if (!e.getMessage().contains("no permissions for [cluster:admin/opendistro/ad/detector/write]")) { + Assert.assertTrue(false); + } + } + } + + public void testStartDetectorWithReadAccess() { + if (!isHttps()) + return; + try { + // User Bob has AD read access, should not be able to modify a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + Assert.assertNotNull(aliceDetector.getDetectorId()); + Response response = startAnomalyDetector(aliceDetector.getDetectorId(), bobClient); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); + } catch (IOException e) { + if (!e.getMessage().contains("no permissions for [cluster:admin/opendistro/ad/detector/jobmanagement]")) { + Assert.assertTrue(false); + } + } + } + + public void testStartDetectorForWriteUser() { + if (!isHttps()) + return; + try { + // User Alice has AD full access, should be able to modify a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + Assert.assertNotNull(aliceDetector.getDetectorId()); + Response response = startAnomalyDetector(aliceDetector.getDetectorId(), aliceClient); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 200 OK"); + } catch (IOException e) { + Assert.assertTrue("User Alice could not start detector", false); + } + } + + public void testFilterByDisabled() { + if (!isHttps()) + return; + try { + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + // User Cat has AD full access, should be able to get a detector + AnomalyDetector detector = getAnomalyDetector(aliceDetector.getDetectorId(), catClient); + Assert.assertEquals(aliceDetector.getDetectorId(), detector.getDetectorId()); + } catch (IOException e) { + Assert.assertTrue("User Cat could not get detector", false); + } + } + + public void testGetApiFilterByEnabled() throws IOException { + if (!isHttps()) + return; + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + try { + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + AnomalyDetector detector = getAnomalyDetector(aliceDetector.getDetectorId(), catClient); + Assert.assertNull(detector.getDetectorId()); + } catch (IOException e) { + if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { + Assert.assertTrue(false); + } + } + } + + public void testStartApiFilterByEnabled() throws IOException { + if (!isHttps()) + return; + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + try { + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Response response = startAnomalyDetector(aliceDetector.getDetectorId(), catClient); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); + } catch (IOException e) { + if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { + Assert.assertTrue(false); + } + } + } + + public void testStopApiFilterByEnabled() throws IOException { + if (!isHttps()) + return; + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + try { + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Response response = stopAnomalyDetector(aliceDetector.getDetectorId(), catClient); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); + } catch (IOException e) { + if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { + Assert.assertTrue(false); + } + } + } + + public void testDeleteApiFilterByEnabled() throws IOException { + if (!isHttps()) + return; + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + try { + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Response response = deleteAnomalyDetector(aliceDetector.getDetectorId(), catClient); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); + } catch (IOException e) { + if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { + Assert.assertTrue(false); + } + } + } + + public void testCreateAnomalyDetectorWithNoBackendRole() throws IOException { + if (!isHttps()) + return; + try { + enableFilterBy(); + // User Dog has AD full access, but has no backend role + // When filter by is enabled, we block creating Detectors + AnomalyDetector dogDetector = createRandomAnomalyDetector(false, false, dogClient); + } catch (IOException e) { + if (!e.getMessage().contains("Filter by backend roles is enabled and User dog does not have backend roles configured")) { + Assert.assertTrue(false); + } + } + } +} From bd4ae091422eba8a420c5789d268998cbd720561 Mon Sep 17 00:00:00 2001 From: Sarat Vemulapalli Date: Thu, 17 Dec 2020 10:45:15 -0800 Subject: [PATCH 2/3] Excluding secure tests when not running against security plugin --- build.gradle | 6 + .../ad/rest/SecureADRestIT.java | 192 ++++++------------ 2 files changed, 72 insertions(+), 126 deletions(-) diff --git a/build.gradle b/build.gradle index 1ca22ef7..f287a432 100644 --- a/build.gradle +++ b/build.gradle @@ -156,6 +156,12 @@ integTest { } } + if (System.getProperty("https") == null) { + filter { + excludeTestsMatching "com.amazon.opendistroforelasticsearch.ad.rest.SecureADRestIT" + } + } + // The 'doFirst' delays till execution time. doFirst { // Tell the test JVM if the cluster JVM is running under a debugger so that tests can diff --git a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java index 4d2e6485..c61ee08a 100644 --- a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java +++ b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/SecureADRestIT.java @@ -43,7 +43,7 @@ public class SecureADRestIT extends AnomalyDetectorRestTestCase { @Before public void setupSecureTests() throws IOException { if (!isHttps()) - return; + throw new IllegalArgumentException("Secure Tests are running but HTTPS is not set"); createIndexRole("index_all_access", "*"); createUser(aliceUser, aliceUser, new ArrayList<>(Arrays.asList("odfe"))); aliceClient = new SecureRestClientBuilder(getClusterHosts().toArray(new HttpHost[0]), isHttps(), aliceUser, aliceUser) @@ -72,8 +72,6 @@ public void setupSecureTests() throws IOException { @After public void deleteUserSetup() throws IOException { - if (!isHttps()) - return; aliceClient.close(); bobClient.close(); catClient.close(); @@ -84,160 +82,102 @@ public void deleteUserSetup() throws IOException { deleteUser(dogUser); } - public void testCreateAnomalyDetectorWithWriteAccess() { - if (!isHttps()) - return; - try { - // User Alice has AD full access, should be able to create a detector - AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - Assert.assertNotNull(aliceDetector.getDetectorId()); - } catch (IOException e) { - Assert.assertTrue("User Alice could not create detector", false); - } + public void testCreateAnomalyDetectorWithWriteAccess() throws IOException { + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + Assert.assertNotNull("User alice could not create detector", aliceDetector.getDetectorId()); } public void testCreateAnomalyDetectorWithReadAccess() { - if (!isHttps()) - return; - try { - // User Bob has AD read access, should not be able to create a detector - AnomalyDetector bobDetector = createRandomAnomalyDetector(false, false, bobClient); - Assert.assertNull(bobDetector.getDetectorId()); - } catch (IOException e) { - if (!e.getMessage().contains("no permissions for [cluster:admin/opendistro/ad/detector/write]")) { - Assert.assertTrue(false); - } - } + // User Bob has AD read access, should not be able to create a detector + Exception exception = expectThrows(IOException.class, () -> { createRandomAnomalyDetector(false, false, bobClient); }); + Assert.assertTrue(exception.getMessage().contains("no permissions for [cluster:admin/opendistro/ad/detector/write]")); } - public void testStartDetectorWithReadAccess() { - if (!isHttps()) - return; - try { - // User Bob has AD read access, should not be able to modify a detector - AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - Assert.assertNotNull(aliceDetector.getDetectorId()); - Response response = startAnomalyDetector(aliceDetector.getDetectorId(), bobClient); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); - } catch (IOException e) { - if (!e.getMessage().contains("no permissions for [cluster:admin/opendistro/ad/detector/jobmanagement]")) { - Assert.assertTrue(false); - } - } + public void testStartDetectorWithReadAccess() throws IOException { + // User Bob has AD read access, should not be able to modify a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + Assert.assertNotNull(aliceDetector.getDetectorId()); + Exception exception = expectThrows(IOException.class, () -> { startAnomalyDetector(aliceDetector.getDetectorId(), bobClient); }); + Assert.assertTrue(exception.getMessage().contains("no permissions for [cluster:admin/opendistro/ad/detector/jobmanagement]")); } - public void testStartDetectorForWriteUser() { - if (!isHttps()) - return; - try { - // User Alice has AD full access, should be able to modify a detector - AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - Assert.assertNotNull(aliceDetector.getDetectorId()); - Response response = startAnomalyDetector(aliceDetector.getDetectorId(), aliceClient); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 200 OK"); - } catch (IOException e) { - Assert.assertTrue("User Alice could not start detector", false); - } + public void testStartDetectorForWriteUser() throws IOException { + // User Alice has AD full access, should be able to modify a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + Assert.assertNotNull(aliceDetector.getDetectorId()); + Response response = startAnomalyDetector(aliceDetector.getDetectorId(), aliceClient); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 200 OK"); } - public void testFilterByDisabled() { - if (!isHttps()) - return; - try { - // User Alice has AD full access, should be able to create a detector - AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - // User Cat has AD full access, should be able to get a detector - AnomalyDetector detector = getAnomalyDetector(aliceDetector.getDetectorId(), catClient); - Assert.assertEquals(aliceDetector.getDetectorId(), detector.getDetectorId()); - } catch (IOException e) { - Assert.assertTrue("User Cat could not get detector", false); - } + public void testFilterByDisabled() throws IOException { + // User Alice has AD full access, should be able to create a detector + AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); + // User Cat has AD full access, should be able to get a detector + AnomalyDetector detector = getAnomalyDetector(aliceDetector.getDetectorId(), catClient); + Assert.assertEquals(aliceDetector.getDetectorId(), detector.getDetectorId()); } public void testGetApiFilterByEnabled() throws IOException { - if (!isHttps()) - return; // User Alice has AD full access, should be able to create a detector AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - try { - enableFilterBy(); - // User Cat has AD full access, but is part of different backend role so Cat should not be able to access - // Alice detector - AnomalyDetector detector = getAnomalyDetector(aliceDetector.getDetectorId(), catClient); - Assert.assertNull(detector.getDetectorId()); - } catch (IOException e) { - if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { - Assert.assertTrue(false); - } - } + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Exception exception = expectThrows(IOException.class, () -> { getAnomalyDetector(aliceDetector.getDetectorId(), catClient); }); + Assert + .assertTrue( + exception.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId()) + ); } public void testStartApiFilterByEnabled() throws IOException { - if (!isHttps()) - return; // User Alice has AD full access, should be able to create a detector AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - try { - enableFilterBy(); - // User Cat has AD full access, but is part of different backend role so Cat should not be able to access - // Alice detector - Response response = startAnomalyDetector(aliceDetector.getDetectorId(), catClient); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); - } catch (IOException e) { - if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { - Assert.assertTrue(false); - } - } + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Exception exception = expectThrows(IOException.class, () -> { startAnomalyDetector(aliceDetector.getDetectorId(), catClient); }); + Assert + .assertTrue( + exception.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId()) + ); } public void testStopApiFilterByEnabled() throws IOException { - if (!isHttps()) - return; // User Alice has AD full access, should be able to create a detector AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - try { - enableFilterBy(); - // User Cat has AD full access, but is part of different backend role so Cat should not be able to access - // Alice detector - Response response = stopAnomalyDetector(aliceDetector.getDetectorId(), catClient); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); - } catch (IOException e) { - if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { - Assert.assertTrue(false); - } - } + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Exception exception = expectThrows(IOException.class, () -> { stopAnomalyDetector(aliceDetector.getDetectorId(), catClient); }); + Assert + .assertTrue( + exception.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId()) + ); } public void testDeleteApiFilterByEnabled() throws IOException { - if (!isHttps()) - return; // User Alice has AD full access, should be able to create a detector AnomalyDetector aliceDetector = createRandomAnomalyDetector(false, false, aliceClient); - try { - enableFilterBy(); - // User Cat has AD full access, but is part of different backend role so Cat should not be able to access - // Alice detector - Response response = deleteAnomalyDetector(aliceDetector.getDetectorId(), catClient); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 500 Internal Server Error"); - } catch (IOException e) { - if (!e.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId())) { - Assert.assertTrue(false); - } - } + enableFilterBy(); + // User Cat has AD full access, but is part of different backend role so Cat should not be able to access + // Alice detector + Exception exception = expectThrows(IOException.class, () -> { deleteAnomalyDetector(aliceDetector.getDetectorId(), catClient); }); + Assert + .assertTrue( + exception.getMessage().contains("User does not have permissions to access detector: " + aliceDetector.getDetectorId()) + ); } public void testCreateAnomalyDetectorWithNoBackendRole() throws IOException { - if (!isHttps()) - return; - try { - enableFilterBy(); - // User Dog has AD full access, but has no backend role - // When filter by is enabled, we block creating Detectors - AnomalyDetector dogDetector = createRandomAnomalyDetector(false, false, dogClient); - } catch (IOException e) { - if (!e.getMessage().contains("Filter by backend roles is enabled and User dog does not have backend roles configured")) { - Assert.assertTrue(false); - } - } + enableFilterBy(); + // User Dog has AD full access, but has no backend role + // When filter by is enabled, we block creating Detectors + Exception exception = expectThrows(IOException.class, () -> { createRandomAnomalyDetector(false, false, dogClient); }); + Assert + .assertTrue( + exception.getMessage().contains("Filter by backend roles is enabled and User dog does not have backend roles configured") + ); } } From 3d645bf5f80b4054e8f53ee6a9270019ebc81eab Mon Sep 17 00:00:00 2001 From: Sarat Vemulapalli Date: Thu, 17 Dec 2020 10:51:15 -0800 Subject: [PATCH 3/3] Updating Delete Detector test to expect exception --- .../ad/rest/AnomalyDetectorRestApiIT.java | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java index 9872bdbb..736e1975 100644 --- a/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java +++ b/src/test/java/com/amazon/opendistroforelasticsearch/ad/rest/AnomalyDetectorRestApiIT.java @@ -1083,20 +1083,13 @@ public void testSearchAnomalyDetectorMatch() throws Exception { } public void testDeleteAnomalyDetectorWhileRunning() throws Exception { - try { - AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); - Assert.assertNotNull(detector.getDetectorId()); - Response response = startAnomalyDetector(detector.getDetectorId(), client()); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 200 OK"); - - // Deleting detector should fail while its running - response = deleteAnomalyDetector(detector.getDetectorId(), client()); - Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 400 Bad Request"); - Assert.assertTrue(false); // Should always raise exception and never end up here - } catch (IOException e) { - if (!e.getMessage().contains("Detector job is running")) { - Assert.assertTrue(false); - } - } + AnomalyDetector detector = createRandomAnomalyDetector(true, true, client()); + Assert.assertNotNull(detector.getDetectorId()); + Response response = startAnomalyDetector(detector.getDetectorId(), client()); + Assert.assertEquals(response.getStatusLine().toString(), "HTTP/1.1 200 OK"); + + // Deleting detector should fail while its running + Exception exception = expectThrows(IOException.class, () -> { deleteAnomalyDetector(detector.getDetectorId(), client()); }); + Assert.assertTrue(exception.getMessage().contains("Detector job is running")); } }