diff --git a/bwc-test/src/test/java/org/opensearch/security/bwc/SecurityBackwardsCompatibilityIT.java b/bwc-test/src/test/java/org/opensearch/security/bwc/SecurityBackwardsCompatibilityIT.java index bd296fa90d..6767a43ddd 100644 --- a/bwc-test/src/test/java/org/opensearch/security/bwc/SecurityBackwardsCompatibilityIT.java +++ b/bwc-test/src/test/java/org/opensearch/security/bwc/SecurityBackwardsCompatibilityIT.java @@ -32,7 +32,6 @@ import org.apache.hc.core5.reactor.ssl.TlsDetails; import org.apache.hc.core5.ssl.SSLContextBuilder; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Assume; import org.junit.Before; @@ -48,10 +47,12 @@ import org.opensearch.security.bwc.helper.RestHelper; import org.opensearch.test.rest.OpenSearchRestTestCase; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; public class SecurityBackwardsCompatibilityIT extends OpenSearchRestTestCase { @@ -199,7 +200,7 @@ public void testDataIngestionAndSearchBackwardsCompatibility() throws Exception public void testNodeStats() throws IOException { List responses = RestHelper.requestAgainstAllNodes(client(), "GET", "_nodes/stats", null); - responses.forEach(r -> Assert.assertEquals(200, r.getStatusLine().getStatusCode())); + responses.forEach(r -> assertThat(r.getStatusLine().getStatusCode(), is(200))); } @SuppressWarnings("unchecked") @@ -246,7 +247,7 @@ private void ingestData(String index) throws IOException { "_bulk?refresh=wait_for", RestHelper.toHttpEntity(bulkRequestBody.toString()) ); - responses.forEach(r -> assertEquals(200, r.getStatusLine().getStatusCode())); + responses.forEach(r -> assertThat(r.getStatusLine().getStatusCode(), is(200))); } } @@ -264,7 +265,7 @@ private void searchMatchAll(String index) throws IOException { index + "/_search", RestHelper.toHttpEntity(matchAllQuery) ); - responses.forEach(r -> assertEquals(200, r.getStatusLine().getStatusCode())); + responses.forEach(r -> assertThat(r.getStatusLine().getStatusCode(), is(200))); } } diff --git a/src/integrationTest/java/org/opensearch/security/api/InternalUsersRestApiIntegrationTest.java b/src/integrationTest/java/org/opensearch/security/api/InternalUsersRestApiIntegrationTest.java index 884f2ce2a6..59c29b1ca7 100644 --- a/src/integrationTest/java/org/opensearch/security/api/InternalUsersRestApiIntegrationTest.java +++ b/src/integrationTest/java/org/opensearch/security/api/InternalUsersRestApiIntegrationTest.java @@ -704,7 +704,7 @@ public void parallelPutRequests() throws Exception { case HttpStatus.SC_OK: break; default: - Assert.assertEquals(HttpStatus.SC_CONFLICT, sc); + assertThat(sc, is(HttpStatus.SC_CONFLICT)); break; } } diff --git a/src/integrationTest/java/org/opensearch/test/framework/cluster/LocalOpenSearchCluster.java b/src/integrationTest/java/org/opensearch/test/framework/cluster/LocalOpenSearchCluster.java index e7b69b0ef7..96da63d9fb 100644 --- a/src/integrationTest/java/org/opensearch/test/framework/cluster/LocalOpenSearchCluster.java +++ b/src/integrationTest/java/org/opensearch/test/framework/cluster/LocalOpenSearchCluster.java @@ -70,11 +70,12 @@ import org.opensearch.transport.BindTransportException; import static java.util.Objects.requireNonNull; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.test.framework.cluster.NodeType.CLIENT; import static org.opensearch.test.framework.cluster.NodeType.CLUSTER_MANAGER; import static org.opensearch.test.framework.cluster.NodeType.DATA; import static org.opensearch.test.framework.cluster.PortAllocator.TCP; -import static org.junit.Assert.assertEquals; /** * Encapsulates all the logic to start a local OpenSearch cluster - without any configuration of the security plugin. @@ -339,7 +340,7 @@ public void waitForCluster(ClusterHealthStatus status, TimeValue timeout, int ex log.debug("... cluster state ok {} with {} nodes", healthResponse.getStatus().name(), healthResponse.getNumberOfNodes()); } - assertEquals(expectedNodeCount, healthResponse.getNumberOfNodes()); + assertThat(healthResponse.getNumberOfNodes(), is(expectedNodeCount)); } diff --git a/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java b/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java index 6e70034f9b..fcd7dd2160 100644 --- a/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java +++ b/src/test/java/com/amazon/dlic/auth/http/jwt/HTTPJwtAuthenticatorTest.java @@ -38,6 +38,8 @@ import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -156,11 +158,11 @@ public void testParsePrevGeneratedJwt() { ); Assert.assertNotNull(credentials); - Assert.assertEquals("horst", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); - Assert.assertEquals(5, credentials.getAttributes().size()); - Assert.assertEquals("854113533", credentials.getAttributes().get("attr.jwt.nbf")); - Assert.assertEquals("4853843133", credentials.getAttributes().get("attr.jwt.exp")); + assertThat(credentials.getUsername(), is("horst")); + assertThat(credentials.getBackendRoles().size(), is(0)); + assertThat(credentials.getAttributes().size(), is(5)); + assertThat(credentials.getAttributes().get("attr.jwt.nbf"), is("854113533")); + assertThat(credentials.getAttributes().get("attr.jwt.exp"), is("4853843133")); } @Test @@ -211,9 +213,9 @@ public void testBearer() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); - Assert.assertEquals(2, credentials.getAttributes().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(0)); + assertThat(credentials.getAttributes().size(), is(2)); } @Test @@ -259,8 +261,8 @@ public void testRoles() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); - Assert.assertEquals(2, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(2)); } @Test @@ -272,8 +274,8 @@ public void testNullClaim() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -285,8 +287,8 @@ public void testNonStringClaim() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); - Assert.assertEquals(1, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(1)); Assert.assertTrue(credentials.getBackendRoles().contains("123")); } @@ -299,8 +301,8 @@ public void testRolesMissing() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -323,8 +325,8 @@ public void testAlternativeSubject() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Dr. Who", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Dr. Who")); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -336,8 +338,8 @@ public void testNonStringAlternativeSubject() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("false", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("false")); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -358,8 +360,8 @@ public void testUrlParam() throws Exception { AuthCredentials credentials = jwtAuth.extractCredentials(req.asSecurityRequest(), null); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); - Assert.assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -411,8 +413,8 @@ public void testRS256() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals("Leonard McCoy", creds.getUsername()); - Assert.assertEquals(0, creds.getBackendRoles().size()); + assertThat(creds.getUsername(), is("Leonard McCoy")); + assertThat(creds.getBackendRoles().size(), is(0)); } @Test @@ -437,8 +439,8 @@ public void testES512() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals("Leonard McCoy", creds.getUsername()); - Assert.assertEquals(0, creds.getBackendRoles().size()); + assertThat(creds.getUsername(), is("Leonard McCoy")); + assertThat(creds.getBackendRoles().size(), is(0)); } @Test @@ -452,8 +454,8 @@ public void testRolesArray() throws Exception { ); Assert.assertNotNull(credentials); - Assert.assertEquals("John Doe", credentials.getUsername()); - Assert.assertEquals(3, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("John Doe")); + assertThat(credentials.getBackendRoles().size(), is(3)); Assert.assertTrue(credentials.getBackendRoles().contains("a")); Assert.assertTrue(credentials.getBackendRoles().contains("b")); Assert.assertTrue(credentials.getBackendRoles().contains("3rd")); @@ -468,7 +470,7 @@ public void testRequiredAudienceWithCorrectAudience() { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); } @Test @@ -493,7 +495,7 @@ public void testRequiredAudienceWithCorrectAtLeastOneAudience() { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); } @Test @@ -518,7 +520,7 @@ public void testRequiredIssuerWithCorrectAudience() { ); Assert.assertNotNull(credentials); - Assert.assertEquals("Leonard McCoy", credentials.getUsername()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); } @Test diff --git a/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/HTTPJwtKeyByOpenIdConnectAuthenticatorTest.java b/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/HTTPJwtKeyByOpenIdConnectAuthenticatorTest.java index 656922bb7a..6253d2ca72 100644 --- a/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/HTTPJwtKeyByOpenIdConnectAuthenticatorTest.java +++ b/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/HTTPJwtKeyByOpenIdConnectAuthenticatorTest.java @@ -24,6 +24,9 @@ import org.opensearch.security.user.AuthCredentials; import org.opensearch.security.util.FakeRestRequest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class HTTPJwtKeyByOpenIdConnectAuthenticatorTest { protected static MockIpdServer mockIdpServer; @@ -58,10 +61,10 @@ public void basicTest() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } @Test @@ -80,10 +83,10 @@ public void jwksUriTest() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } @Test @@ -134,10 +137,10 @@ public void jwksMatchAtLeastOneRequiredAudienceInClaimTest() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } @Test @@ -185,8 +188,8 @@ public void jwksUriMissingTest() { ); }); - Assert.assertEquals("Authentication backend failed", exception.getMessage()); - Assert.assertEquals(OpenSearchSecurityException.class, exception.getClass()); + assertThat(exception.getMessage(), is("Authentication backend failed")); + assertThat(exception.getClass(), is(OpenSearchSecurityException.class)); } @Test @@ -208,10 +211,10 @@ public void testEscapeKid() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } @Test @@ -231,10 +234,10 @@ public void bearerTest() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } @Test @@ -255,8 +258,8 @@ public void testRoles() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(TestJwts.TEST_ROLES, creds.getBackendRoles()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getBackendRoles(), is(TestJwts.TEST_ROLES)); } @Test @@ -366,10 +369,10 @@ public void testRS256() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } @Test @@ -404,10 +407,10 @@ public void testPeculiarJsonEscaping() { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } } diff --git a/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/KeySetRetrieverTest.java b/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/KeySetRetrieverTest.java index 3030d1775e..472cfa1e39 100644 --- a/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/KeySetRetrieverTest.java +++ b/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/KeySetRetrieverTest.java @@ -32,7 +32,6 @@ import org.apache.hc.core5.ssl.SSLContextBuilder; import org.apache.hc.core5.ssl.SSLContexts; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -41,6 +40,9 @@ import com.amazon.dlic.util.SettingsBasedSSLConfigurator; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class KeySetRetrieverTest { protected static MockIpdServer mockIdpServer; @@ -64,12 +66,12 @@ public void cacheTest() { keySetRetriever.get(); - Assert.assertEquals(1, keySetRetriever.getOidcCacheMisses()); - Assert.assertEquals(0, keySetRetriever.getOidcCacheHits()); + assertThat(keySetRetriever.getOidcCacheMisses(), is(1)); + assertThat(keySetRetriever.getOidcCacheHits(), is(0)); keySetRetriever.get(); - Assert.assertEquals(1, keySetRetriever.getOidcCacheMisses()); - Assert.assertEquals(1, keySetRetriever.getOidcCacheHits()); + assertThat(keySetRetriever.getOidcCacheMisses(), is(1)); + assertThat(keySetRetriever.getOidcCacheHits(), is(1)); } @Test @@ -87,7 +89,7 @@ protected void handleDiscoverRequest(HttpRequest request, ClassicHttpResponse re try { String sha256Fingerprint = Hashing.sha256().hashBytes(peerCert.getEncoded()).toString(); - Assert.assertEquals("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68", sha256Fingerprint); + assertThat(sha256Fingerprint, is("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68")); } catch (CertificateEncodingException e) { throw new RuntimeException(e); diff --git a/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/SingleKeyHTTPJwtKeyByOpenIdConnectAuthenticatorTest.java b/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/SingleKeyHTTPJwtKeyByOpenIdConnectAuthenticatorTest.java index 196e91be21..6e3548926e 100644 --- a/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/SingleKeyHTTPJwtKeyByOpenIdConnectAuthenticatorTest.java +++ b/src/test/java/com/amazon/dlic/auth/http/jwt/keybyoidc/SingleKeyHTTPJwtKeyByOpenIdConnectAuthenticatorTest.java @@ -22,6 +22,9 @@ import org.opensearch.security.user.AuthCredentials; import org.opensearch.security.util.FakeRestRequest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SingleKeyHTTPJwtKeyByOpenIdConnectAuthenticatorTest { @Test @@ -39,10 +42,10 @@ public void basicTest() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } finally { try { @@ -89,10 +92,10 @@ public void noAlgTest() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } finally { try { mockIdpServer.close(); @@ -139,10 +142,10 @@ public void keyExchangeTest() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); creds = jwtAuth.extractCredentials( new FakeRestRequest(ImmutableMap.of("Authorization", TestJwts.NoKid.MC_COY_SIGNED_RSA_2), new HashMap()) @@ -167,10 +170,10 @@ public void keyExchangeTest() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } finally { try { @@ -190,10 +193,10 @@ public void keyExchangeTest() throws Exception { ); Assert.assertNotNull(creds); - Assert.assertEquals(TestJwts.MCCOY_SUBJECT, creds.getUsername()); - Assert.assertEquals(List.of(TestJwts.TEST_AUDIENCE).toString(), creds.getAttributes().get("attr.jwt.aud")); - Assert.assertEquals(0, creds.getBackendRoles().size()); - Assert.assertEquals(4, creds.getAttributes().size()); + assertThat(creds.getUsername(), is(TestJwts.MCCOY_SUBJECT)); + assertThat(creds.getAttributes().get("attr.jwt.aud"), is(List.of(TestJwts.TEST_AUDIENCE).toString())); + assertThat(creds.getBackendRoles().size(), is(0)); + assertThat(creds.getAttributes().size(), is(4)); } finally { try { diff --git a/src/test/java/com/amazon/dlic/auth/http/saml/HTTPSamlAuthenticatorTest.java b/src/test/java/com/amazon/dlic/auth/http/saml/HTTPSamlAuthenticatorTest.java index bba2ee8b5c..e7889aa825 100644 --- a/src/test/java/com/amazon/dlic/auth/http/saml/HTTPSamlAuthenticatorTest.java +++ b/src/test/java/com/amazon/dlic/auth/http/saml/HTTPSamlAuthenticatorTest.java @@ -62,6 +62,7 @@ import org.opensaml.saml.saml2.core.NameIDType; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static com.amazon.dlic.auth.http.saml.HTTPSamlAuthenticator.IDP_METADATA_CONTENT; import static com.amazon.dlic.auth.http.saml.HTTPSamlAuthenticator.IDP_METADATA_URL; @@ -158,7 +159,7 @@ public void testRawHMACSettings() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } @Test @@ -200,7 +201,7 @@ public void basicTest() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } } @@ -254,7 +255,7 @@ public void decryptAssertionsTest() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } @Test @@ -296,10 +297,10 @@ public void shouldUnescapeSamlEntitiesTest() throws Exception { Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization); SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("ABC\\User1", jwt.getJWTClaimsSet().getClaim("sub")); - Assert.assertEquals("ABC\\User1", samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getJWTClaimsSet())); - Assert.assertEquals("[ABC\\Admin]", String.valueOf(jwt.getJWTClaimsSet().getClaim("roles"))); - Assert.assertEquals("ABC\\Admin", samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0]); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("ABC\\User1")); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getJWTClaimsSet()), is("ABC\\User1")); + assertThat(String.valueOf(jwt.getJWTClaimsSet().getClaim("roles")), is("[ABC\\Admin]")); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0], is("ABC\\Admin")); } @@ -342,10 +343,10 @@ public void shouldUnescapeSamlEntitiesTest2() throws Exception { Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization); SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("ABC\"User1", jwt.getJWTClaimsSet().getClaim("sub")); - Assert.assertEquals("ABC\"User1", samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getJWTClaimsSet())); - Assert.assertEquals("[ABC\"Admin]", String.valueOf(jwt.getJWTClaimsSet().getClaim("roles"))); - Assert.assertEquals("ABC\"Admin", samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0]); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("ABC\"User1")); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getJWTClaimsSet()), is("ABC\"User1")); + assertThat(String.valueOf(jwt.getJWTClaimsSet().getClaim("roles")), is("[ABC\"Admin]")); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0], is("ABC\"Admin")); } @Test @@ -387,10 +388,10 @@ public void shouldNotEscapeSamlEntities() throws Exception { Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization); SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("ABC/User1", jwt.getJWTClaimsSet().getClaim("sub")); - Assert.assertEquals("ABC/User1", samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getJWTClaimsSet())); - Assert.assertEquals("[ABC/Admin]", String.valueOf(jwt.getJWTClaimsSet().getClaim("roles"))); - Assert.assertEquals("ABC/Admin", samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0]); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("ABC/User1")); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getJWTClaimsSet()), is("ABC/User1")); + assertThat(String.valueOf(jwt.getJWTClaimsSet().getClaim("roles")), is("[ABC/Admin]")); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0], is("ABC/Admin")); } @Test @@ -432,7 +433,7 @@ public void shouldNotTrimWhitespaceInJwtRoles() throws Exception { Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization); SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("ABC/Admin", samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0]); + assertThat(samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getJWTClaimsSet())[0], is("ABC/Admin")); } @@ -475,7 +476,7 @@ public void testMetadataBody() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } @Test(expected = RuntimeException.class) @@ -535,7 +536,7 @@ public void unsolicitedSsoTest() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } @Test @@ -571,7 +572,7 @@ public void badUnsolicitedSsoTest() throws Exception { ); SecurityResponse response = sendToAuthenticator(samlAuthenticator, tokenRestRequest).orElseThrow(); - Assert.assertEquals(RestStatus.UNAUTHORIZED.getStatus(), response.getStatus()); + assertThat(response.getStatus(), is(RestStatus.UNAUTHORIZED.getStatus())); } @Test @@ -601,7 +602,7 @@ public void wrongCertTest() throws Exception { RestRequest tokenRestRequest = buildTokenExchangeRestRequest(encodedSamlResponse, authenticateHeaders); SecurityResponse response = sendToAuthenticator(samlAuthenticator, tokenRestRequest).orElseThrow(); - Assert.assertEquals(401, response.getStatus()); + assertThat(response.getStatus(), is(401)); } @Test @@ -628,7 +629,7 @@ public void noSignatureTest() throws Exception { RestRequest tokenRestRequest = buildTokenExchangeRestRequest(encodedSamlResponse, authenticateHeaders); SecurityResponse response = sendToAuthenticator(samlAuthenticator, tokenRestRequest).orElseThrow(); - Assert.assertEquals(401, response.getStatus()); + assertThat(response.getStatus(), is(401)); } @SuppressWarnings("unchecked") @@ -669,7 +670,7 @@ public void rolesTest() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); Assert.assertArrayEquals( new String[] { "a ", "c", "b ", "d", " e", "f", "g", "h", " ", "i" }, ((List) jwt.getJWTClaimsSet().getClaim("roles")).toArray(new String[0]) @@ -711,7 +712,7 @@ public void idpEndpointWithQueryStringTest() throws Exception { SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } @Test @@ -760,7 +761,7 @@ private void commaSeparatedRoles(final String rolesAsString, final Settings.Buil SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); Assert.assertArrayEquals( new String[] { "a", "b" }, ((List) jwt.getJWTClaimsSet().getClaim("roles")).toArray(new String[0]) @@ -879,7 +880,7 @@ public void initialConnectionFailureTest() throws Exception { Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization); SignedJWT jwt = SignedJWT.parse(authorization.replaceAll("\\s*bearer\\s*", "")); - Assert.assertEquals("horst", jwt.getJWTClaimsSet().getClaim("sub")); + assertThat(jwt.getJWTClaimsSet().getClaim("sub"), is("horst")); } } @@ -897,9 +898,9 @@ private AuthenticateHeaders getAutenticateHeaders(HTTPSamlAuthenticator samlAuth Assert.fail("Invalid WWW-Authenticate header: " + wwwAuthenticateHeader); } - Assert.assertEquals("X-Security-IdP", wwwAuthenticateHeaderMatcher.group(1)); - Assert.assertEquals("location", wwwAuthenticateHeaderMatcher.group(4)); - Assert.assertEquals("requestId", wwwAuthenticateHeaderMatcher.group(6)); + assertThat(wwwAuthenticateHeaderMatcher.group(1), is("X-Security-IdP")); + assertThat(wwwAuthenticateHeaderMatcher.group(4), is("location")); + assertThat(wwwAuthenticateHeaderMatcher.group(6), is("requestId")); String location = wwwAuthenticateHeaderMatcher.group(5); String requestId = wwwAuthenticateHeaderMatcher.group(7); diff --git a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendIntegTest.java b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendIntegTest.java index 24389a1086..863db60e82 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendIntegTest.java +++ b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendIntegTest.java @@ -28,6 +28,9 @@ import com.amazon.dlic.auth.ldap.srv.EmbeddedLDAPServer; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class LdapBackendIntegTest extends SingleClusterTest { private static EmbeddedLDAPServer ldapServer = null; @@ -55,7 +58,7 @@ public void testIntegLdapAuthenticationSSL() throws Exception { securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort)); setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), Settings.EMPTY); final RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("jacksonm", "secret")).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader("jacksonm", "secret")).getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -64,7 +67,7 @@ public void testIntegLdapAuthenticationSSLFail() throws Exception { securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort)); setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), Settings.EMPTY); final RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("wrong", "wrong")).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader("wrong", "wrong")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); } @Test @@ -77,13 +80,15 @@ public void testAttributesWithImpersonation() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), settings); final RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - "_opendistro/_security/authinfo", - new BasicHeader("opendistro_security_impersonate_as", "jacksonm"), - encodeBasicHeader("spock", "spocksecret") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + "_opendistro/_security/authinfo", + new BasicHeader("opendistro_security_impersonate_as", "jacksonm"), + encodeBasicHeader("spock", "spocksecret") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("ldap.dn")); Assert.assertTrue(res.getBody().contains("attr.ldap.entryDN")); diff --git a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTest.java b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTest.java index 8e5e2541b8..0d9127b12e 100755 --- a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTest.java +++ b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTest.java @@ -39,7 +39,9 @@ import org.ldaptive.LdapEntry; import org.ldaptive.ReturnAttributes; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; public class LdapBackendTest { @@ -73,7 +75,7 @@ public void testLdapAuthentication() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -120,7 +122,7 @@ public void testLdapAuthenticationBindDn() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -197,7 +199,7 @@ public void testLdapAuthenticationSSL() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -219,7 +221,7 @@ public void testLdapAuthenticationSSLPEMFile() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -232,7 +234,7 @@ public void testLdapAuthenticationSSLPEMText() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -256,7 +258,7 @@ public void testLdapAuthenticationSSLSSLv3() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); } catch (Exception e) { - Assert.assertEquals(e.getCause().getClass(), org.ldaptive.LdapException.class); + assertThat(org.ldaptive.LdapException.class, is(e.getCause().getClass())); Assert.assertTrue(e.getCause().getMessage().contains("Unable to connec")); } @@ -283,7 +285,7 @@ public void testLdapAuthenticationSSLUnknowCipher() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); } catch (Exception e) { - Assert.assertEquals(e.getCause().getClass(), org.ldaptive.LdapException.class); + assertThat(org.ldaptive.LdapException.class, is(e.getCause().getClass())); Assert.assertTrue(e.getCause().getMessage().contains("Unable to connec")); } @@ -310,7 +312,7 @@ public void testLdapAuthenticationSpecialCipherProtocol() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @@ -333,7 +335,7 @@ public void testLdapAuthenticationSSLNoKeystore() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -350,7 +352,7 @@ public void testLdapAuthenticationSSLFailPlain() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); } catch (final Exception e) { - Assert.assertEquals(org.ldaptive.LdapException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(org.ldaptive.LdapException.class)); } } @@ -388,10 +390,10 @@ public void testLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -416,7 +418,7 @@ public void testLdapAuthenticationReturnAttributes() throws Exception { final String[] attributes = user.getUserEntry().getAttributeNames(); Assert.assertNotNull(user); - Assert.assertEquals(3, attributes.length); + assertThat(attributes.length, is(3)); Assert.assertTrue(Arrays.asList(attributes).contains("mail")); Assert.assertTrue(Arrays.asList(attributes).contains("cn")); Assert.assertTrue(Arrays.asList(attributes).contains("uid")); @@ -433,7 +435,7 @@ public void testLdapAuthenticationReferral() throws Exception { final Connection con = LDAPAuthorizationBackend.getConnection(settings, null); try { final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST", ReturnAttributes.ALL.value(), true); - Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn()); + assertThat(ref1.getDn(), is("cn=refsolved,ou=people,o=TEST")); } finally { con.close(); } @@ -481,10 +483,10 @@ public void testLdapEscape() throws Exception { new AuthCredentials("ssign", "ssignsecret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(4)); Assert.assertTrue(user.getRoles().toString().contains("ceo")); } @@ -507,11 +509,11 @@ public void testLdapAuthorizationRoleSearchUsername() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("Michael Jackson", user.getOriginalUsername()); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getUserEntry().getDn()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getOriginalUsername(), is("Michael Jackson")); + assertThat(user.getUserEntry().getDn(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -531,8 +533,8 @@ public void testLdapAuthorizationOnly() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); } @@ -553,8 +555,8 @@ public void testLdapAuthorizationNonDNEntry() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo-ceo")); } @@ -576,8 +578,8 @@ public void testLdapAuthorizationNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested1")); } @@ -600,8 +602,8 @@ public void testLdapNestedRoleFiltering() { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); // filtered out MatcherAssert.assertThat(user.getRoles(), not(hasItem("nested1"))); MatcherAssert.assertThat(user.getRoles(), not(hasItem("nested2"))); @@ -628,8 +630,8 @@ public void testLdapNestedRoleFilteringWithExcludedRolesWildcard() { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); // filtered out MatcherAssert.assertThat(user.getRoles(), not(hasItem("nested1"))); MatcherAssert.assertThat(user.getRoles(), not(hasItem("nested2"))); @@ -656,8 +658,8 @@ public void testLdapdRoleFiltering() { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested1")); MatcherAssert.assertThat(user.getRoles(), hasItem("nested2")); // filtered out @@ -684,8 +686,8 @@ public void testLdapAuthorizationNestedFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); MatcherAssert.assertThat(user.getRoles(), hasItem("nested2")); } @@ -708,8 +710,8 @@ public void testLdapAuthorizationDnNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); MatcherAssert.assertThat(user.getRoles(), hasItem("cn=nested1,ou=groups,o=TEST")); } @@ -732,8 +734,8 @@ public void testLdapAuthorizationDn() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("cn=ceo,ou=groups,o=TEST")); } @@ -751,7 +753,7 @@ public void testLdapAuthenticationUserNameAttribute() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); + assertThat(user.getName(), is("jacksonm")); } @Test @@ -773,7 +775,7 @@ public void testLdapAuthenticationStartTLS() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -796,9 +798,9 @@ public void testLdapAuthorizationSkipUsers() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(0, user.getRoles().size()); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(0)); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -821,9 +823,9 @@ public void testLdapAuthorizationSkipUsersNoDn() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(0, user.getRoles().size()); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(0)); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -846,8 +848,8 @@ public void testLdapAuthorizationNestedAttr() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(8, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(8)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested3")); MatcherAssert.assertThat(user.getRoles(), hasItem("rolemo4")); } @@ -873,8 +875,8 @@ public void testLdapAuthorizationNestedAttrFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(6, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(6)); MatcherAssert.assertThat(user.getRoles(), hasItem("role2")); MatcherAssert.assertThat(user.getRoles(), hasItem("nested1")); @@ -901,8 +903,8 @@ public void testLdapAuthorizationNestedAttrFilterAll() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -927,8 +929,8 @@ public void testLdapAuthorizationNestedAttrFilterAllEqualsNestedFalse() throws E new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -952,8 +954,8 @@ public void testLdapAuthorizationNestedAttrNoRoleSearch() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(3)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested3")); MatcherAssert.assertThat(user.getRoles(), hasItem("rolemo4")); } @@ -970,8 +972,8 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 16, user.getCustomAttributesMap().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(16)); Assert.assertFalse( user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().keySet().contains("attr.ldap.userpassword") @@ -987,7 +989,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); settings = Settings.builder() .putList(ConfigConstants.LDAP_HOSTS, "127.0.0.1:4", "localhost:" + ldapPort) @@ -999,7 +1001,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); } @@ -1023,8 +1025,8 @@ public void testLdapAuthorizationNonDNRoles() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("nondnroles", user.getName()); - Assert.assertEquals(5, user.getRoles().size()); + assertThat(user.getName(), is("nondnroles")); + assertThat(user.getRoles().size(), is(5)); Assert.assertTrue("Roles do not contain non-LDAP role 'kibanauser'", user.getRoles().contains("kibanauser")); Assert.assertTrue("Roles do not contain non-LDAP role 'humanresources'", user.getRoles().contains("humanresources")); Assert.assertTrue("Roles do not contain LDAP role 'dummyempty'", user.getRoles().contains("dummyempty")); @@ -1052,11 +1054,11 @@ public void testLdapSpecial186() throws Exception { new AuthCredentials("spec186", "spec186".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST", user.getName()); - Assert.assertEquals("AA BB/CC (DD) my, company end=with=whitespace ", user.getUserEntry().getAttribute("cn").getStringValue()); + assertThat(user.getName(), is("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST")); + assertThat(user.getUserEntry().getAttribute("cn").getStringValue(), is("AA BB/CC (DD) my, company end=with=whitespace ")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().toString().contains("ROLE/(186) consists of\\, special=")); Assert.assertTrue(user.getRoles().toString().contains("ROLEx(186n) consists of\\, special=")); Assert.assertTrue(user.getRoles().toString().contains("ROLE/(186nn) consists of\\, special=")); @@ -1100,11 +1102,11 @@ public void testLdapSpecial186_2() throws Exception { new AuthCredentials("spec186", "spec186".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST", user.getName()); - Assert.assertEquals("AA BB/CC (DD) my, company end=with=whitespace ", user.getUserEntry().getAttribute("cn").getStringValue()); + assertThat(user.getName(), is("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST")); + assertThat(user.getUserEntry().getAttribute("cn").getStringValue(), is("AA BB/CC (DD) my, company end=with=whitespace ")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186) consists of\\, special\\=chars\\ ")); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186n) consists of\\, special\\=chars\\ ")); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186nn) consists of\\, special\\=chars\\ ")); @@ -1167,7 +1169,7 @@ public void testMultiCn() throws Exception { new AuthCredentials("multi", "multi".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=cabc,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=cabc,ou=people,o=TEST")); } @AfterClass diff --git a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestClientCert.java b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestClientCert.java index b5cc56f84b..bf358b92ad 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestClientCert.java +++ b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestClientCert.java @@ -29,6 +29,9 @@ import com.amazon.dlic.auth.ldap.backend.LDAPAuthenticationBackend; import com.amazon.dlic.auth.ldap.util.ConfigConstants; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + @Ignore public class LdapBackendTestClientCert { @@ -158,7 +161,7 @@ public void testBindDnAuthLocalhost() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } @Test @@ -187,7 +190,7 @@ public void testLdapSslAuth() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } @Test @@ -219,7 +222,7 @@ public void testLdapSslAuthPem() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } @Test @@ -248,7 +251,7 @@ public void testLdapSslAuthNo() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } public void testLdapAuthenticationSSL() throws Exception { @@ -283,7 +286,7 @@ public void testLdapAuthenticationSSL() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } public static File getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) { diff --git a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestNewStyleConfig.java b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestNewStyleConfig.java index a6ae9eb79d..5522501527 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestNewStyleConfig.java +++ b/src/test/java/com/amazon/dlic/auth/ldap/LdapBackendTestNewStyleConfig.java @@ -38,7 +38,9 @@ import org.ldaptive.LdapEntry; import org.ldaptive.ReturnAttributes; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; public class LdapBackendTestNewStyleConfig { @@ -72,7 +74,7 @@ public void testLdapAuthentication() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -120,7 +122,7 @@ public void testLdapAuthenticationBindDn() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -197,7 +199,7 @@ public void testLdapAuthenticationSSL() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -219,7 +221,7 @@ public void testLdapAuthenticationSSLPEMFile() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -233,7 +235,7 @@ public void testLdapAuthenticationSSLPEMText() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -257,7 +259,7 @@ public void testLdapAuthenticationSSLSSLv3() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); } catch (Exception e) { - Assert.assertEquals(e.getCause().getClass(), org.ldaptive.LdapException.class); + assertThat(org.ldaptive.LdapException.class, is(e.getCause().getClass())); Assert.assertTrue(e.getCause().getMessage().contains("Unable to connec")); } @@ -284,7 +286,7 @@ public void testLdapAuthenticationSSLUnknownCipher() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); } catch (Exception e) { - Assert.assertEquals(e.getCause().getClass(), org.ldaptive.LdapException.class); + assertThat(org.ldaptive.LdapException.class, is(e.getCause().getClass())); Assert.assertTrue(e.getCause().getMessage().contains("Unable to connec")); } @@ -311,7 +313,7 @@ public void testLdapAuthenticationSpecialCipherProtocol() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @@ -334,7 +336,7 @@ public void testLdapAuthenticationSSLNoKeystore() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -351,7 +353,7 @@ public void testLdapAuthenticationSSLFailPlain() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); } catch (final Exception e) { - Assert.assertEquals(org.ldaptive.LdapException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(org.ldaptive.LdapException.class)); } } @@ -389,10 +391,10 @@ public void testLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -406,7 +408,7 @@ public void testLdapAuthenticationReferral() throws Exception { final Connection con = LDAPAuthorizationBackend.getConnection(settings, null); try { final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST", ReturnAttributes.ALL.value(), true); - Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn()); + assertThat(ref1.getDn(), is("cn=refsolved,ou=people,o=TEST")); } finally { con.close(); } @@ -455,10 +457,10 @@ public void testLdapEscape() throws Exception { new AuthCredentials("ssign", "ssignsecret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(4)); Assert.assertTrue(user.getRoles().toString().contains("ceo")); } @@ -481,11 +483,11 @@ public void testLdapAuthorizationRoleSearchUsername() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("Michael Jackson", user.getOriginalUsername()); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getUserEntry().getDn()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getOriginalUsername(), is("Michael Jackson")); + assertThat(user.getUserEntry().getDn(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -505,8 +507,8 @@ public void testLdapAuthorizationOnly() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); } @@ -528,8 +530,8 @@ public void testLdapAuthorizationNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested1")); } @@ -552,8 +554,8 @@ public void testLdapAuthorizationNestedFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo")); MatcherAssert.assertThat(user.getRoles(), hasItem("nested2")); } @@ -576,8 +578,8 @@ public void testLdapAuthorizationDnNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); MatcherAssert.assertThat(user.getRoles(), hasItem("cn=nested1,ou=groups,o=TEST")); } @@ -600,8 +602,8 @@ public void testLdapAuthorizationDn() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("cn=ceo,ou=groups,o=TEST")); } @@ -619,7 +621,7 @@ public void testLdapAuthenticationUserNameAttribute() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); + assertThat(user.getName(), is("jacksonm")); } @Test @@ -641,7 +643,7 @@ public void testLdapAuthenticationStartTLS() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -664,9 +666,9 @@ public void testLdapAuthorizationSkipUsers() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(0, user.getRoles().size()); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(0)); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -689,8 +691,8 @@ public void testLdapAuthorizationNestedAttr() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(8, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(8)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested3")); MatcherAssert.assertThat(user.getRoles(), hasItem("rolemo4")); } @@ -716,8 +718,8 @@ public void testLdapAuthorizationNestedAttrFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(6, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(6)); MatcherAssert.assertThat(user.getRoles(), hasItem("role2")); MatcherAssert.assertThat(user.getRoles(), hasItem("nested1")); @@ -744,8 +746,8 @@ public void testLdapAuthorizationNestedAttrFilterAll() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -771,8 +773,8 @@ public void testLdapAuthorizationNestedAttrFilterAllEqualsNestedFalse() throws E new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -796,8 +798,8 @@ public void testLdapAuthorizationNestedAttrNoRoleSearch() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(3)); MatcherAssert.assertThat(user.getRoles(), hasItem("nested3")); MatcherAssert.assertThat(user.getRoles(), hasItem("rolemo4")); } @@ -814,8 +816,8 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 16, user.getCustomAttributesMap().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(16)); Assert.assertFalse(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().containsKey("attr.ldap.userpassword")); settings = Settings.builder() @@ -828,7 +830,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); settings = Settings.builder() .putList(ConfigConstants.LDAP_HOSTS, "127.0.0.1:4", "localhost:" + ldapPort) @@ -840,7 +842,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); } @@ -864,8 +866,8 @@ public void testLdapAuthorizationNonDNRoles() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("nondnroles", user.getName()); - Assert.assertEquals(5, user.getRoles().size()); + assertThat(user.getName(), is("nondnroles")); + assertThat(user.getRoles().size(), is(5)); Assert.assertTrue("Roles do not contain non-LDAP role 'kibanauser'", user.getRoles().contains("kibanauser")); Assert.assertTrue("Roles do not contain non-LDAP role 'humanresources'", user.getRoles().contains("humanresources")); Assert.assertTrue("Roles do not contain LDAP role 'dummyempty'", user.getRoles().contains("dummyempty")); @@ -891,7 +893,7 @@ public void testChainedLdapAuthentication1() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -909,7 +911,7 @@ public void testChainedLdapAuthentication2() throws Exception { new AuthCredentials("presleye", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Elvis Presley,ou=people2,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Elvis Presley,ou=people2,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -969,14 +971,14 @@ public void testChainedLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().contains("ceo")); Assert.assertTrue(user.getRoles().contains("king")); Assert.assertTrue(user.getRoles().contains("role2")); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -1000,8 +1002,8 @@ public void testCrossChainedLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Freddy Mercury,ou=people2,o=TEST", user.getName()); - Assert.assertEquals(1, user.getRoles().size()); + assertThat(user.getName(), is("cn=Freddy Mercury,ou=people2,o=TEST")); + assertThat(user.getRoles().size(), is(1)); Assert.assertTrue(user.getRoles().contains("crossnested2")); // The user is NOT in crossnested1! diff --git a/src/test/java/com/amazon/dlic/auth/ldap/UtilsTest.java b/src/test/java/com/amazon/dlic/auth/ldap/UtilsTest.java index ce22bf6036..05873fc7c8 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap/UtilsTest.java +++ b/src/test/java/com/amazon/dlic/auth/ldap/UtilsTest.java @@ -17,24 +17,27 @@ import org.junit.Assert; import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class UtilsTest { @Test public void testLDAPName() throws Exception { // same ldapname - Assert.assertEquals(new LdapName("CN=1,OU=2,O=3,C=4"), new LdapName("CN=1,OU=2,O=3,C=4")); + assertThat(new LdapName("CN=1,OU=2,O=3,C=4"), is(new LdapName("CN=1,OU=2,O=3,C=4"))); // case differ - Assert.assertEquals(new LdapName("CN=1,OU=2,O=3,C=4".toLowerCase()), new LdapName("CN=1,OU=2,O=3,C=4".toUpperCase())); + assertThat(new LdapName("CN=1,OU=2,O=3,C=4".toUpperCase()), is(new LdapName("CN=1,OU=2,O=3,C=4".toLowerCase()))); // case differ - Assert.assertEquals(new LdapName("CN=abc,OU=xyz,O=3,C=4".toLowerCase()), new LdapName("CN=abc,OU=xyz,O=3,C=4".toUpperCase())); + assertThat(new LdapName("CN=abc,OU=xyz,O=3,C=4".toUpperCase()), is(new LdapName("CN=abc,OU=xyz,O=3,C=4".toLowerCase()))); // same ldapname - Assert.assertEquals(new LdapName("CN=a,OU=2,O=3,C=xxx"), new LdapName("CN=A,OU=2,O=3,C=XxX")); + assertThat(new LdapName("CN=A,OU=2,O=3,C=XxX"), is(new LdapName("CN=a,OU=2,O=3,C=xxx"))); // case differ and spaces - Assert.assertEquals(new LdapName("Cn =1 ,OU=2, O = 3,C=4"), new LdapName("CN= 1,Ou=2,O=3,c=4")); + assertThat(new LdapName("CN= 1,Ou=2,O=3,c=4"), is(new LdapName("Cn =1 ,OU=2, O = 3,C=4"))); // same components, different order Assert.assertNotEquals(new LdapName("CN=1,OU=2,C=4,O=3"), new LdapName("CN=1,OU=2,O=3,C=4")); diff --git a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendIntegTest2.java b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendIntegTest2.java index e4f71ff264..4eaa78392f 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendIntegTest2.java +++ b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendIntegTest2.java @@ -28,6 +28,9 @@ import com.amazon.dlic.auth.ldap.srv.EmbeddedLDAPServer; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class LdapBackendIntegTest2 extends SingleClusterTest { private static EmbeddedLDAPServer ldapServer = null; @@ -55,7 +58,7 @@ public void testIntegLdapAuthenticationSSL() throws Exception { securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort)); setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), Settings.EMPTY); final RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("jacksonm", "secret")).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader("jacksonm", "secret")).getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -64,7 +67,7 @@ public void testIntegLdapAuthenticationSSLFail() throws Exception { securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort)); setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), Settings.EMPTY); final RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("wrong", "wrong")).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader("wrong", "wrong")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); } @Test @@ -77,13 +80,15 @@ public void testAttributesWithImpersonation() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), settings); final RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - "_opendistro/_security/authinfo", - new BasicHeader("opendistro_security_impersonate_as", "jacksonm"), - encodeBasicHeader("spock", "spocksecret") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + "_opendistro/_security/authinfo", + new BasicHeader("opendistro_security_impersonate_as", "jacksonm"), + encodeBasicHeader("spock", "spocksecret") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("ldap.dn")); Assert.assertTrue(res.getBody().contains("attr.ldap.entryDN")); diff --git a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestClientCert2.java b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestClientCert2.java index 64e9521155..bb51ce00a6 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestClientCert2.java +++ b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestClientCert2.java @@ -29,6 +29,9 @@ import com.amazon.dlic.auth.ldap.LdapUser; import com.amazon.dlic.auth.ldap.util.ConfigConstants; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + @Ignore public class LdapBackendTestClientCert2 { @@ -161,7 +164,7 @@ public void testBindDnAuthLocalhost() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } @Test @@ -190,7 +193,7 @@ public void testLdapSslAuth() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } @Test @@ -222,7 +225,7 @@ public void testLdapSslAuthPem() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } @Test @@ -251,7 +254,7 @@ public void testLdapSslAuthNo() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } public void testLdapAuthenticationSSL() throws Exception { @@ -286,7 +289,7 @@ public void testLdapAuthenticationSSL() throws Exception { new AuthCredentials("ldap_hr_employee", "ldap_hr_employee".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("ldap_hr_employee", user.getName()); + assertThat(user.getName(), is("ldap_hr_employee")); } public static File getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) { diff --git a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestNewStyleConfig2.java b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestNewStyleConfig2.java index 6f23e4ab44..dd19b383c2 100644 --- a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestNewStyleConfig2.java +++ b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestNewStyleConfig2.java @@ -48,7 +48,9 @@ import org.ldaptive.LdapEntry; import org.ldaptive.ReturnAttributes; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; @RunWith(Parameterized.class) public class LdapBackendTestNewStyleConfig2 { @@ -98,7 +100,7 @@ public void testLdapAuthentication() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -143,7 +145,7 @@ public void testLdapAuthenticationBindDn() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -220,7 +222,7 @@ public void testLdapAuthenticationSSL() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -241,7 +243,7 @@ public void testLdapAuthenticationSSLPEMFile() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -255,7 +257,7 @@ public void testLdapAuthenticationSSLPEMText() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -279,7 +281,7 @@ public void testLdapAuthenticationSSLSSLv3() throws Exception { ); Assert.fail("Expected Exception"); } catch (Exception e) { - Assert.assertEquals(org.ldaptive.provider.ConnectionException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(org.ldaptive.provider.ConnectionException.class)); Assert.assertTrue(ExceptionUtils.getStackTrace(e).contains("No appropriate protocol")); } @@ -306,7 +308,7 @@ public void testLdapAuthenticationSSLUnknownCipher() throws Exception { ); Assert.fail("Expected Exception"); } catch (Exception e) { - Assert.assertEquals(org.ldaptive.provider.ConnectionException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(org.ldaptive.provider.ConnectionException.class)); Assert.assertTrue( ExceptionUtils.getStackTrace(e), WildcardMatcher.from("*unsupported*ciphersuite*aaa*").test(ExceptionUtils.getStackTrace(e).toLowerCase()) @@ -335,7 +337,7 @@ public void testLdapAuthenticationSpecialCipherProtocol() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @@ -357,7 +359,7 @@ public void testLdapAuthenticationSSLNoKeystore() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -374,7 +376,7 @@ public void testLdapAuthenticationSSLFailPlain() throws Exception { ); Assert.fail("Expected exception"); } catch (final Exception e) { - Assert.assertEquals(IllegalStateException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(IllegalStateException.class)); } } @@ -410,10 +412,10 @@ public void testLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -437,7 +439,7 @@ public void testLdapAuthorizationReturnAttributes() throws Exception { final String[] attributes = user.getUserEntry().getAttributeNames(); Assert.assertNotNull(user); - Assert.assertEquals(3, attributes.length); + assertThat(attributes.length, is(3)); Assert.assertTrue(Arrays.asList(attributes).contains("mail")); Assert.assertTrue(Arrays.asList(attributes).contains("cn")); Assert.assertTrue(Arrays.asList(attributes).contains("uid")); @@ -454,7 +456,7 @@ public void testLdapAuthenticationReferral() throws Exception { try { con.open(); final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST", ReturnAttributes.ALL.value(), true); - Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn()); + assertThat(ref1.getDn(), is("cn=refsolved,ou=people,o=TEST")); } finally { con.close(); } @@ -502,10 +504,10 @@ public void testLdapEscape() throws Exception { new AuthCredentials("ssign", "ssignsecret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(4)); Assert.assertTrue(user.getRoles().toString().contains("ceo")); } @@ -527,11 +529,11 @@ public void testLdapAuthorizationRoleSearchUsername() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("Michael Jackson", user.getOriginalUsername()); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getUserEntry().getDn()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getOriginalUsername(), is("Michael Jackson")); + assertThat(user.getUserEntry().getDn(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -550,9 +552,9 @@ public void testLdapAuthorizationOnly() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); } @Test @@ -573,8 +575,8 @@ public void testLdapAuthorizationNested() throws Exception { new LDAPAuthorizationBackend2(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().contains("nested1")); Assert.assertFalse(user.getRoles().contains("nested2")); } @@ -597,10 +599,10 @@ public void testLdapAuthorizationNestedFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals("nested2", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("nested2")); } @Test @@ -620,9 +622,9 @@ public void testLdapAuthorizationDnNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); - Assert.assertEquals("cn=nested1,ou=groups,o=TEST", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("cn=nested1,ou=groups,o=TEST")); } @Test @@ -643,9 +645,9 @@ public void testLdapAuthorizationDn() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("cn=ceo,ou=groups,o=TEST", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("cn=ceo,ou=groups,o=TEST")); } @Test @@ -661,7 +663,7 @@ public void testLdapAuthenticationUserNameAttribute() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); + assertThat(user.getName(), is("jacksonm")); } @Test @@ -682,7 +684,7 @@ public void testLdapAuthenticationStartTLS() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -704,9 +706,9 @@ public void testLdapAuthorizationSkipUsers() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(0, user.getRoles().size()); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(0)); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -728,10 +730,10 @@ public void testLdapAuthorizationNestedAttr() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(8, user.getRoles().size()); - Assert.assertEquals("nested3", new ArrayList<>(new TreeSet<>(user.getRoles())).get(4)); - Assert.assertEquals("rolemo4", new ArrayList<>(new TreeSet<>(user.getRoles())).get(7)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(8)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(4), is("nested3")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(7), is("rolemo4")); } @Test @@ -754,10 +756,10 @@ public void testLdapAuthorizationNestedAttrFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(6, user.getRoles().size()); - Assert.assertEquals("role2", new ArrayList<>(new TreeSet<>(user.getRoles())).get(4)); - Assert.assertEquals("nested1", new ArrayList<>(new TreeSet<>(user.getRoles())).get(2)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(6)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(4), is("role2")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(2), is("nested1")); } @@ -781,8 +783,8 @@ public void testLdapAuthorizationNestedAttrFilterAll() { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @Test @@ -806,8 +808,8 @@ public void testLdapAuthorizationNestedAttrFilterAllEqualsNestedFalse() throws E new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -830,10 +832,10 @@ public void testLdapAuthorizationNestedAttrNoRoleSearch() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); - Assert.assertEquals("nested3", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); - Assert.assertEquals("rolemo4", new ArrayList<>(new TreeSet<>(user.getRoles())).get(2)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(3)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("nested3")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(2), is("rolemo4")); } @Test @@ -847,8 +849,8 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 16, user.getCustomAttributesMap().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(16)); Assert.assertFalse( user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().keySet().contains("attr.ldap.userpassword") @@ -863,7 +865,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); settings = createBaseSettings().putList(ConfigConstants.LDAP_HOSTS, "127.0.0.1:4", "localhost:" + ldapPort) .put("users.u1.search", "(uid={0})") @@ -874,7 +876,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); } @@ -897,8 +899,8 @@ public void testLdapAuthorizationNonDNRoles() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("nondnroles", user.getName()); - Assert.assertEquals(5, user.getRoles().size()); + assertThat(user.getName(), is("nondnroles")); + assertThat(user.getRoles().size(), is(5)); Assert.assertTrue("Roles do not contain non-LDAP role 'kibanauser'", user.getRoles().contains("kibanauser")); Assert.assertTrue("Roles do not contain non-LDAP role 'humanresources'", user.getRoles().contains("humanresources")); Assert.assertTrue("Roles do not contain LDAP role 'dummyempty'", user.getRoles().contains("dummyempty")); @@ -923,7 +925,7 @@ public void testChainedLdapAuthentication1() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -940,7 +942,7 @@ public void testChainedLdapAuthentication2() throws Exception { new AuthCredentials("presleye", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Elvis Presley,ou=people2,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Elvis Presley,ou=people2,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -997,14 +999,14 @@ public void testChainedLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().contains("ceo")); Assert.assertTrue(user.getRoles().contains("king")); Assert.assertTrue(user.getRoles().contains("role2")); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -1027,8 +1029,8 @@ public void testCrossChainedLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Freddy Mercury,ou=people2,o=TEST", user.getName()); - Assert.assertEquals(1, user.getRoles().size()); + assertThat(user.getName(), is("cn=Freddy Mercury,ou=people2,o=TEST")); + assertThat(user.getRoles().size(), is(1)); Assert.assertTrue(user.getRoles().contains("crossnested2")); // The user is NOT in crossnested1! @@ -1051,8 +1053,8 @@ public void testLdapAuthorizationNonDNEntry() throws Exception { new LDAPAuthorizationBackend2(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo-ceo")); } @@ -1073,11 +1075,11 @@ public void testLdapSpecial186() throws Exception { new AuthCredentials("spec186", "spec186".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST", user.getName()); - Assert.assertEquals("AA BB/CC (DD) my, company end=with=whitespace ", user.getUserEntry().getAttribute("cn").getStringValue()); + assertThat(user.getName(), is("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST")); + assertThat(user.getUserEntry().getAttribute("cn").getStringValue(), is("AA BB/CC (DD) my, company end=with=whitespace ")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().toString().contains("ROLE/(186) consists of\\, special=")); Assert.assertTrue(user.getRoles().toString().contains("ROLEx(186n) consists of\\, special=")); Assert.assertTrue(user.getRoles().toString().contains("ROLE/(186nn) consists of\\, special=")); @@ -1121,11 +1123,11 @@ public void testLdapSpecial186_2() throws Exception { new AuthCredentials("spec186", "spec186".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST", user.getName()); - Assert.assertEquals("AA BB/CC (DD) my, company end=with=whitespace ", user.getUserEntry().getAttribute("cn").getStringValue()); + assertThat(user.getName(), is("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST")); + assertThat(user.getUserEntry().getAttribute("cn").getStringValue(), is("AA BB/CC (DD) my, company end=with=whitespace ")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186) consists of\\, special\\=chars\\ ")); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186n) consists of\\, special\\=chars\\ ")); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186nn) consists of\\, special\\=chars\\ ")); diff --git a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestOldStyleConfig2.java b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestOldStyleConfig2.java index 5c4a85d6cc..41776e62d2 100755 --- a/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestOldStyleConfig2.java +++ b/src/test/java/com/amazon/dlic/auth/ldap2/LdapBackendTestOldStyleConfig2.java @@ -47,7 +47,9 @@ import org.ldaptive.LdapEntry; import org.ldaptive.ReturnAttributes; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; @RunWith(Parameterized.class) public class LdapBackendTestOldStyleConfig2 { @@ -99,7 +101,7 @@ public void testLdapAuthentication() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -114,7 +116,7 @@ public void testLdapAuthenticationPooled() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test(expected = OpenSearchSecurityException.class) @@ -159,7 +161,7 @@ public void testLdapAuthenticationBindDn() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -248,7 +250,7 @@ public void testLdapAuthenticationSSL() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -270,7 +272,7 @@ public void testLdapAuthenticationSSLPooled() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -291,7 +293,7 @@ public void testLdapAuthenticationSSLPEMFile() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -305,7 +307,7 @@ public void testLdapAuthenticationSSLPEMText() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -329,7 +331,7 @@ public void testLdapAuthenticationSSLSSLv3() throws Exception { ); Assert.fail("Expected Exception"); } catch (Exception e) { - Assert.assertEquals(org.ldaptive.provider.ConnectionException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(org.ldaptive.provider.ConnectionException.class)); Assert.assertTrue(ExceptionUtils.getStackTrace(e).contains("No appropriate protocol")); } @@ -356,11 +358,7 @@ public void testLdapAuthenticationSSLUnknowCipher() throws Exception { ); Assert.fail("Expected Exception"); } catch (Exception e) { - Assert.assertEquals( - e.getCause().getClass().toString(), - org.ldaptive.provider.ConnectionException.class, - e.getCause().getClass() - ); + assertThat(e.getCause().getClass().toString(), org.ldaptive.provider.ConnectionException.class, is(e.getCause().getClass())); Assert.assertTrue(ExceptionUtils.getStackTrace(e), EXCEPTION_MATCHER.test(ExceptionUtils.getStackTrace(e).toLowerCase())); } @@ -386,7 +384,7 @@ public void testLdapAuthenticationSpecialCipherProtocol() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @@ -408,7 +406,7 @@ public void testLdapAuthenticationSSLNoKeystore() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -425,7 +423,7 @@ public void testLdapAuthenticationSSLFailPlain() throws Exception { ); Assert.fail("Expected exception"); } catch (final Exception e) { - Assert.assertEquals(IllegalStateException.class, e.getCause().getClass()); + assertThat(e.getCause().getClass(), is(IllegalStateException.class)); } } @@ -461,10 +459,10 @@ public void testLdapAuthorization() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -488,10 +486,10 @@ public void testLdapAuthorizationPooled() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -505,7 +503,7 @@ public void testLdapAuthenticationReferral() throws Exception { try { con.open(); final LdapEntry ref1 = LdapHelper.lookup(con, "cn=Ref1,ou=people,o=TEST", ReturnAttributes.ALL.value(), true); - Assert.assertEquals("cn=refsolved,ou=people,o=TEST", ref1.getDn()); + assertThat(ref1.getDn(), is("cn=refsolved,ou=people,o=TEST")); } finally { con.close(); } @@ -553,10 +551,10 @@ public void testLdapEscape() throws Exception { new AuthCredentials("ssign", "ssignsecret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals("cn=Special\\, Sign,ou=people,o=TEST", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("cn=Special\\, Sign,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(4)); Assert.assertTrue(user.getRoles().toString().contains("ceo")); } @@ -578,11 +576,11 @@ public void testLdapAuthorizationRoleSearchUsername() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("Michael Jackson", user.getOriginalUsername()); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getUserEntry().getDn()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getOriginalUsername(), is("Michael Jackson")); + assertThat(user.getUserEntry().getDn(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -601,9 +599,9 @@ public void testLdapAuthorizationOnly() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); } @Test @@ -623,9 +621,9 @@ public void testLdapAuthorizationNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); - Assert.assertEquals("nested1", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("nested1")); } @Test @@ -646,10 +644,10 @@ public void testLdapAuthorizationNestedFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("ceo", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); - Assert.assertEquals("nested2", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("ceo")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("nested2")); } @Test @@ -669,9 +667,9 @@ public void testLdapAuthorizationDnNested() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); - Assert.assertEquals("cn=nested1,ou=groups,o=TEST", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("cn=nested1,ou=groups,o=TEST")); } @Test @@ -692,9 +690,9 @@ public void testLdapAuthorizationDn() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); - Assert.assertEquals("cn=ceo,ou=groups,o=TEST", new ArrayList<>(new TreeSet<>(user.getRoles())).get(0)); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(0), is("cn=ceo,ou=groups,o=TEST")); } @Test @@ -710,7 +708,7 @@ public void testLdapAuthenticationUserNameAttribute() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); + assertThat(user.getName(), is("jacksonm")); } @Test @@ -731,7 +729,7 @@ public void testLdapAuthenticationStartTLS() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); } @Test @@ -753,9 +751,9 @@ public void testLdapAuthorizationSkipUsers() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(0, user.getRoles().size()); - Assert.assertEquals(user.getName(), user.getUserEntry().getDn()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getRoles().size(), is(0)); + assertThat(user.getUserEntry().getDn(), is(user.getName())); } @Test @@ -777,10 +775,10 @@ public void testLdapAuthorizationNestedAttr() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(8, user.getRoles().size()); - Assert.assertEquals("nested3", new ArrayList<>(new TreeSet<>(user.getRoles())).get(4)); - Assert.assertEquals("rolemo4", new ArrayList<>(new TreeSet<>(user.getRoles())).get(7)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(8)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(4), is("nested3")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(7), is("rolemo4")); } @Test @@ -803,10 +801,10 @@ public void testLdapAuthorizationNestedAttrFilter() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(6, user.getRoles().size()); - Assert.assertEquals("role2", new ArrayList<>(new TreeSet<>(user.getRoles())).get(4)); - Assert.assertEquals("nested1", new ArrayList<>(new TreeSet<>(user.getRoles())).get(2)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(6)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(4), is("role2")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(2), is("nested1")); } @@ -830,8 +828,8 @@ public void testLdapAuthorizationNestedAttrFilterAll() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -856,8 +854,8 @@ public void testLdapAuthorizationNestedAttrFilterAllEqualsNestedFalse() throws E new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(4, user.getRoles().size()); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(4)); } @@ -880,10 +878,10 @@ public void testLdapAuthorizationNestedAttrNoRoleSearch() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("spock", user.getName()); - Assert.assertEquals(3, user.getRoles().size()); - Assert.assertEquals("nested3", new ArrayList<>(new TreeSet<>(user.getRoles())).get(1)); - Assert.assertEquals("rolemo4", new ArrayList<>(new TreeSet<>(user.getRoles())).get(2)); + assertThat(user.getName(), is("spock")); + assertThat(user.getRoles().size(), is(3)); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(1), is("nested3")); + assertThat(new ArrayList<>(new TreeSet<>(user.getRoles())).get(2), is("rolemo4")); } @Test @@ -897,8 +895,8 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("cn=Michael Jackson,ou=people,o=TEST", user.getName()); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 16, user.getCustomAttributesMap().size()); + assertThat(user.getName(), is("cn=Michael Jackson,ou=people,o=TEST")); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(16)); Assert.assertFalse(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().containsKey("attr.ldap.userpassword")); settings = createBaseSettings().putList(ConfigConstants.LDAP_HOSTS, "127.0.0.1:4", "localhost:" + ldapPort) @@ -910,7 +908,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); settings = createBaseSettings().putList(ConfigConstants.LDAP_HOSTS, "127.0.0.1:4", "localhost:" + ldapPort) .put(ConfigConstants.LDAP_AUTHC_USERSEARCH, "(uid={0})") @@ -921,7 +919,7 @@ public void testCustomAttributes() throws Exception { new AuthCredentials("jacksonm", "secret".getBytes(StandardCharsets.UTF_8)) ); - Assert.assertEquals(user.getCustomAttributesMap().toString(), 2, user.getCustomAttributesMap().size()); + assertThat(user.getCustomAttributesMap().toString(), user.getCustomAttributesMap().size(), is(2)); } @@ -944,8 +942,8 @@ public void testLdapAuthorizationNonDNRoles() throws Exception { new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("nondnroles", user.getName()); - Assert.assertEquals(5, user.getRoles().size()); + assertThat(user.getName(), is("nondnroles")); + assertThat(user.getRoles().size(), is(5)); Assert.assertTrue("Roles do not contain non-LDAP role 'kibanauser'", user.getRoles().contains("kibanauser")); Assert.assertTrue("Roles do not contain non-LDAP role 'humanresources'", user.getRoles().contains("humanresources")); Assert.assertTrue("Roles do not contain LDAP role 'dummyempty'", user.getRoles().contains("dummyempty")); @@ -973,8 +971,8 @@ public void testLdapAuthorizationNonDNEntry() throws Exception { new LDAPAuthorizationBackend2(settings, null).fillRoles(user, null); Assert.assertNotNull(user); - Assert.assertEquals("jacksonm", user.getName()); - Assert.assertEquals(2, user.getRoles().size()); + assertThat(user.getName(), is("jacksonm")); + assertThat(user.getRoles().size(), is(2)); MatcherAssert.assertThat(user.getRoles(), hasItem("ceo-ceo")); } @@ -995,11 +993,11 @@ public void testLdapSpecial186() throws Exception { new AuthCredentials("spec186", "spec186".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST", user.getName()); - Assert.assertEquals("AA BB/CC (DD) my, company end=with=whitespace ", user.getUserEntry().getAttribute("cn").getStringValue()); + assertThat(user.getName(), is("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST")); + assertThat(user.getUserEntry().getAttribute("cn").getStringValue(), is("AA BB/CC (DD) my, company end=with=whitespace ")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().toString().contains("ROLE/(186) consists of\\, special=")); Assert.assertTrue(user.getRoles().toString().contains("ROLEx(186n) consists of\\, special=")); Assert.assertTrue(user.getRoles().toString().contains("ROLE/(186nn) consists of\\, special=")); @@ -1043,11 +1041,11 @@ public void testLdapSpecial186_2() throws Exception { new AuthCredentials("spec186", "spec186".getBytes(StandardCharsets.UTF_8)) ); Assert.assertNotNull(user); - Assert.assertEquals("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST", user.getName()); - Assert.assertEquals("AA BB/CC (DD) my, company end=with=whitespace ", user.getUserEntry().getAttribute("cn").getStringValue()); + assertThat(user.getName(), is("CN=AA BB/CC (DD) my\\, company end\\=with\\=whitespace\\ ,ou=people,o=TEST")); + assertThat(user.getUserEntry().getAttribute("cn").getStringValue(), is("AA BB/CC (DD) my, company end=with=whitespace ")); new LDAPAuthorizationBackend(settings, null).fillRoles(user, null); - Assert.assertEquals(3, user.getRoles().size()); + assertThat(user.getRoles().size(), is(3)); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186) consists of\\, special\\=chars\\ ")); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186n) consists of\\, special\\=chars\\ ")); Assert.assertTrue(user.getRoles().toString().contains("cn=ROLE/(186nn) consists of\\, special\\=chars\\ ")); diff --git a/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java b/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java index 5cf9485892..99782324dc 100644 --- a/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java +++ b/src/test/java/org/opensearch/security/AdvancedSecurityMigrationTests.java @@ -17,7 +17,6 @@ import org.apache.hc.core5.http.Header; import org.apache.http.HttpStatus; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -28,6 +27,9 @@ import org.opensearch.security.test.helper.cluster.ClusterHelper; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class AdvancedSecurityMigrationTests extends SingleClusterTest { @Before @@ -218,7 +220,7 @@ public void testWithPassiveAuthDisabled() throws Exception { RestHelper.HttpResponse res; RestHelper rh = nonSslRestHelper(); res = rh.executeGetRequest("/_cluster/health"); - Assert.assertEquals(res.getBody(), HttpStatus.SC_INTERNAL_SERVER_ERROR, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); } @Test @@ -241,7 +243,7 @@ public void testWithPassiveAuthDisabledDynamic() throws Exception { RestHelper.HttpResponse res; RestHelper rh = nonSslRestHelper(); res = rh.executeGetRequest("/_cluster/health"); - Assert.assertEquals(res.getBody(), HttpStatus.SC_INTERNAL_SERVER_ERROR, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); } @@ -250,15 +252,15 @@ private void commonTestsForAdvancedSecurityMigration(final RestHelper rh, final RestHelper.HttpResponse res; res = rh.executePutRequest("testindex", getIndexSettingsForAdvSec(), basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executePutRequest("testindex2", getIndexSettingForSSLOnlyNode(), basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/_cluster/health", basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/_cat/shards", basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); commonTestsForAnIndex(rh, "testindex", basicHeaders); commonTestsForAnIndex(rh, "testindex2", basicHeaders); @@ -269,15 +271,15 @@ private void commonTestsForAnIndex(final RestHelper rh, final String index, fina String slashIndex = "/" + index; res = rh.executeGetRequest(slashIndex, basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executePutRequest(slashIndex + "/_doc/1", "{}", basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_CREATED, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_CREATED)); res = rh.executePutRequest(slashIndex + "/_doc/1", "{}", basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeDeleteRequest(slashIndex + "/_doc/1", basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeDeleteRequest(slashIndex, basicHeaders); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); } private Settings.Builder getAdvSecSettings() { diff --git a/src/test/java/org/opensearch/security/AggregationTests.java b/src/test/java/org/opensearch/security/AggregationTests.java index c6591125d5..bdd51960d0 100644 --- a/src/test/java/org/opensearch/security/AggregationTests.java +++ b/src/test/java/org/opensearch/security/AggregationTests.java @@ -27,7 +27,6 @@ package org.opensearch.security; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest; @@ -42,6 +41,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class AggregationTests extends SingleClusterTest { @Test @@ -106,13 +108,15 @@ public void testBasicAggregations() throws Exception { } HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "_search?pretty", - "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", - encodeBasicHeader("nagilum", "nagilum") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "_search?pretty", + "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", + encodeBasicHeader("nagilum", "nagilum") + )).getStatusCode() + ) ); assertNotContains(res, "*xception*"); assertNotContains(res, "*erial*"); @@ -125,13 +129,15 @@ public void testBasicAggregations() throws Exception { assertContains(res, "*role01_role02*"); assertContains(res, "*\"failed\" : 0*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "*/_search?pretty", - "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", - encodeBasicHeader("nagilum", "nagilum") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "*/_search?pretty", + "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", + encodeBasicHeader("nagilum", "nagilum") + )).getStatusCode() + ) ); assertNotContains(res, "*xception*"); assertNotContains(res, "*erial*"); @@ -144,13 +150,15 @@ public void testBasicAggregations() throws Exception { assertContains(res, "*role01_role02*"); assertContains(res, "*\"failed\" : 0*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "_search?pretty", - "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", - encodeBasicHeader("worf", "worf") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "_search?pretty", + "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", + encodeBasicHeader("worf", "worf") + )).getStatusCode() + ) ); assertNotContains(res, "*xception*"); assertNotContains(res, "*erial*"); @@ -163,13 +171,15 @@ public void testBasicAggregations() throws Exception { assertContains(res, "*xyz*"); assertContains(res, "*\"failed\" : 0*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_search?pretty", - "{\"size\":0,\"aggs\":{\"myindices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", - encodeBasicHeader("worf", "worf") - ).getStatusCode() + is( + rh.executePostRequest( + "_search?pretty", + "{\"size\":0,\"aggs\":{\"myindices\":{\"terms\":{\"field\":\"_index\",\"size\":40}}}}", + encodeBasicHeader("worf", "worf") + ).getStatusCode() + ) ); } diff --git a/src/test/java/org/opensearch/security/ConfigTests.java b/src/test/java/org/opensearch/security/ConfigTests.java index 4815f5a9b7..7a4e626d1b 100644 --- a/src/test/java/org/opensearch/security/ConfigTests.java +++ b/src/test/java/org/opensearch/security/ConfigTests.java @@ -45,6 +45,9 @@ import org.opensearch.security.securityconf.impl.v7.TenantV7; import org.opensearch.security.test.SingleClusterTest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class ConfigTests { private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); @@ -104,7 +107,7 @@ private void check(String file, CType cType) throws Exception { JsonNode jsonNode = YAML.readTree(Files.readString(new File(adjustedFilePath).toPath(), StandardCharsets.UTF_8)); int configVersion = 1; if (jsonNode.get("_meta") != null) { - Assert.assertEquals(jsonNode.get("_meta").get("type").asText(), cType.toLCString()); + assertThat(cType.toLCString(), is(jsonNode.get("_meta").get("type").asText())); configVersion = jsonNode.get("_meta").get("config_version").asInt(); } @@ -123,7 +126,7 @@ private SecurityDynamicConfiguration load(String file, CType cType) throws Ex int configVersion = 1; if (jsonNode.get("_meta") != null) { - Assert.assertEquals(jsonNode.get("_meta").get("type").asText(), cType.toLCString()); + assertThat(cType.toLCString(), is(jsonNode.get("_meta").get("type").asText())); configVersion = jsonNode.get("_meta").get("config_version").asInt(); } return SecurityDynamicConfiguration.fromNode(jsonNode, cType, configVersion, 0, 0); diff --git a/src/test/java/org/opensearch/security/DataStreamIntegrationTests.java b/src/test/java/org/opensearch/security/DataStreamIntegrationTests.java index 2f4e665001..6ca83c83dc 100644 --- a/src/test/java/org/opensearch/security/DataStreamIntegrationTests.java +++ b/src/test/java/org/opensearch/security/DataStreamIntegrationTests.java @@ -19,6 +19,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class DataStreamIntegrationTests extends SingleClusterTest { final String bulkDocsBody = "{ \"create\" : {} }" @@ -64,29 +67,29 @@ public void testCreateDataStream() throws Exception { getIndexTemplateBody(), encodeBasicHeader("ds0", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePutRequest( "/_index_template/my-data-stream-template", getIndexTemplateBody(), encodeBasicHeader("ds1", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePutRequest("/_data_stream/my-data-stream11", getIndexTemplateBody(), encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePutRequest("/_data_stream/my-data-stream11", getIndexTemplateBody(), encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePutRequest("/_data_stream/my-data-stream22", getIndexTemplateBody(), encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePutRequest("/_data_stream/my-data-stream33", getIndexTemplateBody(), encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePutRequest("/_data_stream/my-data-stream33", getIndexTemplateBody(), encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -98,40 +101,40 @@ public void testGetDataStream() throws Exception { HttpResponse response; response = rh.executeGetRequest("/_data_stream/my-data-stream11", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream11", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream11", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream22", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream33", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream21,my-data-stream22", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream2*", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream21,my-data-stream22", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -143,43 +146,43 @@ public void testDeleteDataStream() throws Exception { HttpResponse response; response = rh.executeDeleteRequest("/_data_stream/my-data-stream11", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream11", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream11", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream22", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream33", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream21,my-data-stream22", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream21,my-data-stream22", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream2*", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream21,my-data-stream22", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeDeleteRequest("/_data_stream/my-data-stream*", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -191,43 +194,43 @@ public void testDataStreamStats() throws Exception { HttpResponse response; response = rh.executeGetRequest("/_data_stream/my-data-stream11/_stats", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream11/_stats", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream11/_stats", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream22/_stats", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream22/_stats", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream33/_stats", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream*/_stats", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream21,my-data-stream22/_stats", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream*/_stats", encodeBasicHeader("ds1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream2*/_stats", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream21,my-data-stream22/_stats", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("/_data_stream/my-data-stream*/_stats", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("/_data_stream/my-data-stream*/_stats", encodeBasicHeader("ds3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -239,40 +242,40 @@ public void testGetIndexOnBackingIndicesOfDataStream() throws Exception { HttpResponse response; response = rh.executeGetRequest("my-data-stream11", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("my-data-stream22", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(".ds-my-data-stream11-000001", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest(".ds-my-data-stream22-000001", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(".ds-my-data-stream21-000001,.ds-my-data-stream22-000001", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(".ds-my-data-stream2*", encodeBasicHeader("ds0", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("my-data-stream11", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("my-data-stream22", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(".ds-my-data-stream11-000001", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest(".ds-my-data-stream22-000001", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(".ds-my-data-stream21-000001,.ds-my-data-stream22-000001", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(".ds-my-data-stream2*", encodeBasicHeader("ds2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -287,59 +290,59 @@ public void testDocumentLevelSecurityOnDataStream() throws Exception { rh.executePutRequest("/my-data-stream21/_bulk?refresh=true", bulkDocsBody, encodeBasicHeader("ds_admin", "nagilum")); response = rh.executePostRequest("/my-data-stream11/_search", searchQuery1, encodeBasicHeader("ds_dls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("8a4f500d")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); response = rh.executePostRequest("/my-data-stream22/_search", searchQuery1, encodeBasicHeader("ds_dls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/.ds-my-data-stream11-000001/_search", searchQuery1, encodeBasicHeader("ds_dls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("8a4f500d")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); response = rh.executePostRequest("/.ds-my-data-stream11-000001/_search", searchQuery2, encodeBasicHeader("ds_dls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(response.getBody().contains("l7gk7f82")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":0,\"relation\":\"eq\"}")); response = rh.executePostRequest("/.ds-my-data-stream22-000001/_search", searchQuery2, encodeBasicHeader("ds_dls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/my-data-stream2*/_search", searchQuery1, encodeBasicHeader("ds_dls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("8a4f500d")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); response = rh.executePostRequest("/my-data-stream1*/_search", searchQuery1, encodeBasicHeader("ds_dls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/.ds-my-data-stream2*/_search", searchQuery1, encodeBasicHeader("ds_dls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("8a4f500d")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); response = rh.executePostRequest("/.ds-my-data-stream1*/_search", searchQuery1, encodeBasicHeader("ds_dls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/my-*/_search", searchQuery1, encodeBasicHeader("ds_dls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("8a4f500d")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":2,\"relation\":\"eq\"}")); response = rh.executePostRequest("/.ds-my-*/_search", searchQuery1, encodeBasicHeader("ds_dls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("8a4f500d")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":2,\"relation\":\"eq\"}")); response = rh.executePostRequest("/my-*/_search", searchQuery2, encodeBasicHeader("ds_dls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(response.getBody().contains("l7gk7f82")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":0,\"relation\":\"eq\"}")); response = rh.executePostRequest("/.ds-my-*/_search", searchQuery2, encodeBasicHeader("ds_dls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(response.getBody().contains("l7gk7f82")); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":0,\"relation\":\"eq\"}")); } @@ -356,67 +359,67 @@ public void testFLSOnBackingIndicesOfDataStream() throws Exception { rh.executePutRequest("/my-data-stream21/_bulk?refresh=true", bulkDocsBody, encodeBasicHeader("ds_admin", "nagilum")); response = rh.executePostRequest("/my-data-stream11/_search", searchQuery1, encodeBasicHeader("ds_fls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertFalse(response.getBody().contains("\"name\":\"")); Assert.assertTrue(response.getBody().contains("\"message\":\"Login successful\"")); response = rh.executePostRequest("/.ds-my-data-stream11-000001/_search", searchQuery1, encodeBasicHeader("ds_fls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertFalse(response.getBody().contains("\"name\":\"")); Assert.assertTrue(response.getBody().contains("\"message\":\"Login successful\"")); response = rh.executePostRequest("/.ds-my-data-stream11-000001/_search", searchQuery2, encodeBasicHeader("ds_fls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"l7gk7f82\"")); Assert.assertFalse(response.getBody().contains("\"name\":\"")); Assert.assertTrue(response.getBody().contains("\"message\":\"Login attempt failed\"")); response = rh.executePostRequest("/my-data-stream22/_search", searchQuery1, encodeBasicHeader("ds_fls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/.ds-my-data-stream22-000001/_search", searchQuery2, encodeBasicHeader("ds_fls1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/my-data-stream2*/_search", searchQuery1, encodeBasicHeader("ds_fls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); Assert.assertFalse(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/.ds-my-data-stream2*/_search", searchQuery1, encodeBasicHeader("ds_fls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); Assert.assertFalse(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/my-data-stream1*/_search", searchQuery1, encodeBasicHeader("ds_fls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/.ds-my-data-stream1*/_search", searchQuery1, encodeBasicHeader("ds_fls2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/my-*/_search", searchQuery1, encodeBasicHeader("ds_fls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":2,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); Assert.assertFalse(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/.ds-my-*/_search", searchQuery1, encodeBasicHeader("ds_fls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); Assert.assertFalse(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/my-*/_search", searchQuery2, encodeBasicHeader("ds_fls3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"id\":\"l7gk7f82\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Pam\"")); Assert.assertFalse(response.getBody().contains("\"message\":\"")); @@ -434,7 +437,7 @@ public void testFieldMaskingOnDataStream() throws Exception { rh.executePutRequest("/my-data-stream21/_bulk?refresh=true", bulkDocsBody, encodeBasicHeader("ds_admin", "nagilum")); response = rh.executePostRequest("/my-data-stream11/_search", searchQuery1, encodeBasicHeader("ds_fm1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); @@ -442,7 +445,7 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/.ds-my-data-stream11-000001/_search", searchQuery1, encodeBasicHeader("ds_fm1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); @@ -450,7 +453,7 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/.ds-my-data-stream11-000001/_search", searchQuery2, encodeBasicHeader("ds_fm1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"l7gk7f82\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Pam\"")); @@ -458,13 +461,13 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/my-data-stream22/_search", searchQuery1, encodeBasicHeader("ds_fm1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/.ds-my-data-stream22-000001/_search", searchQuery2, encodeBasicHeader("ds_fm1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/my-data-stream2*/_search", searchQuery1, encodeBasicHeader("ds_fm2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); @@ -472,7 +475,7 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/.ds-my-data-stream2*/_search", searchQuery1, encodeBasicHeader("ds_fm2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"Dam\"")); @@ -480,13 +483,13 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/my-data-stream1*/_search", searchQuery1, encodeBasicHeader("ds_fm2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/.ds-my-data-stream1*/_search", searchQuery1, encodeBasicHeader("ds_fm2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executePostRequest("/my-*/_search", searchQuery1, encodeBasicHeader("ds_fm3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"hits\":{\"total\":{\"value\":2,\"relation\":\"eq\"}")); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertFalse(response.getBody().contains("\"name\":\"Dam\"")); @@ -495,7 +498,7 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/.ds-my-*/_search", searchQuery1, encodeBasicHeader("ds_fm3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"id\":\"8a4f500d\"")); Assert.assertFalse(response.getBody().contains("\"name\":\"Dam\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"")); @@ -503,7 +506,7 @@ public void testFieldMaskingOnDataStream() throws Exception { Assert.assertTrue(response.getBody().contains("\"message\":\"")); response = rh.executePostRequest("/my-*/_search", searchQuery2, encodeBasicHeader("ds_fm3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"id\":\"l7gk7f82\"")); Assert.assertFalse(response.getBody().contains("\"name\":\"Pam\"")); Assert.assertTrue(response.getBody().contains("\"name\":\"")); diff --git a/src/test/java/org/opensearch/security/EncryptionInTransitMigrationTests.java b/src/test/java/org/opensearch/security/EncryptionInTransitMigrationTests.java index a028f2d43d..b26546f92e 100644 --- a/src/test/java/org/opensearch/security/EncryptionInTransitMigrationTests.java +++ b/src/test/java/org/opensearch/security/EncryptionInTransitMigrationTests.java @@ -21,6 +21,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class EncryptionInTransitMigrationTests extends SingleClusterTest { @Test @@ -42,59 +45,59 @@ private void testSslOnlyMode(boolean dualModeEnabled) throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("_opendistro/_security/sslinfo"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executePutRequest("/xyz/_doc/1", "{\"a\":5}"); - Assert.assertEquals(HttpStatus.SC_CREATED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_CREATED)); res = rh.executeGetRequest("/_mappings"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/_search"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); if (dualModeEnabled) { res = rh.executeGetRequest("_cluster/settings?flat_settings&include_defaults"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"plugins.security_config.ssl_dual_mode_enabled\":\"true\"")); String disableDualModeClusterSetting = "{ \"persistent\": { \"" + ConfigConstants.SECURITY_CONFIG_SSL_DUAL_MODE_ENABLED + "\": false } }"; res = rh.executePutRequest("_cluster/settings", disableDualModeClusterSetting); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); - Assert.assertEquals( + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( "{\"acknowledged\":true,\"persistent\":{\"plugins\":{\"security_config\":{\"ssl_dual_mode_enabled\":\"false\"}}},\"transient\":{}}", - res.getBody() + is(res.getBody()) ); res = rh.executeGetRequest("_cluster/settings?flat_settings&include_defaults"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"plugins.security_config.ssl_dual_mode_enabled\":\"false\"")); String enableDualModeClusterSetting = "{ \"persistent\": { \"" + ConfigConstants.SECURITY_CONFIG_SSL_DUAL_MODE_ENABLED + "\": true } }"; res = rh.executePutRequest("_cluster/settings", enableDualModeClusterSetting); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); - Assert.assertEquals( + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( "{\"acknowledged\":true,\"persistent\":{\"plugins\":{\"security_config\":{\"ssl_dual_mode_enabled\":\"true\"}}},\"transient\":{}}", - res.getBody() + is(res.getBody()) ); res = rh.executeGetRequest("_cluster/settings?flat_settings&include_defaults"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"plugins.security_config.ssl_dual_mode_enabled\":\"true\"")); res = rh.executePutRequest("_cluster/settings", disableDualModeClusterSetting); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); - Assert.assertEquals( + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( "{\"acknowledged\":true,\"persistent\":{\"plugins\":{\"security_config\":{\"ssl_dual_mode_enabled\":\"false\"}}},\"transient\":{}}", - res.getBody() + is(res.getBody()) ); res = rh.executeGetRequest("_cluster/settings?flat_settings&include_defaults"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"plugins.security_config.ssl_dual_mode_enabled\":\"false\"")); } } @@ -109,7 +112,7 @@ public void testSslOnlyModeDualModeWithNonSSLClusterManagerNode() throws Excepti final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("/_search"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -122,7 +125,7 @@ public void testSslOnlyModeDualModeWithNonSSLDataNode() throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("/_search"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -130,17 +133,17 @@ public void testDualModeSettingFallback() throws Exception { final Settings legacySettings = Settings.builder() .put(ConfigConstants.LEGACY_OPENDISTRO_SECURITY_CONFIG_SSL_DUAL_MODE_ENABLED, true) .build(); - Assert.assertEquals(SecuritySettings.SSL_DUAL_MODE_SETTING.get(legacySettings), true); + assertThat(true, is(SecuritySettings.SSL_DUAL_MODE_SETTING.get(legacySettings))); final Settings legacySettings2 = Settings.builder() .put(ConfigConstants.LEGACY_OPENDISTRO_SECURITY_CONFIG_SSL_DUAL_MODE_ENABLED, false) .build(); - Assert.assertEquals(SecuritySettings.SSL_DUAL_MODE_SETTING.get(legacySettings2), false); + assertThat(false, is(SecuritySettings.SSL_DUAL_MODE_SETTING.get(legacySettings2))); final Settings settings = Settings.builder().put(ConfigConstants.SECURITY_CONFIG_SSL_DUAL_MODE_ENABLED, true).build(); - Assert.assertEquals(SecuritySettings.SSL_DUAL_MODE_SETTING.get(settings), true); + assertThat(true, is(SecuritySettings.SSL_DUAL_MODE_SETTING.get(settings))); final Settings settings2 = Settings.builder().put(ConfigConstants.SECURITY_CONFIG_SSL_DUAL_MODE_ENABLED, false).build(); - Assert.assertEquals(SecuritySettings.SSL_DUAL_MODE_SETTING.get(settings2), false); + assertThat(false, is(SecuritySettings.SSL_DUAL_MODE_SETTING.get(settings2))); } } diff --git a/src/test/java/org/opensearch/security/HealthTests.java b/src/test/java/org/opensearch/security/HealthTests.java index 385757ea53..03030aaec9 100644 --- a/src/test/java/org/opensearch/security/HealthTests.java +++ b/src/test/java/org/opensearch/security/HealthTests.java @@ -27,7 +27,6 @@ package org.opensearch.security; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.common.settings.Settings; @@ -36,6 +35,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class HealthTests extends SingleClusterTest { @Test @@ -44,15 +46,12 @@ public void testHealth() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( - HttpStatus.SC_OK, - (res = rh.executeGetRequest("_opendistro/_security/health?pretty&mode=lenient")).getStatusCode() - ); + assertThat(HttpStatus.SC_OK, is((res = rh.executeGetRequest("_opendistro/_security/health?pretty&mode=lenient")).getStatusCode())); assertContains(res, "*UP*"); assertNotContains(res, "*DOWN*"); assertNotContains(res, "*strict*"); - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*UP*"); assertContains(res, "*strict*"); assertNotContains(res, "*DOWN*"); @@ -64,17 +63,14 @@ public void testHealthUnitialized() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( - HttpStatus.SC_OK, - (res = rh.executeGetRequest("_opendistro/_security/health?pretty&mode=lenient")).getStatusCode() - ); + assertThat(HttpStatus.SC_OK, is((res = rh.executeGetRequest("_opendistro/_security/health?pretty&mode=lenient")).getStatusCode())); assertContains(res, "*UP*"); assertNotContains(res, "*DOWN*"); assertNotContains(res, "*strict*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_SERVICE_UNAVAILABLE, - (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode() + is((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()) ); assertContains(res, "*DOWN*"); assertContains(res, "*strict*"); diff --git a/src/test/java/org/opensearch/security/HttpIntegrationTests.java b/src/test/java/org/opensearch/security/HttpIntegrationTests.java index 3a437ea80a..33a85ed2d6 100644 --- a/src/test/java/org/opensearch/security/HttpIntegrationTests.java +++ b/src/test/java/org/opensearch/security/HttpIntegrationTests.java @@ -57,6 +57,8 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.DefaultObjectMapper.readTree; public class HttpIntegrationTests extends SingleClusterTest { @@ -120,166 +122,155 @@ public void testHTTPBasic() throws Exception { } - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("_search").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("_search").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeDeleteRequest("nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeDeleteRequest("nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest(".nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest(".nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("xxxxyyyy/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("xxxxyyyy/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("abc", "abc:abc")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("", encodeBasicHeader("abc", "abc:abc")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", encodeBasicHeader("userwithnopassword", "")).getStatusCode())); + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", encodeBasicHeader("userwithnopassword", "")).getStatusCode() + is(rh.executeGetRequest("", encodeBasicHeader("userwithblankpassword", "")).getStatusCode()) ); - Assert.assertEquals( + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", encodeBasicHeader("userwithblankpassword", "")).getStatusCode() + is(rh.executeGetRequest("", new BasicHeader("Authorization", "Basic " + "wrongheader")).getStatusCode()) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode()); - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", new BasicHeader("Authorization", "Basic " + "wrongheader")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", new BasicHeader("Authorization", "Basic ")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", new BasicHeader("Authorization", "Basic")).getStatusCode() - ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", new BasicHeader("Authorization", "")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("picard", "picard")).getStatusCode()); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", new BasicHeader("Authorization", "Basic ")).getStatusCode())); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", new BasicHeader("Authorization", "Basic")).getStatusCode())); + assertThat(rh.executeGetRequest("", new BasicHeader("Authorization", "")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("picard", "picard")).getStatusCode(), is(HttpStatus.SC_OK)); for (int i = 0; i < 10; i++) { - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode() - ); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode())); } - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest("/theindex", "{}", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode() + is(rh.executePutRequest("/theindex", "{}", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - rh.executePutRequest("/theindex/_doc/1?refresh=true", "{\"a\":0}", encodeBasicHeader("theindexadmin", "theindexadmin")) - .getStatusCode() + is( + rh.executePutRequest("/theindex/_doc/1?refresh=true", "{\"a\":0}", encodeBasicHeader("theindexadmin", "theindexadmin")) + .getStatusCode() + ) ); - // Assert.assertEquals(HttpStatus.SC_OK, + // assertThat(HttpStatus.SC_OK, // rh.executeGetRequest("/theindex/_analyze?text=this+is+a+test",encodeBasicHeader("theindexadmin", // "theindexadmin")).getStatusCode()); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, + // assertThat(HttpStatus.SC_FORBIDDEN, // rh.executeGetRequest("_analyze?text=this+is+a+test",encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeDeleteRequest("/theindex", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode() + is(rh.executeDeleteRequest("/theindex", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeDeleteRequest("/klingonempire", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode() + is(rh.executeDeleteRequest("/klingonempire", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()) ); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("starfleet/_search", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest("_search", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("starfleet/_search", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executeGetRequest("_search", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeDeleteRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeDeleteRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("/.opendistro_security/_close", null, encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePostRequest("/.opendistro_security/_close", null, encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("/.opendistro_security/_upgrade", null, encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePostRequest("/.opendistro_security/_upgrade", null, encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("/.opendistro_security/_mapping", "{}", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePutRequest("/.opendistro_security/_mapping", "{}", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeDeleteRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeDeleteRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("worf", "worf")).getStatusCode()) ); HttpResponse resc = rh.executeGetRequest("_cat/indices/public?v", encodeBasicHeader("bug108", "nagilum")); Assert.assertTrue(resc.getBody().contains("green")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "role01_role02/_search?pretty", - encodeBasicHeader("user_role01_role02_role03", "user_role01_role02_role03") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "role01_role02/_search?pretty", + encodeBasicHeader("user_role01_role02_role03", "user_role01_role02_role03") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("role01_role02/_search?pretty", encodeBasicHeader("user_role01", "user_role01")).getStatusCode() + is(rh.executeGetRequest("role01_role02/_search?pretty", encodeBasicHeader("user_role01", "user_role01")).getStatusCode()) ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("spock", "spock")).getStatusCode() - ); - Assert.assertEquals( + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("spock", "spock")).getStatusCode())); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("kirk/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode() + is(rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("kirk/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode())); // all - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest(".opendistro_security/_mget", "{\"ids\" : [\"0\"]}", encodeBasicHeader("worf", "worf")).getStatusCode() + is( + rh.executePostRequest(".opendistro_security/_mget", "{\"ids\" : [\"0\"]}", encodeBasicHeader("worf", "worf")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); try (Client tc = getClient()) { @@ -290,12 +281,12 @@ public void testHTTPBasic() throws Exception { ).actionGet(); ConfigUpdateResponse cur = tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[] { "roles" })) .actionGet(); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); try (Client tc = getClient()) { @@ -306,27 +297,27 @@ public void testHTTPBasic() throws Exception { ).actionGet(); ConfigUpdateResponse cur = tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[] { "roles" })) .actionGet(); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); HttpResponse res = rh.executeGetRequest("_search?pretty", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"value\" : 11")); Assert.assertFalse(res.getBody().contains(".opendistro_security")); res = rh.executeGetRequest("_nodes/stats?pretty", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("total_in_bytes")); Assert.assertTrue(res.getBody().contains("max_file_descriptors")); Assert.assertTrue(res.getBody().contains("buffer_pools")); Assert.assertFalse(res.getBody().contains("\"nodes\" : { }")); res = rh.executePostRequest("*/_upgrade", "", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); String bulkBody = "{ \"index\" : { \"_index\" : \"test\", \"_id\" : \"1\" } }" + System.lineSeparator() @@ -338,7 +329,7 @@ public void testHTTPBasic() throws Exception { + System.lineSeparator(); res = rh.executePostRequest("_bulk", bulkBody, encodeBasicHeader("writer", "writer")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"errors\":false")); Assert.assertTrue(res.getBody().contains("\"status\":201")); @@ -347,14 +338,14 @@ public void testHTTPBasic() throws Exception { new BasicHeader("security_tenant", "unittesttenant"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("tenant")); Assert.assertTrue(res.getBody().contains("unittesttenant")); Assert.assertTrue(res.getBody().contains("\"kltentrw\":true")); Assert.assertTrue(res.getBody().contains("\"user_name\":\"worf\"")); res = rh.executeGetRequest("_opendistro/_security/authinfo", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("tenant")); Assert.assertTrue(res.getBody().contains("\"user_requested_tenant\":null")); Assert.assertTrue(res.getBody().contains("\"kltentrw\":true")); @@ -363,7 +354,7 @@ public void testHTTPBasic() throws Exception { Assert.assertFalse(res.getBody().contains("attributes=")); res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("custattr", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("tenants")); Assert.assertTrue(res.getBody().contains("\"user_requested_tenant\" : null")); Assert.assertTrue(res.getBody().contains("\"user_name\" : \"custattr\"")); @@ -372,10 +363,10 @@ public void testHTTPBasic() throws Exception { Assert.assertTrue(res.getBody().contains("attr.internal.c1")); res = rh.executeGetRequest("v2/_search", encodeBasicHeader("custattr", "nagilum")); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("v3/_search", encodeBasicHeader("custattr", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); final String reindex = "{" + "\"source\": {" @@ -387,7 +378,7 @@ public void testHTTPBasic() throws Exception { + "}"; res = rh.executePostRequest("_reindex?pretty", reindex, encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"total\" : 1")); Assert.assertTrue(res.getBody().contains("\"batches\" : 1")); Assert.assertTrue(res.getBody().contains("\"failures\" : [ ]")); @@ -398,7 +389,7 @@ public void testHTTPBasic() throws Exception { new BasicHeader("opendistro_security_impersonate_as", "knuddel"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("name=knuddel")); Assert.assertTrue(res.getBody().contains("attr.internal.test1")); Assert.assertFalse(res.getBody().contains("worf")); @@ -408,14 +399,14 @@ public void testHTTPBasic() throws Exception { new BasicHeader("opendistro_security_impersonate_as", "nonexists"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "notallowed"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -430,11 +421,11 @@ public void testHTTPSCompressionEnabled() throws Exception { final RestHelper rh = restHelper(); // ssl resthelper HttpResponse res = rh.executeGetRequest("_opendistro/_security/sslinfo", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*ssl_protocol\":\"TLSv1.2*"); res = rh.executeGetRequest("_nodes", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); assertNotContains(res, "*\"compression\":\"false\"*"); assertContains(res, "*\"compression\":\"true\"*"); } @@ -450,11 +441,11 @@ public void testHTTPSCompression() throws Exception { final RestHelper rh = restHelper(); // ssl resthelper HttpResponse res = rh.executeGetRequest("_opendistro/_security/sslinfo", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*ssl_protocol\":\"TLSv1.2*"); res = rh.executeGetRequest("_nodes", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*\"compression\":\"false\"*"); assertNotContains(res, "*\"compression\":\"true\"*"); } @@ -466,22 +457,22 @@ public void testHTTPAnon() throws Exception { RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("worf", "wrong")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "wrong")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); HttpResponse resc = rh.executeGetRequest("_opendistro/_security/authinfo"); Assert.assertTrue(resc.getBody().contains("opendistro_security_anonymous")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("_opendistro/_security/authinfo?pretty=true"); Assert.assertTrue(resc.getBody().contains("\"remote_address\" : \"")); // check pretty print - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("_opendistro/_security/authinfo", encodeBasicHeader("nagilum", "nagilum")); Assert.assertTrue(resc.getBody().contains("nagilum")); Assert.assertFalse(resc.getBody().contains("opendistro_security_anonymous")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); try (Client tc = getClient()) { tc.index( @@ -499,13 +490,13 @@ public void testHTTPAnon() throws Exception { new ConfigUpdateRequest(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }) ).actionGet(); Assert.assertFalse(cur.hasFailures()); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("_opendistro/_security/authinfo").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("worf", "wrong")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("_opendistro/_security/authinfo").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "wrong")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -533,7 +524,7 @@ public void testHTTPClientCert() throws Exception { new ConfigUpdateRequest(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }) ).actionGet(); Assert.assertFalse(cur.hasFailures()); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } RestHelper rh = restHelper(); @@ -542,12 +533,12 @@ public void testHTTPClientCert() throws Exception { rh.trustHTTPServerCertificate = true; rh.sendAdminCertificate = true; rh.keystore = "spock-keystore.jks"; - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("_search").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executePutRequest(".opendistro_security/_doc/x", "{}").getStatusCode()); + assertThat(rh.executeGetRequest("_search").getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executePutRequest(".opendistro_security/_doc/x", "{}").getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); rh.keystore = "kirk-keystore.jks"; - Assert.assertEquals(HttpStatus.SC_CREATED, rh.executePutRequest(".opendistro_security/_doc/y", "{}").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("_opendistro/_security/authinfo").getStatusCode()); + assertThat(rh.executePutRequest(".opendistro_security/_doc/y", "{}").getStatusCode(), is(HttpStatus.SC_CREATED)); + assertThat(rh.executeGetRequest("_opendistro/_security/authinfo").getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -578,63 +569,78 @@ public void testHTTPProxyDefault() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig().setConfig("config_proxy.yml"), Settings.EMPTY, true); RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "", - new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), - new BasicHeader("x-proxy-user", "scotty"), - encodeBasicHeader("nagilum-wrong", "nagilum-wrong") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "", + new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), + new BasicHeader("x-proxy-user", "scotty"), + encodeBasicHeader("nagilum-wrong", "nagilum-wrong") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "", - new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), - new BasicHeader("x-proxy-user-wrong", "scotty"), - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "", + new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), + new BasicHeader("x-proxy-user-wrong", "scotty"), + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executeGetRequest( - "", - new BasicHeader("x-forwarded-for", "a"), - new BasicHeader("x-proxy-user", "scotty"), - encodeBasicHeader("nagilum-wrong", "nagilum-wrong") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "", + new BasicHeader("x-forwarded-for", "a"), + new BasicHeader("x-proxy-user", "scotty"), + encodeBasicHeader("nagilum-wrong", "nagilum-wrong") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executeGetRequest("", new BasicHeader("x-forwarded-for", "a,b,c"), new BasicHeader("x-proxy-user", "scotty")).getStatusCode() + is( + rh.executeGetRequest("", new BasicHeader("x-forwarded-for", "a,b,c"), new BasicHeader("x-proxy-user", "scotty")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "", - new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), - new BasicHeader("x-proxy-user", "scotty") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "", + new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), + new BasicHeader("x-proxy-user", "scotty") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "", - new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), - new BasicHeader("X-Proxy-User", "scotty") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "", + new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), + new BasicHeader("X-Proxy-User", "scotty") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "", - new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), - new BasicHeader("x-proxy-user", "scotty"), - new BasicHeader("x-proxy-roles", "starfleet,engineer") - ).getStatusCode() + is( + rh.executeGetRequest( + "", + new BasicHeader("x-forwarded-for", "localhost,192.168.0.1,10.0.0.2"), + new BasicHeader("x-proxy-user", "scotty"), + new BasicHeader("x-proxy-roles", "starfleet,engineer") + ).getStatusCode() + ) ); } @@ -728,155 +734,141 @@ public void testHTTPBasic2() throws Exception { RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeDeleteRequest("nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeDeleteRequest("nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest(".nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest(".nonexistentindex*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("xxxxyyyy/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("xxxxyyyy/_doc/0", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("abc", "abc:abc")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("", encodeBasicHeader("abc", "abc:abc")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", encodeBasicHeader("userwithnopassword", "")).getStatusCode())); + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", encodeBasicHeader("userwithnopassword", "")).getStatusCode() + is(rh.executeGetRequest("", encodeBasicHeader("userwithblankpassword", "")).getStatusCode()) ); - Assert.assertEquals( + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", encodeBasicHeader("userwithblankpassword", "")).getStatusCode() + is(rh.executeGetRequest("", new BasicHeader("Authorization", "Basic " + "wrongheader")).getStatusCode()) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode()); - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", new BasicHeader("Authorization", "Basic " + "wrongheader")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", new BasicHeader("Authorization", "Basic ")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", new BasicHeader("Authorization", "Basic")).getStatusCode() - ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", new BasicHeader("Authorization", "")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("picard", "picard")).getStatusCode()); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", new BasicHeader("Authorization", "Basic ")).getStatusCode())); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", new BasicHeader("Authorization", "Basic")).getStatusCode())); + assertThat(rh.executeGetRequest("", new BasicHeader("Authorization", "")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("picard", "picard")).getStatusCode(), is(HttpStatus.SC_OK)); for (int i = 0; i < 10; i++) { - Assert.assertEquals( - HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode() - ); + assertThat(HttpStatus.SC_UNAUTHORIZED, is(rh.executeGetRequest("", encodeBasicHeader("worf", "wrongpasswd")).getStatusCode())); } - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest("/theindex", "{}", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode() + is(rh.executePutRequest("/theindex", "{}", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - rh.executePutRequest("/theindex/_doc/1?refresh=true", "{\"a\":0}", encodeBasicHeader("theindexadmin", "theindexadmin")) - .getStatusCode() + is( + rh.executePutRequest("/theindex/_doc/1?refresh=true", "{\"a\":0}", encodeBasicHeader("theindexadmin", "theindexadmin")) + .getStatusCode() + ) ); - // Assert.assertEquals(HttpStatus.SC_OK, + // assertThat(HttpStatus.SC_OK, // rh.executeGetRequest("/theindex/_analyze?text=this+is+a+test",encodeBasicHeader("theindexadmin", // "theindexadmin")).getStatusCode()); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, + // assertThat(HttpStatus.SC_FORBIDDEN, // rh.executeGetRequest("_analyze?text=this+is+a+test",encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeDeleteRequest("/theindex", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode() + is(rh.executeDeleteRequest("/theindex", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeDeleteRequest("/klingonempire", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode() + is(rh.executeDeleteRequest("/klingonempire", encodeBasicHeader("theindexadmin", "theindexadmin")).getStatusCode()) ); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("starfleet/_search", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest("_search", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("starfleet/_search", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executeGetRequest("_search", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeDeleteRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeDeleteRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("/.opendistro_security/_close", null, encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePostRequest("/.opendistro_security/_close", null, encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("/.opendistro_security/_upgrade", null, encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePostRequest("/.opendistro_security/_upgrade", null, encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("/.opendistro_security/_mapping", "{}", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePutRequest("/.opendistro_security/_mapping", "{}", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest(".opendistro_security/", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/2", "{}", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeDeleteRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeDeleteRequest(".opendistro_security/_doc/0", encodeBasicHeader("worf", "worf")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("worf", "worf")).getStatusCode()) ); HttpResponse resc = rh.executeGetRequest("_cat/indices/public", encodeBasicHeader("bug108", "nagilum")); // Assert.assertTrue(resc.getBody().contains("green")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "role01_role02/_search?pretty", - encodeBasicHeader("user_role01_role02_role03", "user_role01_role02_role03") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executeGetRequest( + "role01_role02/_search?pretty", + encodeBasicHeader("user_role01_role02_role03", "user_role01_role02_role03") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("role01_role02/_search?pretty", encodeBasicHeader("user_role01", "user_role01")).getStatusCode() + is(rh.executeGetRequest("role01_role02/_search?pretty", encodeBasicHeader("user_role01", "user_role01")).getStatusCode()) ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("spock", "spock")).getStatusCode() - ); - Assert.assertEquals( + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("spock", "spock")).getStatusCode())); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("kirk/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode() + is(rh.executeGetRequest("spock/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("kirk/_search?pretty", encodeBasicHeader("kirk", "kirk")).getStatusCode())); // all @@ -898,7 +890,7 @@ public void testBulk() throws Exception { + System.lineSeparator(); HttpResponse res = rh.executePostRequest("_bulk", bulkBody, encodeBasicHeader("bulk", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"errors\":false")); Assert.assertTrue(res.getBody().contains("\"status\":201")); } @@ -920,10 +912,10 @@ public void testBulkWithOneIndexFailure() throws Exception { HttpResponse res = rh.executePostRequest("_bulk?refresh=true", bulkBody, encodeBasicHeader("bulk_test_user", "nagilum")); JsonNode jsonNode = readTree(res.getBody()); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(jsonNode.get("errors").booleanValue()); - Assert.assertEquals(201, jsonNode.get("items").get(0).get("index").get("status").intValue()); - Assert.assertEquals(403, jsonNode.get("items").get(1).get("index").get("status").intValue()); + assertThat(jsonNode.get("items").get(0).get("index").get("status").intValue(), is(201)); + assertThat(jsonNode.get("items").get(1).get("index").get("status").intValue(), is(403)); } @Test @@ -954,14 +946,14 @@ public void test557() throws Exception { "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":10}}}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("starfleet_academy")); res = rh.executePostRequest( "/*/_search", "{\"size\":0,\"aggs\":{\"indices\":{\"terms\":{\"field\":\"_index\",\"size\":10}}}}", encodeBasicHeader("557", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("starfleet_academy")); } @@ -1019,11 +1011,11 @@ public void testITT1635() throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("/esb-prod-*/_search?pretty", encodeBasicHeader("itt1635", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/esb-alias-*/_search?pretty", encodeBasicHeader("itt1635", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/esb-prod-all/_search?pretty", encodeBasicHeader("itt1635", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -1100,10 +1092,10 @@ public void testTenantInfo() throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("_opendistro/_security/tenantinfo?pretty", encodeBasicHeader("itt1635", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executeGetRequest("_opendistro/_security/tenantinfo?pretty", encodeBasicHeader("kibanaserver", "kibanaserver")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\".kibana_-1139640511_admin1\" : \"admin_1\"")); Assert.assertTrue(res.getBody().contains("\".kibana_-1386441176_praxisrw\" : \"praxisrw\"")); Assert.assertTrue(res.getBody().contains(".kibana_-2014056163_kltentrw\" : \"kltentrw\"")); @@ -1129,7 +1121,7 @@ public void testRestImpersonation() throws Exception { new BasicHeader("opendistro_security_impersonate_as", "someotherusernotininternalusersfile"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("name=someotherusernotininternalusersfile")); Assert.assertFalse(res.getBody().contains("worf")); } @@ -1141,16 +1133,16 @@ public void testSslOnlyMode() throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("_opendistro/_security/sslinfo"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executePutRequest("/xyz/_doc/1", "{\"a\":5}"); - Assert.assertEquals(HttpStatus.SC_CREATED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_CREATED)); res = rh.executeGetRequest("/_mappings"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/_search"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -1164,12 +1156,9 @@ public void testAll() throws Exception { .actionGet(); } - Assert.assertEquals( - HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("_all/_search", encodeBasicHeader("worf", "worf")).getStatusCode() - ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest("*/_search", encodeBasicHeader("worf", "worf")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest("_search", encodeBasicHeader("worf", "worf")).getStatusCode()); + assertThat(HttpStatus.SC_FORBIDDEN, is(rh.executeGetRequest("_all/_search", encodeBasicHeader("worf", "worf")).getStatusCode())); + assertThat(rh.executeGetRequest("*/_search", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); + assertThat(rh.executeGetRequest("_search", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } } diff --git a/src/test/java/org/opensearch/security/IndexIntegrationTests.java b/src/test/java/org/opensearch/security/IndexIntegrationTests.java index a5c137d61e..648a9b1ade 100644 --- a/src/test/java/org/opensearch/security/IndexIntegrationTests.java +++ b/src/test/java/org/opensearch/security/IndexIntegrationTests.java @@ -55,6 +55,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class IndexIntegrationTests extends SingleClusterTest { @Test @@ -92,7 +95,7 @@ public void testComposite() throws Exception { + System.lineSeparator(); HttpResponse resc = rh.executePostRequest("_msearch", msearchBody, encodeBasicHeader("worf", "worf")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("\"_index\":\"klingonempire\"")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("hits")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("no permissions for [indices:data/read/search]")); @@ -159,7 +162,7 @@ public void testBulkShards() throws Exception { // _bulk HttpResponse res = rh.executePostRequest("_bulk?refresh=true&pretty=true", bulkBody, encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"errors\" : true")); Assert.assertTrue(res.getBody().contains("\"status\" : 201")); Assert.assertTrue(res.getBody().contains("no permissions for")); @@ -176,39 +179,36 @@ public void testCreateIndex() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( "Unable to create index 'nag'", - HttpStatus.SC_OK, - rh.executePutRequest("nag1", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + rh.executePutRequest("nag1", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), + is(HttpStatus.SC_OK) ); - Assert.assertEquals( + assertThat( "Unable to create index 'starfleet_library'", - HttpStatus.SC_OK, - rh.executePutRequest("starfleet_library", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + rh.executePutRequest("starfleet_library", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), + is(HttpStatus.SC_OK) ); clusterHelper.waitForCluster(ClusterHealthStatus.GREEN, TimeValue.timeValueSeconds(10), clusterInfo.numNodes); - Assert.assertEquals( + assertThat( "Unable to close index 'starfleet_library'", - HttpStatus.SC_OK, - rh.executePostRequest("starfleet_library/_close", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + rh.executePostRequest("starfleet_library/_close", null, encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), + is(HttpStatus.SC_OK) ); - Assert.assertEquals( + assertThat( "Unable to open index 'starfleet_library'", - HttpStatus.SC_OK, - (res = rh.executePostRequest("starfleet_library/_open", null, encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + (res = rh.executePostRequest("starfleet_library/_open", null, encodeBasicHeader("nagilum", "nagilum"))).getStatusCode(), + is(HttpStatus.SC_OK) ); Assert.assertTrue("open index 'starfleet_library' not acknowledged", res.getBody().contains("acknowledged")); Assert.assertFalse("open index 'starfleet_library' not acknowledged", res.getBody().contains("false")); clusterHelper.waitForCluster(ClusterHealthStatus.GREEN, TimeValue.timeValueSeconds(10), clusterInfo.numNodes); - Assert.assertEquals( - HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("public", null, encodeBasicHeader("spock", "spock")).getStatusCode() - ); + assertThat(HttpStatus.SC_FORBIDDEN, is(rh.executePutRequest("public", null, encodeBasicHeader("spock", "spock")).getStatusCode())); } @@ -255,16 +255,16 @@ public void testFilteredAlias() throws Exception { // opendistro_security_user2 -> picard HttpResponse resc = rh.executeGetRequest("alias*/_search", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("theindex/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("alias3/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("_cat/indices", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); } @@ -299,43 +299,43 @@ public void testIndexTypeEvaluation() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse resc = rh.executeGetRequest("/foo1/_search?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"content\" : 1")); resc = rh.executeGetRequest("/foo2/_search?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"content\" : 2")); resc = rh.executeGetRequest("/foo/_search?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"content\" : 3")); // resc = rh.executeGetRequest("/fooba/z/_search?pretty", encodeBasicHeader("baz", "worf")); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + // assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/foo1/_doc/1?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"found\" : true")); Assert.assertTrue(resc.getBody().contains("\"content\" : 1")); resc = rh.executeGetRequest("/foo2/_doc/2?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"content\" : 2")); Assert.assertTrue(resc.getBody().contains("\"found\" : true")); resc = rh.executeGetRequest("/foo/_doc/3?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"content\" : 3")); Assert.assertTrue(resc.getBody().contains("\"found\" : true")); // resc = rh.executeGetRequest("/fooba/z/4?pretty", encodeBasicHeader("baz", "worf")); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + // assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // resc = rh.executeGetRequest("/foo*/_search?pretty", encodeBasicHeader("baz", "worf")); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + // assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/foo*,-fooba/_search?pretty", encodeBasicHeader("baz", "worf")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody().contains("\"content\" : 1")); Assert.assertTrue(resc.getBody().contains("\"content\" : 2")); } @@ -370,135 +370,166 @@ public void testIndices() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse res = null; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("/logstash-1/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/logstash-1/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); // nonexistent index with permissions - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("/logstash-nonex/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is( + rh.executeGetRequest("/logstash-nonex/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); // existent index without permissions - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/nopermindex/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/nopermindex/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); // nonexistent index without permissions - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/does-not-exist-and-no-perm/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("/does-not-exist-and-no-perm/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); // nonexistent and existent index with permissions - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("/logstash-nonex,logstash-1/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("/logstash-nonex,logstash-1/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); // existent index with permissions - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("/logstash-1/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/logstash-1/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); // nonexistent index with failed login - Assert.assertEquals( + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executeGetRequest("/logstash-nonex/_search", encodeBasicHeader("nouser", "nosuer")).getStatusCode() + is(rh.executeGetRequest("/logstash-nonex/_search", encodeBasicHeader("nouser", "nosuer")).getStatusCode()) ); // nonexistent index with no login - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, (res = rh.executeGetRequest("/logstash-nonex/_search")).getStatusCode()); + assertThat((res = rh.executeGetRequest("/logstash-nonex/_search")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/_all/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/_all/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/*/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/*/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/nopermindex,logstash-1,nonexist/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest( + "/nopermindex,logstash-1,nonexist/_search", + encodeBasicHeader("opendistro_security_logstash", "nagilum") + ).getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/logstash-1,nonexist/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("/logstash-1,nonexist/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/nonexist/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/nonexist/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("/%3Clogstash-%7Bnow%2Fd%7D%3E/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("/%3Clogstash-%7Bnow%2Fd%7D%3E/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/%3Cnonex-%7Bnow%2Fd%7D%3E/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("/%3Cnonex-%7Bnow%2Fd%7D%3E/_search", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "/%3Clogstash-%7Bnow%2Fd%7D%3E,logstash-*/_search", - encodeBasicHeader("opendistro_security_logstash", "nagilum") - ).getStatusCode() + is( + rh.executeGetRequest( + "/%3Clogstash-%7Bnow%2Fd%7D%3E,logstash-*/_search", + encodeBasicHeader("opendistro_security_logstash", "nagilum") + ).getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest( - "/%3Clogstash-%7Bnow%2Fd%7D%3E,logstash-1/_search", - encodeBasicHeader("opendistro_security_logstash", "nagilum") - ).getStatusCode() + is( + rh.executeGetRequest( + "/%3Clogstash-%7Bnow%2Fd%7D%3E,logstash-1/_search", + encodeBasicHeader("opendistro_security_logstash", "nagilum") + ).getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - rh.executePutRequest("/logstash-b/_doc/1", "{}", encodeBasicHeader("opendistro_security_logstash", "nagilum")).getStatusCode() + is( + rh.executePutRequest("/logstash-b/_doc/1", "{}", encodeBasicHeader("opendistro_security_logstash", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest("/%3Clogstash-cnew-%7Bnow%2Fd%7D%3E", "{}", encodeBasicHeader("opendistro_security_logstash", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest( + "/%3Clogstash-cnew-%7Bnow%2Fd%7D%3E", + "{}", + encodeBasicHeader("opendistro_security_logstash", "nagilum") + ).getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - rh.executePutRequest( - "/%3Clogstash-new-%7Bnow%2Fd%7D%3E/_doc/1", - "{}", - encodeBasicHeader("opendistro_security_logstash", "nagilum") - ).getStatusCode() + is( + rh.executePutRequest( + "/%3Clogstash-new-%7Bnow%2Fd%7D%3E/_doc/1", + "{}", + encodeBasicHeader("opendistro_security_logstash", "nagilum") + ).getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/_cat/indices?v", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is((res = rh.executeGetRequest("/_cat/indices?v", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()) ); String body = res.getBody(); Assert.assertTrue(body.contains("logstash-b")); @@ -554,38 +585,38 @@ public void testAliases() throws Exception { HttpResponse res = null; - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("/mysgi/_doc", "{}", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executePostRequest("/mysgi/_doc", "{}", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/mysgi/_search?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is((res = rh.executeGetRequest("/mysgi/_search?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()) ); assertContains(res, "*\"hits\" : {*\"value\" : 0,*\"hits\" : [ ]*"); // add alias to allowed index - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest("/logstash-1/_alias/alog1", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executePutRequest("/logstash-1/_alias/alog1", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); // add alias to not existing (no perm) - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("/nonexitent/_alias/alnp", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executePutRequest("/nonexitent/_alias/alnp", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); // add alias to not existing (with perm) - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executePutRequest("/logstash-nonex/_alias/alnp", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executePutRequest("/logstash-nonex/_alias/alnp", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); // add alias to not allowed index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("/nopermindex/_alias/alnp", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executePutRequest("/nopermindex/_alias/alnp", "", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); String aliasRemoveIndex = "{" @@ -596,35 +627,35 @@ public void testAliases() throws Exception { + "}"; // remove_index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("/_aliases", aliasRemoveIndex, encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executePostRequest("/_aliases", aliasRemoveIndex, encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); // get alias for permitted index - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("/logstash-1/_alias/alog1", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/logstash-1/_alias/alog1", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); // get alias for all indices - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/_alias/alog1", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/_alias/alog1", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); // get alias no perm - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("/_alias/nopermalias", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executeGetRequest("/_alias/nopermalias", encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); String alias = "{" + "\"aliases\": {" + "\"alias1\": {}" + "}" + "}"; // create alias along with index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("/beats-withalias", alias, encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode() + is(rh.executePutRequest("/beats-withalias", alias, encodeBasicHeader("aliasmngt", "nagilum")).getStatusCode()) ); } @@ -638,7 +669,7 @@ public void testIndexResolveInvalidIndexName() throws Exception { URLEncoder.encode("_##pdt_data/_search", "UTF-8"), encodeBasicHeader("ccsresolv", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); Assert.assertTrue(res.getBody().contains("invalid_index_name_exception")); } @@ -655,10 +686,10 @@ public void testCCSIndexResolve() throws Exception { // ccsresolv has perm for ?abc* HttpResponse res = rh.executeGetRequest("ggg:.abc-6,.abc-6/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executeGetRequest("/*:.abc-6,.abc-6/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); // TODO: Change for 25.0 to be forbidden (possible bug in ES regarding ccs wildcard) } @@ -680,50 +711,50 @@ public void testCCSIndexResolve2() throws Exception { } HttpResponse res = rh.executeGetRequest("/*:.abc,.abc/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":1")); res = rh.executeGetRequest("/ba*bcuzh/_search", encodeBasicHeader("nagilum", "nagilum")); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":12")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:.abc/_search", encodeBasicHeader("nagilum", "nagilum")); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":1")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:xyz,xyz/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":2")); // res = rh.executeGetRequest("/*noexist/_search", encodeBasicHeader("nagilum", "nagilum")); - // Assert.assertEquals(HttpStatus.SC_NOT_FOUND, res.getStatusCode()); + // assertThat(res.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); res = rh.executeGetRequest("/*:.abc/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":1")); res = rh.executeGetRequest("/*:xyz/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":2")); res = rh.executeGetRequest("/.abc/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/xyz/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:.abc,.abc/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:xyz,xyz/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:.abc/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:xyz/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:noperm/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:noperm/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/*:noexists/_search", encodeBasicHeader("ccsresolv", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -751,7 +782,7 @@ public void testIndexResolveIgnoreUnavailable() throws Exception { + System.lineSeparator(); HttpResponse resc = rh.executePostRequest("_msearch", msearchBody, encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("\"total\":{\"value\":1")); } @@ -777,13 +808,13 @@ public void testIndexResolveIndicesAlias() throws Exception { Assert.assertFalse(resc.getBody().contains("foo")); resc = rh.executeGetRequest("/foo-alias/_search", encodeBasicHeader("foo_index", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/foo-index/_search", encodeBasicHeader("foo_index", "nagilum")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); resc = rh.executeGetRequest("/foo-alias/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); } @@ -801,34 +832,34 @@ public void testIndexResolveMinus() throws Exception { } HttpResponse resc = rh.executeGetRequest("/**/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/*/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/**,-foo*/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/*,-foo*/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/*,-*security/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("/*,-*security/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("/*,-*security,-foo*/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("/_all,-*security/_search", encodeBasicHeader("foo_all", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resc = rh.executeGetRequest("/_all,-*security/_search", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); } } diff --git a/src/test/java/org/opensearch/security/IndexTemplateClusterPermissionsCheckTest.java b/src/test/java/org/opensearch/security/IndexTemplateClusterPermissionsCheckTest.java index e08367d2b2..72a5c2006c 100644 --- a/src/test/java/org/opensearch/security/IndexTemplateClusterPermissionsCheckTest.java +++ b/src/test/java/org/opensearch/security/IndexTemplateClusterPermissionsCheckTest.java @@ -12,7 +12,6 @@ package org.opensearch.security; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -20,6 +19,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class IndexTemplateClusterPermissionsCheckTest extends SingleClusterTest { private RestHelper rh; @@ -42,8 +44,8 @@ public void testPutIndexTemplateByNonPrivilegedUser() throws Exception { // should fail, as user `ds3` doesn't have correct permissions HttpResponse response = rh.executePutRequest("/_index_template/sem1234", indexTemplateBody, encodeBasicHeader("ds4", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertEquals(expectedFailureResponse, response.findValueInJson("error.root_cause[0].reason")); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); + assertThat(response.findValueInJson("error.root_cause[0].reason"), is(expectedFailureResponse)); } @Test @@ -54,7 +56,7 @@ public void testPutIndexTemplateByPrivilegedUser() throws Exception { indexTemplateBody, encodeBasicHeader("sem-user", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -67,8 +69,8 @@ public void testPutIndexTemplateAsIndexLevelPermission() throws Exception { indexTemplateBody, encodeBasicHeader("sem-user2", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); - Assert.assertEquals(expectedFailureResponse, response.findValueInJson("error.root_cause[0].reason")); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); + assertThat(response.findValueInJson("error.root_cause[0].reason"), is(expectedFailureResponse)); } } diff --git a/src/test/java/org/opensearch/security/InitializationIntegrationTests.java b/src/test/java/org/opensearch/security/InitializationIntegrationTests.java index 7545822620..a5f4ff6dba 100644 --- a/src/test/java/org/opensearch/security/InitializationIntegrationTests.java +++ b/src/test/java/org/opensearch/security/InitializationIntegrationTests.java @@ -61,6 +61,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class InitializationIntegrationTests extends SingleClusterTest { @Test @@ -78,19 +81,19 @@ public void testEnsureInitViaRestDoesWork() throws Exception { rh.enableHTTPClientSSL = true; rh.trustHTTPServerCertificate = true; rh.sendAdminCertificate = true; - Assert.assertEquals( + assertThat( HttpStatus.SC_SERVICE_UNAVAILABLE, - rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("___", "")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("___", "")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_SERVICE_UNAVAILABLE, - rh.executePutRequest(".opendistro_security/_doc/config", "{}", encodeBasicHeader("___", "")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/config", "{}", encodeBasicHeader("___", "")).getStatusCode()) ); rh.keystore = "kirk-keystore.jks"; - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - rh.executePutRequest(".opendistro_security/_doc/config", "{}", encodeBasicHeader("___", "")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/config", "{}", encodeBasicHeader("___", "")).getStatusCode()) ); Assert.assertFalse(rh.executeSimpleRequest("_nodes/stats?pretty").contains("\"tx_size_in_bytes\" : 0")); @@ -112,13 +115,13 @@ public void testInitWithInjectedUser() throws Exception { RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("___", "")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("___", "")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_UNAUTHORIZED, - rh.executePutRequest(".opendistro_security/_doc/config", "{}", encodeBasicHeader("___", "")).getStatusCode() + is(rh.executePutRequest(".opendistro_security/_doc/config", "{}", encodeBasicHeader("___", "")).getStatusCode()) ); } @@ -139,12 +142,12 @@ public void testWhoAmI() throws Exception { try (RestHighLevelClient restHighLevelClient = getRestClient(clusterInfo, "spock-keystore.jks", "truststore.jks")) { Response whoAmIRes = restHighLevelClient.getLowLevelClient().performRequest(new Request("GET", "/_plugins/_security/whoami")); - Assert.assertEquals(whoAmIRes.getStatusLine().getStatusCode(), 200); + assertThat(200, is(whoAmIRes.getStatusLine().getStatusCode())); // Should be using HTTP/2 by default - Assert.assertEquals(whoAmIRes.getStatusLine().getProtocolVersion(), HttpVersion.HTTP_2); + assertThat(HttpVersion.HTTP_2, is(whoAmIRes.getStatusLine().getProtocolVersion())); JsonNode whoAmIResNode = DefaultObjectMapper.objectMapper.readTree(whoAmIRes.getEntity().getContent()); String whoAmIResponsePayload = whoAmIResNode.toPrettyString(); - Assert.assertEquals(whoAmIResponsePayload, "CN=spock,OU=client,O=client,L=Test,C=DE", whoAmIResNode.get("dn").asText()); + assertThat(whoAmIResponsePayload, whoAmIResNode.get("dn").asText(), is("CN=spock,OU=client,O=client,L=Test,C=DE")); Assert.assertFalse(whoAmIResponsePayload, whoAmIResNode.get("is_admin").asBoolean()); Assert.assertFalse(whoAmIResponsePayload, whoAmIResNode.get("is_node_certificate_request").asBoolean()); } @@ -173,12 +176,12 @@ public void testWhoAmIForceHttp1() throws Exception { ) ) { Response whoAmIRes = restHighLevelClient.getLowLevelClient().performRequest(new Request("GET", "/_plugins/_security/whoami")); - Assert.assertEquals(whoAmIRes.getStatusLine().getStatusCode(), 200); + assertThat(200, is(whoAmIRes.getStatusLine().getStatusCode())); // The HTTP/1.1 is forced and should be used instead - Assert.assertEquals(whoAmIRes.getStatusLine().getProtocolVersion(), HttpVersion.HTTP_1_1); + assertThat(HttpVersion.HTTP_1_1, is(whoAmIRes.getStatusLine().getProtocolVersion())); JsonNode whoAmIResNode = DefaultObjectMapper.objectMapper.readTree(whoAmIRes.getEntity().getContent()); String whoAmIResponsePayload = whoAmIResNode.toPrettyString(); - Assert.assertEquals(whoAmIResponsePayload, "CN=spock,OU=client,O=client,L=Test,C=DE", whoAmIResNode.get("dn").asText()); + assertThat(whoAmIResponsePayload, whoAmIResNode.get("dn").asText(), is("CN=spock,OU=client,O=client,L=Test,C=DE")); Assert.assertFalse(whoAmIResponsePayload, whoAmIResNode.get("is_admin").asBoolean()); Assert.assertFalse(whoAmIResponsePayload, whoAmIResNode.get("is_node_certificate_request").asBoolean()); } @@ -210,7 +213,7 @@ public void testConfigHotReload() throws Exception { } try (Client tc = getClient()) { - Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(clusterInfo.numNodes)); tc.index( new IndexRequest(".opendistro_security").setRefreshPolicy(RefreshPolicy.IMMEDIATE) .id("internalusers") @@ -220,7 +223,7 @@ public void testConfigHotReload() throws Exception { ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }) ).actionGet(); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } for (Iterator iterator = clusterInfo.httpAdresses.iterator(); iterator.hasNext();) { @@ -244,7 +247,7 @@ public void testConfigHotReload() throws Exception { } try (Client tc = getClient()) { - Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(clusterInfo.numNodes)); tc.index( new IndexRequest(".opendistro_security").setRefreshPolicy(RefreshPolicy.IMMEDIATE) .id("config") @@ -252,7 +255,7 @@ public void testConfigHotReload() throws Exception { ).actionGet(); ConfigUpdateResponse cur = tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[] { "config" })) .actionGet(); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } for (Iterator iterator = clusterInfo.httpAdresses.iterator(); iterator.hasNext();) { @@ -272,7 +275,7 @@ public void testConfigHotReload() throws Exception { Assert.assertTrue(res.getBody().contains("opendistro_security_anonymous")); Assert.assertTrue(res.getBody().contains("name=opendistro_security_anonymous")); Assert.assertTrue(res.getBody().contains("roles=[opendistro_security_anonymous_backendrole]")); - Assert.assertEquals(200, res.getStatusCode()); + assertThat(res.getStatusCode(), is(200)); } } @@ -283,9 +286,9 @@ public void testDefaultConfig() throws Exception { RestHelper rh = nonSslRestHelper(); Thread.sleep(10000); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("admin", "admin")).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader("admin", "admin")).getStatusCode(), is(HttpStatus.SC_OK)); HttpResponse res = rh.executeGetRequest("/_cluster/health", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(res.getBody(), HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getBody(), res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -298,9 +301,9 @@ public void testInvalidDefaultConfig() throws Exception { setup(Settings.EMPTY, null, settings, false); RestHelper rh = nonSslRestHelper(); Thread.sleep(10000); - Assert.assertEquals( + assertThat( HttpStatus.SC_SERVICE_UNAVAILABLE, - rh.executeGetRequest("", encodeBasicHeader("admin", "admin")).getStatusCode() + is(rh.executeGetRequest("", encodeBasicHeader("admin", "admin")).getStatusCode()) ); } finally { ClusterHelper.resetSystemProperties(); @@ -316,25 +319,27 @@ public void testDisabled() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse resc = rh.executeGetRequest("_search"); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("hits")); } @Test public void testDiscoveryWithoutInitialization() throws Exception { setup(Settings.EMPTY, null, Settings.EMPTY, false); - Assert.assertEquals( + assertThat( clusterInfo.numNodes, - clusterHelper.nodeClient() - .admin() - .cluster() - .health(new ClusterHealthRequest().waitForGreenStatus()) - .actionGet() - .getNumberOfNodes() + is( + clusterHelper.nodeClient() + .admin() + .cluster() + .health(new ClusterHealthRequest().waitForGreenStatus()) + .actionGet() + .getNumberOfNodes() + ) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); } } diff --git a/src/test/java/org/opensearch/security/IntegrationTests.java b/src/test/java/org/opensearch/security/IntegrationTests.java index ebe1f799e9..1f3cd2e3c8 100644 --- a/src/test/java/org/opensearch/security/IntegrationTests.java +++ b/src/test/java/org/opensearch/security/IntegrationTests.java @@ -58,6 +58,8 @@ import io.netty.handler.ssl.OpenSsl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.DefaultObjectMapper.readTree; public class IntegrationTests extends SingleClusterTest { @@ -79,21 +81,26 @@ public void testSearchScroll() throws Exception { // search HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is( + (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("nagilum", "nagilum"))) + .getStatusCode() + ) ); int start = res.getBody().indexOf("_scroll_id") + 15; String scrollid = res.getBody().substring(start, res.getBody().indexOf("\"", start + 1)); // search scroll - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "/_search/scroll?pretty=true", - "{\"scroll_id\" : \"" + scrollid + "\"}", - encodeBasicHeader("nagilum", "nagilum") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/_search/scroll?pretty=true", + "{\"scroll_id\" : \"" + scrollid + "\"}", + encodeBasicHeader("nagilum", "nagilum") + )).getStatusCode() + ) ); // search done @@ -104,14 +111,14 @@ public void testSearchScroll() throws Exception { public void testDnParsingCertAuth() throws Exception { Settings settings = Settings.builder().put("username_attribute", "cn").put("roles_attribute", "l").build(); HTTPClientCertAuthenticator auth = new HTTPClientCertAuthenticator(settings, null); - Assert.assertEquals("abc", auth.extractCredentials(null, newThreadContext("cn=abc,cn=xxx,l=ert,st=zui,c=qwe")).getUsername()); - Assert.assertEquals("abc", auth.extractCredentials(null, newThreadContext("cn=abc,l=ert,st=zui,c=qwe")).getUsername()); - Assert.assertEquals("abc", auth.extractCredentials(null, newThreadContext("CN=abc,L=ert,st=zui,c=qwe")).getUsername()); - Assert.assertEquals("abc", auth.extractCredentials(null, newThreadContext("l=ert,cn=abc,st=zui,c=qwe")).getUsername()); + assertThat(auth.extractCredentials(null, newThreadContext("cn=abc,cn=xxx,l=ert,st=zui,c=qwe")).getUsername(), is("abc")); + assertThat(auth.extractCredentials(null, newThreadContext("cn=abc,l=ert,st=zui,c=qwe")).getUsername(), is("abc")); + assertThat(auth.extractCredentials(null, newThreadContext("CN=abc,L=ert,st=zui,c=qwe")).getUsername(), is("abc")); + assertThat(auth.extractCredentials(null, newThreadContext("l=ert,cn=abc,st=zui,c=qwe")).getUsername(), is("abc")); Assert.assertNull(auth.extractCredentials(null, newThreadContext("L=ert,CN=abc,c,st=zui,c=qwe"))); - Assert.assertEquals("abc", auth.extractCredentials(null, newThreadContext("l=ert,st=zui,c=qwe,cn=abc")).getUsername()); - Assert.assertEquals("abc", auth.extractCredentials(null, newThreadContext("L=ert,st=zui,c=qwe,CN=abc")).getUsername()); - Assert.assertEquals("L=ert,st=zui,c=qwe", auth.extractCredentials(null, newThreadContext("L=ert,st=zui,c=qwe")).getUsername()); + assertThat(auth.extractCredentials(null, newThreadContext("l=ert,st=zui,c=qwe,cn=abc")).getUsername(), is("abc")); + assertThat(auth.extractCredentials(null, newThreadContext("L=ert,st=zui,c=qwe,CN=abc")).getUsername(), is("abc")); + assertThat(auth.extractCredentials(null, newThreadContext("L=ert,st=zui,c=qwe")).getUsername(), is("L=ert,st=zui,c=qwe")); Assert.assertArrayEquals( new String[] { "ert" }, auth.extractCredentials(null, newThreadContext("cn=abc,l=ert,st=zui,c=qwe")).getBackendRoles().toArray(new String[0]) @@ -125,9 +132,9 @@ public void testDnParsingCertAuth() throws Exception { settings = Settings.builder().build(); auth = new HTTPClientCertAuthenticator(settings, null); - Assert.assertEquals( + assertThat( "cn=abc,l=ert,st=zui,c=qwe", - auth.extractCredentials(null, newThreadContext("cn=abc,l=ert,st=zui,c=qwe")).getUsername() + is(auth.extractCredentials(null, newThreadContext("cn=abc,l=ert,st=zui,c=qwe")).getUsername()) ); } @@ -169,8 +176,8 @@ public void testDNSpecials() throws Exception { setup(tcSettings, new DynamicSecurityConfig(), settings, true); RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode()); + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_OK)); } @@ -203,8 +210,8 @@ public void testDNSpecials1() throws Exception { setup(tcSettings, new DynamicSecurityConfig(), settings, true); RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("").getStatusCode()); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode()); + assertThat(rh.executeGetRequest("").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("worf", "worf")).getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -244,7 +251,7 @@ public void testMultiget() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse resc = rh.executePostRequest("_mget?refresh=true", mgetBody, encodeBasicHeader("picard", "picard")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(resc.getBody().contains("type2")); } @@ -269,14 +276,14 @@ public void testRestImpersonation() throws Exception { new BasicHeader("opendistro_security_impersonate_as", "knuddel"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resp.getStatusCode()); + assertThat(resp.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resp = rh.executeGetRequest( "/_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "knuddel"), encodeBasicHeader("spock", "spock") ); - Assert.assertEquals(HttpStatus.SC_OK, resp.getStatusCode()); + assertThat(resp.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resp.getBody().contains("name=knuddel")); Assert.assertFalse(resp.getBody().contains("spock")); @@ -285,14 +292,14 @@ public void testRestImpersonation() throws Exception { new BasicHeader("opendistro_security_impersonate_as", "userwhonotexists"), encodeBasicHeader("spock", "spock") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resp.getStatusCode()); + assertThat(resp.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); resp = rh.executeGetRequest( "/_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "invalid"), encodeBasicHeader("spock", "spock") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resp.getStatusCode()); + assertThat(resp.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -311,18 +318,18 @@ public void testSingle() throws Exception { ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }) ).actionGet(); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } RestHelper rh = nonSslRestHelper(); // opendistro_security_shakespeare -> picard HttpResponse resc = rh.executeGetRequest("shakespeare/_search", encodeBasicHeader("picard", "picard")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"content\":1")); resc = rh.executeHeadRequest("shakespeare", encodeBasicHeader("picard", "picard")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); } @@ -332,13 +339,10 @@ public void testSpecialUsernames() throws Exception { setup(); RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("bug.88", "nagilum")).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest("", encodeBasicHeader("a", "b")).getStatusCode()); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("", encodeBasicHeader("\"'+-,;_?*@<>!$%&/()=#", "nagilum")).getStatusCode() - ); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("", encodeBasicHeader("§ÄÖÜäöüß", "nagilum")).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader("bug.88", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(rh.executeGetRequest("", encodeBasicHeader("a", "b")).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("", encodeBasicHeader("\"'+-,;_?*@<>!$%&/()=#", "nagilum")).getStatusCode())); + assertThat(rh.executeGetRequest("", encodeBasicHeader("§ÄÖÜäöüß", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); } @@ -352,7 +356,7 @@ public void testXff() throws Exception { new BasicHeader("x-forwarded-for", "10.0.0.7"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody().contains("10.0.0.7")); } @@ -377,25 +381,19 @@ public void testRegexExcludes() throws Exception { } RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("index*/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode())); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("indexa/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode())); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("index*/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode() + is(rh.executeGetRequest("isallowed/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode()) ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("indexa/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("isallowed/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("special/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode() + is(rh.executeGetRequest("special/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("alsonotallowed/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode() + is(rh.executeGetRequest("alsonotallowed/_search", encodeBasicHeader("rexclude", "nagilum")).getStatusCode()) ); } @@ -413,7 +411,7 @@ public void testMultiRoleSpan() throws Exception { } HttpResponse res = rh.executeGetRequest("/mindex_1,mindex_2/_search", encodeBasicHeader("mindex12", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertFalse(res.getBody().contains("\"content\":1")); Assert.assertFalse(res.getBody().contains("\"content\":2")); @@ -426,11 +424,11 @@ public void testMultiRoleSpan() throws Exception { ConfigUpdateResponse cur = tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[] { "config" })) .actionGet(); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); } res = rh.executeGetRequest("/mindex_1,mindex_2/_search", encodeBasicHeader("mindex12", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(res.getBody().contains("\"content\":1")); Assert.assertTrue(res.getBody().contains("\"content\":2")); @@ -454,13 +452,13 @@ public void testMultiRoleSpan2() throws Exception { } HttpResponse res = rh.executeGetRequest("/mindex_1,mindex_2/_search", encodeBasicHeader("mindex12", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("/mindex_1,mindex_3/_search", encodeBasicHeader("mindex12", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executeGetRequest("/mindex_1,mindex_4/_search", encodeBasicHeader("mindex12", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @@ -478,11 +476,11 @@ public void testSecurityUnderscore() throws Exception { res = rh.executeGetRequest("abc_xyz_2018_05_24/_doc/1", encodeBasicHeader("underscore", "nagilum")); Assert.assertTrue(res.getBody(), res.getBody().contains("\"content\":1")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("abc_xyz_2018_05_24/_refresh", encodeBasicHeader("underscore", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("aaa_bbb_2018_05_24/_refresh", encodeBasicHeader("underscore", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -500,13 +498,15 @@ public void testDeleteByQueryDnfof() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "/vulcango*/_delete_by_query?refresh=true&wait_for_completion=true&pretty=true", - "{\"query\" : {\"match_all\" : {}}}", - encodeBasicHeader("nagilum", "nagilum") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/vulcango*/_delete_by_query?refresh=true&wait_for_completion=true&pretty=true", + "{\"query\" : {\"match_all\" : {}}}", + encodeBasicHeader("nagilum", "nagilum") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"deleted\" : 3")); @@ -529,7 +529,7 @@ public void testUpdate() throws Exception { "{\"doc\" : {\"content\":2}}", encodeBasicHeader("user_c", "user_c") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -600,18 +600,18 @@ public void testDnfof() throws Exception { } HttpResponse resc; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("exception")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("permission")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_b", "user_b"))).getStatusCode() + is((resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_b", "user_b"))).getStatusCode()) ); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexb")); @@ -632,22 +632,22 @@ public void testDnfof() throws Exception { + System.lineSeparator(); // msearch resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_a", "user_a")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("permission")); - Assert.assertEquals(3, resc.getBody().split("\"status\" : 200").length); - Assert.assertEquals(2, resc.getBody().split("\"status\" : 403").length); + assertThat(resc.getBody().split("\"status\" : 200").length, is(3)); + assertThat(resc.getBody().split("\"status\" : 403").length, is(2)); resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("permission")); - Assert.assertEquals(3, resc.getBody().split("\"status\" : 200").length); - Assert.assertEquals(2, resc.getBody().split("\"status\" : 403").length); + assertThat(resc.getBody().split("\"status\" : 200").length, is(3)); + assertThat(resc.getBody().split("\"status\" : 403").length, is(2)); msearchBody = "{\"index\":\"indexc\", \"ignore_unavailable\": true}" + System.lineSeparator() @@ -659,9 +659,9 @@ public void testDnfof() throws Exception { + System.lineSeparator(); resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(resc.getBody(), 200, resc.getStatusCode()); - Assert.assertEquals(resc.getBody(), "security_exception", resc.findValueInJson("responses[0].error.type")); - Assert.assertEquals(resc.getBody(), "security_exception", resc.findValueInJson("responses[1].error.type")); + assertThat(resc.getBody(), resc.getStatusCode(), is(200)); + assertThat(resc.getBody(), resc.findValueInJson("responses[0].error.type"), is("security_exception")); + assertThat(resc.getBody(), resc.findValueInJson("responses[1].error.type"), is("security_exception")); String mgetBody = "{" + "\"docs\" : [" @@ -678,7 +678,7 @@ public void testDnfof() throws Exception { // mget resc = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("\"content\" : \"indexa\"")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("\"content\" : \"indexb\"")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); @@ -698,80 +698,77 @@ public void testDnfof() throws Exception { + "}"; resc = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(resc.getBody(), 200, resc.getStatusCode()); - Assert.assertEquals(resc.getBody(), "index_not_found_exception", resc.findValueInJson("docs[0].error.type")); - Assert.assertEquals(resc.getBody(), "index_not_found_exception", resc.findValueInJson("docs[1].error.type")); + assertThat(resc.getBody(), resc.getStatusCode(), is(200)); + assertThat(resc.getBody(), resc.findValueInJson("docs[0].error.type"), is("index_not_found_exception")); + assertThat(resc.getBody(), resc.findValueInJson("docs[1].error.type"), is("index_not_found_exception")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (resc = rh.executeGetRequest("_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexb")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (resc = rh.executeGetRequest("index*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("index*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("exception")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("permission")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("indexa/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexa/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("indexb/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexb/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() - ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode())); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_all/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("_all/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("notexists/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("notexists/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("permitnotexistentindex/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("permitnotexistentindex/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("permitnotexistentindex*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("permitnotexistentindex*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("indexanbh,indexabb*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexanbh,indexabb*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); // _all/_mapping/field/* - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_all/_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_all/_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); } @@ -843,14 +840,14 @@ public void testNoDnfof() throws Exception { } HttpResponse resc; - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_b", "user_b")).getStatusCode() + is(rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_b", "user_b")).getStatusCode()) ); String msearchBody = "{\"index\":\"indexa\", \"ignore_unavailable\": true}" @@ -863,7 +860,7 @@ public void testNoDnfof() throws Exception { + System.lineSeparator(); // msearch a resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_a", "user_a")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); @@ -871,7 +868,7 @@ public void testNoDnfof() throws Exception { // msearch b resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexb")); @@ -890,13 +887,13 @@ public void testNoDnfof() throws Exception { // msearch b2 resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexc")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexd")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("permission")); int count = resc.getBody().split("\"status\" : 403").length; - Assert.assertEquals(3, count); + assertThat(count, is(3)); String mgetBody = "{" + "\"docs\" : [" @@ -912,7 +909,7 @@ public void testNoDnfof() throws Exception { + "}"; resc = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("\"content\" : \"indexa\"")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); @@ -932,75 +929,72 @@ public void testNoDnfof() throws Exception { + "}"; resc = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); count = resc.getBody().split("root_cause").length; - Assert.assertEquals(3, count); + assertThat(count, is(3)); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("index*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("index*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("indexa/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexa/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("indexb/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexb/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("_all/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("_all/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("notexists/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("notexists/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("indexanbh,indexabb*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("indexanbh,indexabb*/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("user_a", "user_a")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode() + is(rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf")).getStatusCode()) ); // _all/_mapping/field/* - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_all/_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_all/_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); // _mapping/field/* - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); // */_mapping/field/* - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("*/_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("*/_mapping/field/*", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); } @@ -1014,45 +1008,45 @@ public void testSecurityIndexSecurity() throws Exception { "{\"properties\": {\"name\":{\"type\":\"text\"}}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePutRequest( "*dis*rit*/_mapping?pretty", "{\"properties\": {\"name\":{\"type\":\"text\"}}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePutRequest( "*/_mapping?pretty", "{\"properties\": {\"name\":{\"type\":\"text\"}}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePutRequest( "_all/_mapping?pretty", "{\"properties\": {\"name\":{\"type\":\"text\"}}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePostRequest(".opendistro_security/_close", "", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executeDeleteRequest(".opendistro_security", encodeBasicHeader("nagilum", "nagilum")); res = rh.executeDeleteRequest("_all", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePutRequest( ".opendistro_security/_settings", "{\"index\" : {\"number_of_replicas\" : 2}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePutRequest( ".opendistro_secur*/_settings", "{\"index\" : {\"number_of_replicas\" : 2}}", encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); res = rh.executePostRequest(".opendistro_security/_freeze", "", encodeBasicHeader("nagilum", "nagilum")); - Assert.assertEquals(400, res.getStatusCode()); + assertThat(res.getStatusCode(), is(400)); String bulkBody = "{ \"index\" : { \"_index\" : \".opendistro_security\", \"_id\" : \"1\" } }\n" + "{ \"field1\" : \"value1\" }\n" @@ -1064,11 +1058,11 @@ public void testSecurityIndexSecurity() throws Exception { res = rh.executePostRequest("_bulk?refresh=true&pretty", bulkBody, encodeBasicHeader("nagilum", "nagilum")); JsonNode jsonNode = readTree(res.getBody()); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); - Assert.assertEquals(403, jsonNode.get("items").get(0).get("index").get("status").intValue()); - Assert.assertEquals(403, jsonNode.get("items").get(1).get("index").get("status").intValue()); - Assert.assertEquals(201, jsonNode.get("items").get(2).get("index").get("status").intValue()); - Assert.assertEquals(403, jsonNode.get("items").get(3).get("delete").get("status").intValue()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(jsonNode.get("items").get(0).get("index").get("status").intValue(), is(403)); + assertThat(jsonNode.get("items").get(1).get("index").get("status").intValue(), is(403)); + assertThat(jsonNode.get("items").get(2).get("index").get("status").intValue(), is(201)); + assertThat(jsonNode.get("items").get(3).get("delete").get("status").intValue(), is(403)); } @Test @@ -1077,6 +1071,6 @@ public void testMonitorHealth() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig(), Settings.EMPTY); RestHelper rh = nonSslRestHelper(); - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("_cat/health", encodeBasicHeader("picard", "picard")).getStatusCode()); + assertThat(rh.executeGetRequest("_cat/health", encodeBasicHeader("picard", "picard")).getStatusCode(), is(HttpStatus.SC_OK)); } } diff --git a/src/test/java/org/opensearch/security/PitIntegrationTests.java b/src/test/java/org/opensearch/security/PitIntegrationTests.java index c1c25fcf9c..11c9ba8ddd 100644 --- a/src/test/java/org/opensearch/security/PitIntegrationTests.java +++ b/src/test/java/org/opensearch/security/PitIntegrationTests.java @@ -14,7 +14,6 @@ import java.util.List; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.action.admin.indices.alias.Alias; @@ -26,6 +25,9 @@ import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + /** * Integration tests to test point in time APIs permission model */ @@ -51,32 +53,32 @@ public void testPitExplicitAPIAccess() throws Exception { // Create point in time in index should be successful since the user has permission for index resc = rh.executePostRequest("/alias/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); String pitId1 = resc.findValueInJson("pit_id"); // Create point in time in index for which the user does not have permission resc = rh.executePostRequest("/pit_2/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Create point in time in index for which the user has permission for resc = rh.executePostRequest("/pit_2/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); String pitId2 = resc.findValueInJson("pit_id"); resc = rh.executePostRequest("/pit*/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("all-pit", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); // PIT segments should work since there is atleast one PIT for which user has access for resc = rh.executeGetRequest("/_cat/pit_segments", "{\"pit_id\":\"" + pitId1 + "\"}", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); // PIT segments should work since there is atleast one PIT for which user has access for resc = rh.executeGetRequest("/_cat/pit_segments", "{\"pit_id\":\"" + pitId1 + "\"}", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); // Should throw error since user does not have access for pitId2 resc = rh.executeGetRequest("/_cat/pit_segments", "{\"pit_id\":\"" + pitId2 + "\"}", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Should throw error since user does not have access for pitId2 resc = rh.executeGetRequest( @@ -84,17 +86,17 @@ public void testPitExplicitAPIAccess() throws Exception { "{\"pit_id\":[\"" + pitId1 + "\",\"" + pitId2 + "\"]}", encodeBasicHeader("pit-1", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Delete explicit PITs should work for PIT for which user has access for resc = rh.executeDeleteRequest("/_search/point_in_time", "{\"pit_id\":\"" + pitId1 + "\"}", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); - Assert.assertEquals(pitId1, resc.findValueInJson("pits[0].pit_id")); - Assert.assertEquals("true", resc.findValueInJson("pits[0].successful")); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(resc.findValueInJson("pits[0].pit_id"), is(pitId1)); + assertThat(resc.findValueInJson("pits[0].successful"), is("true")); // Should throw error since user does not have access for pitId2 resc = rh.executeDeleteRequest("/_search/point_in_time", "{\"pit_id\":\"" + pitId2 + "\"}", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Should throw error since user does not have access for pitId2 resc = rh.executeDeleteRequest( @@ -102,13 +104,13 @@ public void testPitExplicitAPIAccess() throws Exception { "{\"pit_id\":[\"" + pitId1 + "\",\"" + pitId2 + "\"]}", encodeBasicHeader("pit-1", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Delete explicit PITs should work for PIT for which user has access for resc = rh.executeDeleteRequest("/_search/point_in_time", "{\"pit_id\":\"" + pitId2 + "\"}", encodeBasicHeader("pit-2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); - Assert.assertEquals(pitId2, resc.findValueInJson("pits[0].pit_id")); - Assert.assertEquals("true", resc.findValueInJson("pits[0].successful")); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(resc.findValueInJson("pits[0].pit_id"), is(pitId2)); + assertThat(resc.findValueInJson("pits[0].successful"), is("true")); } @@ -135,26 +137,26 @@ public void testPitAllAPIAccess() throws Exception { // Create point in time in index should be successful since the user has permission for index resc = rh.executePostRequest("/pit_1/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); String pitId1 = resc.findValueInJson("pit_id"); // Create point in time in index for which the user does not have permission resc = rh.executePostRequest("/pit_2/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Create point in time in index for which the user has permission for resc = rh.executePostRequest("/pit_2/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); String pitId2 = resc.findValueInJson("pit_id"); // Throw security error if user does not have all index permission resc = rh.executeGetRequest("/_search/point_in_time/_all", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // List all PITs should work for user with all index access resc = rh.executeGetRequest("/_search/point_in_time/_all", encodeBasicHeader("all-pit", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); List pitList = new ArrayList<>(); pitList.add(pitId1); pitList.add(pitId2); @@ -163,23 +165,23 @@ public void testPitAllAPIAccess() throws Exception { // Throw security error if user does not have all index permission resc = rh.executeGetRequest("/_cat/pit_segments/_all", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // PIT segments should work for user with all index access resc = rh.executeGetRequest("/_cat/pit_segments/_all", encodeBasicHeader("all-pit", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); // Throw security error if user does not have all index permission resc = rh.executeDeleteRequest("/_search/point_in_time/_all", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Delete all PITs should work for user with all index access resc = rh.executeDeleteRequest("/_search/point_in_time/_all", encodeBasicHeader("all-pit", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); pitList.contains(resc.findValueInJson("pits[0].pit_id")); pitList.contains(resc.findValueInJson("pits[1].pit_id")); - Assert.assertEquals("true", resc.findValueInJson("pits[0].successful")); - Assert.assertEquals("true", resc.findValueInJson("pits[1].successful")); + assertThat(resc.findValueInJson("pits[0].successful"), is("true")); + assertThat(resc.findValueInJson("pits[1].successful"), is("true")); } @@ -198,24 +200,24 @@ public void testDataStreamWithPits() throws Exception { RestHelper.HttpResponse resc; // create pit should work since user has permission on data stream resc = rh.executePostRequest("/my-data-stream11/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); String pitId1 = resc.findValueInJson("pit_id"); // PIT segments works since the user has access for backing indices resc = rh.executeGetRequest("/_cat/pit_segments", "{\"pit_id\":\"" + pitId1 + "\"}", encodeBasicHeader("pit-1", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); // create pit should work since user has permission on data stream resc = rh.executePostRequest("/my-data-stream21/_search/point_in_time?keep_alive=100m", "", encodeBasicHeader("pit-2", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); String pitId2 = resc.findValueInJson("pit_id"); // since pit-3 doesn't have permission to backing data stream indices, throw security error resc = rh.executeGetRequest("/_cat/pit_segments", "{\"pit_id\":\"" + pitId2 + "\"}", encodeBasicHeader("pit-3", "nagilum")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Delete all PITs should work for user with all index access resc = rh.executeDeleteRequest("/_search/point_in_time/_all", encodeBasicHeader("all-pit", "nagilum")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); } } diff --git a/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java b/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java index b7af395daa..d52853c05b 100644 --- a/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java +++ b/src/test/java/org/opensearch/security/PrivilegesEvaluationTest.java @@ -12,7 +12,6 @@ package org.opensearch.security; import com.google.common.collect.ImmutableMap; -import org.junit.Assert; import org.junit.Test; import org.opensearch.action.admin.indices.create.CreateIndexRequest; @@ -23,6 +22,9 @@ import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class PrivilegesEvaluationTest extends SingleClusterTest { @Test public void resolveTestHidden() throws Exception { @@ -49,9 +51,9 @@ public void resolveTestHidden() throws Exception { "/*hidden_test*/_search?expand_wildcards=all&pretty=true", encodeBasicHeader("hidden_test", "nagilum") ); - Assert.assertEquals(httpResponse.getBody(), 403, httpResponse.getStatusCode()); + assertThat(httpResponse.getBody(), httpResponse.getStatusCode(), is(403)); httpResponse = rh.executeGetRequest("/hidden_test_not_hidden?pretty=true", encodeBasicHeader("hidden_test", "nagilum")); - Assert.assertEquals(httpResponse.getBody(), 200, httpResponse.getStatusCode()); + assertThat(httpResponse.getBody(), httpResponse.getStatusCode(), is(200)); } } diff --git a/src/test/java/org/opensearch/security/ResolveAPITests.java b/src/test/java/org/opensearch/security/ResolveAPITests.java index 765d933432..9d1c77341e 100644 --- a/src/test/java/org/opensearch/security/ResolveAPITests.java +++ b/src/test/java/org/opensearch/security/ResolveAPITests.java @@ -18,7 +18,6 @@ import org.apache.http.HttpStatus; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Assert; import org.junit.Test; import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest; @@ -32,6 +31,9 @@ import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class ResolveAPITests extends SingleClusterTest { protected final Logger log = LogManager.getLogger(this.getClass()); @@ -47,9 +49,9 @@ public void testResolveDnfofFalse() throws Exception { final RestHelper rh = nonSslRestHelper(); RestHelper.HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()) ); log.debug(res.getBody()); assertNotContains(res, "*xception*"); @@ -61,9 +63,9 @@ public void testResolveDnfofFalse() throws Exception { assertContains(res, "*xyz*"); assertContains(res, "*role01_role02*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()) ); log.debug(res.getBody()); assertNotContains(res, "*xception*"); @@ -77,15 +79,15 @@ public void testResolveDnfofFalse() throws Exception { assertContains(res, "*starfleet_academy*"); assertContains(res, "*starfleet_library*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode()) ); log.debug(res.getBody()); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode()) ); log.debug(res.getBody()); assertContains(res, "*starfleet*"); @@ -103,9 +105,9 @@ public void testResolveDnfofTrue() throws Exception { final RestHelper rh = nonSslRestHelper(); RestHelper.HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()) ); log.debug(res.getBody()); assertNotContains(res, "*xception*"); @@ -117,9 +119,9 @@ public void testResolveDnfofTrue() throws Exception { assertContains(res, "*xyz*"); assertContains(res, "*role01_role02*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()) ); log.debug(res.getBody()); assertNotContains(res, "*xception*"); @@ -133,9 +135,9 @@ public void testResolveDnfofTrue() throws Exception { assertContains(res, "*starfleet_academy*"); assertContains(res, "*starfleet_library*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode()) ); log.debug(res.getBody()); assertNotContains(res, "*xception*"); @@ -147,9 +149,9 @@ public void testResolveDnfofTrue() throws Exception { assertContains(res, "*public*"); assertContains(res, "*xyz*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/starfleet*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode()) ); log.debug(res.getBody()); assertNotContains(res, "*xception*"); @@ -163,9 +165,9 @@ public void testResolveDnfofTrue() throws Exception { assertContains(res, "*starfleet_academy*"); assertContains(res, "*starfleet_library*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (res = rh.executeGetRequest("_resolve/index/vulcangov*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode() + is((res = rh.executeGetRequest("_resolve/index/vulcangov*?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode()) ); log.debug(res.getBody()); } diff --git a/src/test/java/org/opensearch/security/RolesInjectorIntegTest.java b/src/test/java/org/opensearch/security/RolesInjectorIntegTest.java index 3137eab640..42fca1c065 100644 --- a/src/test/java/org/opensearch/security/RolesInjectorIntegTest.java +++ b/src/test/java/org/opensearch/security/RolesInjectorIntegTest.java @@ -53,6 +53,9 @@ import org.opensearch.transport.Netty4ModulePlugin; import org.opensearch.watcher.ResourceWatcherService; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class RolesInjectorIntegTest extends SingleClusterTest { public static class RolesInjectorPlugin extends Plugin implements ActionPlugin { @@ -87,18 +90,20 @@ public Collection createComponents( public void testRolesInject() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig().setSecurityRoles("roles.yml"), Settings.EMPTY); - Assert.assertEquals( + assertThat( clusterInfo.numNodes, - clusterHelper.nodeClient() - .admin() - .cluster() - .health(new ClusterHealthRequest().waitForGreenStatus()) - .actionGet() - .getNumberOfNodes() + is( + clusterHelper.nodeClient() + .admin() + .cluster() + .health(new ClusterHealthRequest().waitForGreenStatus()) + .actionGet() + .getNumberOfNodes() + ) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); final Settings tcSettings = AbstractSecurityUnitTest.nodeRolesSettings(Settings.builder(), false, false) diff --git a/src/test/java/org/opensearch/security/SecurityAdminIEndpointsTests.java b/src/test/java/org/opensearch/security/SecurityAdminIEndpointsTests.java index 99cf3b82fe..36f11b364f 100644 --- a/src/test/java/org/opensearch/security/SecurityAdminIEndpointsTests.java +++ b/src/test/java/org/opensearch/security/SecurityAdminIEndpointsTests.java @@ -12,7 +12,6 @@ package org.opensearch.security; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.common.settings.Settings; @@ -20,6 +19,9 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SecurityAdminIEndpointsTests extends SingleClusterTest { @Test @@ -28,18 +30,22 @@ public void testNoSSL() throws Exception { setup(settings); final RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode()); - Assert.assertEquals( + assertThat(rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest("_plugins/_security/whoami").getStatusCode()); + assertThat(rh.executeGetRequest("_plugins/_security/whoami").getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -56,89 +62,102 @@ public void testEndpoints() throws Exception { rh.trustHTTPServerCertificate = true; rh.sendAdminCertificate = false; - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode()); - Assert.assertEquals( + assertThat(rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); RestHelper.HttpResponse res; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*\"dn\":null*"); rh.sendAdminCertificate = true; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*\"dn\":\"CN=node-0.example.com*"); assertContains(res, "*\"is_admin\":false*"); assertContains(res, "*\"is_node_certificate_request\":true*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode()); - Assert.assertEquals( + assertThat(rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); rh.keystore = "spock-keystore.jks"; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*\"dn\":\"CN=spock*"); assertContains(res, "*\"is_admin\":false*"); assertContains(res, "*\"is_node_certificate_request\":false*"); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode()); - Assert.assertEquals( + assertThat(rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=xxx", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); rh.keystore = "kirk-keystore.jks"; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_plugins/_security/whoami")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*\"dn\":\"CN=kirk*"); assertContains(res, "*\"is_admin\":true*"); assertContains(res, "*\"is_node_certificate_request\":false*"); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() - ); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode()); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "").getStatusCode() + is( + rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "{}", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); + assertThat(rh.executePutRequest("_plugins/_security/configupdate", "").getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); + assertThat(HttpStatus.SC_OK, is(rh.executePutRequest("_plugins/_security/configupdate?config_types=roles", "").getStatusCode())); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePutRequest( - "_plugins/_security/configupdate?config_types=unknown_xxx", - "", - encodeBasicHeader("nagilum", "nagilum") - )).getStatusCode() + is( + (res = rh.executePutRequest( + "_plugins/_security/configupdate?config_types=unknown_xxx", + "", + encodeBasicHeader("nagilum", "nagilum") + )).getStatusCode() + ) ); assertContains(res, "*\"successful\":0*failed_node_exception*"); diff --git a/src/test/java/org/opensearch/security/SecurityAdminInvalidConfigsTests.java b/src/test/java/org/opensearch/security/SecurityAdminInvalidConfigsTests.java index 1586878b9f..90af959830 100644 --- a/src/test/java/org/opensearch/security/SecurityAdminInvalidConfigsTests.java +++ b/src/test/java/org/opensearch/security/SecurityAdminInvalidConfigsTests.java @@ -40,6 +40,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.tools.SecurityAdmin; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SecurityAdminInvalidConfigsTests extends SingleClusterTest { @Test @@ -71,15 +74,12 @@ public void testSecurityAdminDuplicateKey() throws Exception { RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat((rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); } @Test @@ -101,19 +101,16 @@ public void testSecurityAdminDuplicateKeyReload() throws Exception { argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat((rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); } @Test @@ -147,15 +144,12 @@ public void testSecurityAdminDuplicateKeySingleFile() throws Exception { RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); - Assert.assertEquals( + assertThat((rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); } @Test @@ -177,18 +171,15 @@ public void testSecurityAdminDuplicateKeyReloadSingleFile() throws Exception { argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat((rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); } } diff --git a/src/test/java/org/opensearch/security/SecurityAdminTests.java b/src/test/java/org/opensearch/security/SecurityAdminTests.java index d2b7dab37d..44c2934469 100644 --- a/src/test/java/org/opensearch/security/SecurityAdminTests.java +++ b/src/test/java/org/opensearch/security/SecurityAdminTests.java @@ -40,6 +40,7 @@ import org.opensearch.security.tools.SecurityAdmin; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.matchesPattern; import static org.junit.Assert.assertThrows; @@ -73,11 +74,11 @@ public void testSecurityAdmin() throws Exception { argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -159,7 +160,7 @@ public void testSecurityAdminHostnameVerificationNotEnforced() throws Exception argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); } @Test @@ -190,11 +191,11 @@ public void testSecurityAdminInvalidCert() throws Exception { argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_plugins/_security/health?pretty")).getStatusCode()); + assertThat((rh.executeGetRequest("_plugins/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); argsAsList = new ArrayList<>(); argsAsList.add("-ts"); @@ -214,9 +215,9 @@ public void testSecurityAdminInvalidCert() throws Exception { argsAsList.add("-nhnv"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(-1, returnCode); + assertThat(returnCode, is(-1)); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_plugins/_security/health?pretty")).getStatusCode()); + assertThat((rh.executeGetRequest("_plugins/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); argsAsList = new ArrayList<>(); argsAsList.add("-ts"); @@ -235,9 +236,9 @@ public void testSecurityAdminInvalidCert() throws Exception { argsAsList.add("-nhnv"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(-1, returnCode); + assertThat(returnCode, is(-1)); - Assert.assertEquals(HttpStatus.SC_OK, (rh.executeGetRequest("_plugins/_security/health?pretty")).getStatusCode()); + assertThat((rh.executeGetRequest("_plugins/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -272,7 +273,7 @@ public void testSecurityAdminV6Update() throws Exception { RestHelper rh = restHelper(); - Assert.assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, rh.executeGetRequest("_opendistro/_security/health?pretty").getStatusCode()); + assertThat(rh.executeGetRequest("_opendistro/_security/health?pretty").getStatusCode(), is(HttpStatus.SC_SERVICE_UNAVAILABLE)); } @Test @@ -303,12 +304,12 @@ public void testSecurityAdminRegularUpdate() throws Exception { argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); RestHelper rh = restHelper(); HttpResponse res; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*UP*"); assertContains(res, "*strict*"); assertNotContains(res, "*DOWN*"); @@ -345,7 +346,7 @@ public void testSecurityAdminSingularV7Updates() throws Exception { argsAsList.add("-nhnv"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-ts"); @@ -367,7 +368,7 @@ public void testSecurityAdminSingularV7Updates() throws Exception { argsAsList.add("-nhnv"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-ts"); @@ -389,12 +390,12 @@ public void testSecurityAdminSingularV7Updates() throws Exception { argsAsList.add("-nhnv"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); RestHelper rh = restHelper(); HttpResponse res; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*UP*"); assertContains(res, "*strict*"); assertNotContains(res, "*DOWN*"); @@ -436,7 +437,7 @@ public void testSecurityAdminSingularV6Updates() throws Exception { RestHelper rh = restHelper(); HttpResponse res; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*UP*"); assertContains(res, "*strict*"); assertNotContains(res, "*DOWN*"); @@ -482,7 +483,7 @@ public void testSecurityAdminInvalidYml() throws Exception { RestHelper rh = restHelper(); HttpResponse res; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*UP*"); assertContains(res, "*strict*"); assertNotContains(res, "*DOWN*"); @@ -505,10 +506,7 @@ public void testSecurityAdminReloadInvalidConfig() throws Exception { rh.keystore = "kirk-keystore.jks"; rh.executePutRequest(".opendistro_security/_doc/roles", FileHelper.loadFile("roles_invalidxcontent.yml")); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executePutRequest(".opendistro_security/_doc/roles", "{\"roles\":\"dummy\"}").getStatusCode() - ); + assertThat(HttpStatus.SC_OK, is(rh.executePutRequest(".opendistro_security/_doc/roles", "{\"roles\":\"dummy\"}").getStatusCode())); final String prefix = getResourceFolder() == null ? "" : getResourceFolder() + "/"; @@ -533,7 +531,7 @@ public void testSecurityAdminReloadInvalidConfig() throws Exception { HttpResponse res; - Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode()); + assertThat((res = rh.executeGetRequest("_opendistro/_security/health?pretty")).getStatusCode(), is(HttpStatus.SC_OK)); assertContains(res, "*UP*"); assertContains(res, "*strict*"); assertNotContains(res, "*DOWN*"); @@ -546,7 +544,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList.add("-vc"); int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-f"); @@ -554,7 +552,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-f"); @@ -562,7 +560,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-f"); @@ -572,7 +570,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-f"); @@ -580,7 +578,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList.add("-vc"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); argsAsList.add("-f"); @@ -613,7 +611,7 @@ public void testSecurityAdminValidateConfig() throws Exception { argsAsList.add("6"); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); argsAsList = new ArrayList<>(); addDirectoryPath(argsAsList, TEST_RESOURCE_ABSOLUTE_PATH); @@ -653,7 +651,7 @@ public void testIsLegacySecurityIndexOnV7Index() throws Exception { // Execute first time to create the index int returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); @@ -661,7 +659,7 @@ public void testIsLegacySecurityIndexOnV7Index() throws Exception { System.setOut(ps); returnCode = SecurityAdmin.execute(argsAsList.toArray(new String[0])); - Assert.assertEquals(0, returnCode); + assertThat(returnCode, is(0)); System.out.flush(); System.setOut(old); diff --git a/src/test/java/org/opensearch/security/SecurityRolesTests.java b/src/test/java/org/opensearch/security/SecurityRolesTests.java index 0b4dd0b95b..e042fc6fa3 100644 --- a/src/test/java/org/opensearch/security/SecurityRolesTests.java +++ b/src/test/java/org/opensearch/security/SecurityRolesTests.java @@ -38,6 +38,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SecurityRolesTests extends SingleClusterTest { @Test @@ -55,14 +58,14 @@ public void testSecurityRolesAnon() throws Exception { HttpResponse resc = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); Assert.assertTrue(resc.getBody().contains("anonymous")); Assert.assertFalse(resc.getBody().contains("xyz_sr")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("sr_user", "nagilum")); Assert.assertTrue(resc.getBody().contains("sr_user")); Assert.assertTrue(resc.getBody().contains("xyz_sr")); Assert.assertFalse(resc.getBody().contains("opendistro_security_kibana_server")); Assert.assertTrue(resc.getBody().contains("backend_roles=[abc_ber]")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -92,7 +95,7 @@ public void testSecurityRoles() throws Exception { Assert.assertFalse(resc.getBody().contains("xyz_sr_hidden")); Assert.assertTrue(resc.getBody().contains("backend_roles=[abc_ber]")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -116,13 +119,13 @@ public void testSecurityRolesImpersonation() throws Exception { Assert.assertFalse(resc.getBody().contains("xyz_sr")); Assert.assertTrue(resc.getBody().contains("xyz_impsr")); Assert.assertTrue(resc.getBody().contains("backend_roles=[ert_ber]")); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); resc = rh.executeGetRequest( "*/_search?pretty", encodeBasicHeader("sr_user", "nagilum"), new BasicHeader("opendistro_security_impersonate_as", "sr_impuser") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); } } diff --git a/src/test/java/org/opensearch/security/SlowIntegrationTests.java b/src/test/java/org/opensearch/security/SlowIntegrationTests.java index eb147ec422..74e3bfa9e4 100644 --- a/src/test/java/org/opensearch/security/SlowIntegrationTests.java +++ b/src/test/java/org/opensearch/security/SlowIntegrationTests.java @@ -51,7 +51,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.transport.Netty4ModulePlugin; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThrows; public class SlowIntegrationTests extends SingleClusterTest { @@ -67,18 +69,20 @@ public void testCustomInterclusterRequestEvaluator() throws Exception { .put("discovery.initial_state_timeout", "8s") .build(); setup(Settings.EMPTY, null, settings, false, ClusterConfiguration.DEFAULT, 5, 1); - Assert.assertEquals( + assertThat( 1, - clusterHelper.nodeClient() - .admin() - .cluster() - .health(new ClusterHealthRequest().waitForGreenStatus()) - .actionGet() - .getNumberOfNodes() + is( + clusterHelper.nodeClient() + .admin() + .cluster() + .health(new ClusterHealthRequest().waitForGreenStatus()) + .actionGet() + .getNumberOfNodes() + ) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); } @@ -86,18 +90,20 @@ public void testCustomInterclusterRequestEvaluator() throws Exception { @Test public void testNodeClientAllowedWithServerCertificate() throws Exception { setup(); - Assert.assertEquals( + assertThat( clusterInfo.numNodes, - clusterHelper.nodeClient() - .admin() - .cluster() - .health(new ClusterHealthRequest().waitForGreenStatus()) - .actionGet() - .getNumberOfNodes() + is( + clusterHelper.nodeClient() + .admin() + .cluster() + .health(new ClusterHealthRequest().waitForGreenStatus()) + .actionGet() + .getNumberOfNodes() + ) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); final Settings tcSettings = AbstractSecurityUnitTest.nodeRolesSettings(Settings.builder(), false, false) @@ -125,9 +131,9 @@ public void testNodeClientAllowedWithServerCertificate() throws Exception { .actionGet() .isTimedOut() ); - Assert.assertEquals( + assertThat( clusterInfo.numNodes + 1, - node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size() + is(node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()) ); } } @@ -136,18 +142,20 @@ public void testNodeClientAllowedWithServerCertificate() throws Exception { @Test public void testNodeClientDisallowedWithNonServerCertificate() throws Exception { setup(); - Assert.assertEquals( + assertThat( clusterInfo.numNodes, - clusterHelper.nodeClient() - .admin() - .cluster() - .health(new ClusterHealthRequest().waitForGreenStatus()) - .actionGet() - .getNumberOfNodes() + is( + clusterHelper.nodeClient() + .admin() + .cluster() + .health(new ClusterHealthRequest().waitForGreenStatus()) + .actionGet() + .getNumberOfNodes() + ) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); final Settings tcSettings = AbstractSecurityUnitTest.nodeRolesSettings(Settings.builder(), false, false) @@ -170,7 +178,7 @@ public void testNodeClientDisallowedWithNonServerCertificate() throws Exception .start() ) { Thread.sleep(10000); - Assert.assertEquals(1, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(1)); } catch (Exception e) { Assert.fail(e.toString()); } @@ -181,18 +189,20 @@ public void testNodeClientDisallowedWithNonServerCertificate() throws Exception @Test public void testNodeClientDisallowedWithNonServerCertificate2() throws Exception { setup(); - Assert.assertEquals( + assertThat( clusterInfo.numNodes, - clusterHelper.nodeClient() - .admin() - .cluster() - .health(new ClusterHealthRequest().waitForGreenStatus()) - .actionGet() - .getNumberOfNodes() + is( + clusterHelper.nodeClient() + .admin() + .cluster() + .health(new ClusterHealthRequest().waitForGreenStatus()) + .actionGet() + .getNumberOfNodes() + ) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); final Settings tcSettings = AbstractSecurityUnitTest.nodeRolesSettings(Settings.builder(), false, false) @@ -215,7 +225,7 @@ public void testNodeClientDisallowedWithNonServerCertificate2() throws Exception .start() ) { Thread.sleep(10000); - Assert.assertEquals(1, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(1)); } catch (Exception e) { Assert.fail(e.toString()); } diff --git a/src/test/java/org/opensearch/security/SnapshotRestoreTests.java b/src/test/java/org/opensearch/security/SnapshotRestoreTests.java index 1e9c26d898..0291b79577 100644 --- a/src/test/java/org/opensearch/security/SnapshotRestoreTests.java +++ b/src/test/java/org/opensearch/security/SnapshotRestoreTests.java @@ -52,6 +52,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; public class SnapshotRestoreTests extends SingleClusterTest { @@ -118,143 +119,164 @@ public void testSnapshotEnableSecurityIndexRestore() throws Exception { } RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/vulcangov", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/vulcangov", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/vulcangov/vulcangov_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/vulcangov/vulcangov_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // worf not allowed to restore vulcangov index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("worf", "worf") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("worf", "worf") + ).getStatusCode() + ) ); // Try to restore vulcangov index as .opendistro_security index, not possible since Security index is open - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index. - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/.opendistro_security", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/.opendistro_security", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/.opendistro_security/opendistro_security_1", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("_snapshot/.opendistro_security/opendistro_security_1", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); // 500 because Security index is open - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore all indices. - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/all", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("_snapshot/all", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/all/all_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/all/all_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); // 500 because Security index is open - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executePostRequest("_snapshot/all/all_1/_restore?wait_for_completion=true", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePostRequest("_snapshot/all/all_1/_restore?wait_for_completion=true", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); // Try to restore vulcangov index as .opendistro_security index -> 500 because Security index is open - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index. Delete opendistro_security_copy first, was created // in test above - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeDeleteRequest("opendistro_security_copy", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeDeleteRequest("opendistro_security_copy", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore an unknown snapshot - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - rh.executePostRequest( - "_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // close and restore Security index - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest(".opendistro_security/_close", "", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executePostRequest(".opendistro_security/_close", "", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executePostRequest(".opendistro_security/_open", "", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executePostRequest(".opendistro_security/_open", "", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); } @@ -318,121 +340,140 @@ public void testSnapshot() throws Exception { } RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/vulcangov", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/vulcangov", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/vulcangov/vulcangov_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/vulcangov/vulcangov_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("worf", "worf") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("worf", "worf") + ).getStatusCode() + ) ); // Try to restore vulcangov index as .opendistro_security index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index. - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/.opendistro_security", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/.opendistro_security", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/.opendistro_security/opendistro_security_1", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("_snapshot/.opendistro_security/opendistro_security_1", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore all indices. - Assert.assertEquals( + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("_snapshot/all", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/all", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/all/all_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/all/all_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("_snapshot/all/all_1/_restore?wait_for_completion=true", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePostRequest("_snapshot/all/all_1/_restore?wait_for_completion=true", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore an unknown snapshot - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, + is( + rh.executePostRequest( + "_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + // assertThat(HttpStatus.SC_FORBIDDEN, // executePostRequest("_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true","{ \"indices\": \"the-unknown-index\" }", - // encodeBasicHeader("nagilum", "nagilum"))).getStatusCode()); + // encois(deBasicHeader("nagilum", "nagilum"))).getStatusCode()); } @Test @@ -495,173 +536,204 @@ public void testSnapshotCheckWritePrivileges() throws Exception { new ConfigUpdateRequest(new String[] { "config", "roles", "rolesmapping", "internalusers", "actiongroups" }) ).actionGet(); Assert.assertFalse(cur.hasFailures()); - Assert.assertEquals(currentClusterConfig.getNodes(), cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(currentClusterConfig.getNodes())); } RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/vulcangov", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/vulcangov", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/vulcangov/vulcangov_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/vulcangov/vulcangov_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("worf", "worf") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("worf", "worf") + ).getStatusCode() + ) ); // Try to restore vulcangov index as .opendistro_security index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index. - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/.opendistro_security", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/.opendistro_security", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/.opendistro_security/opendistro_security_1", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executeGetRequest("_snapshot/.opendistro_security/opendistro_security_1", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", - "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/.opendistro_security/opendistro_security_1/_restore?wait_for_completion=true", + "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore all indices. - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/all", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() - ); - Assert.assertEquals( + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("_snapshot/all", encodeBasicHeader("nagilum", "nagilum")).getStatusCode())); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/all/all_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode() + is(rh.executeGetRequest("_snapshot/all/all_1", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest("_snapshot/all/all_1/_restore?wait_for_completion=true", "", encodeBasicHeader("nagilum", "nagilum")) - .getStatusCode() + is( + rh.executePostRequest("_snapshot/all/all_1/_restore?wait_for_completion=true", "", encodeBasicHeader("nagilum", "nagilum")) + .getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{ \"indices\": \"vulcangov\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \".opendistro_security\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore .opendistro_security index as .opendistro_security_copy index - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{ \"indices\": \".opendistro_security\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"opendistro_security_copy\" }", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Try to restore an unknown snapshot - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true", - "", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/unknown-snapshot/_restore?wait_for_completion=true", + "", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); // Tests snapshot with write permissions (OK) - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_restore_1\" }", - encodeBasicHeader("restoreuser", "restoreuser") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_restore_1\" }", + encodeBasicHeader("restoreuser", "restoreuser") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_restore_2a\" }", - encodeBasicHeader("restoreuser", "restoreuser") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_restore_2a\" }", + encodeBasicHeader("restoreuser", "restoreuser") + ).getStatusCode() + ) ); // Test snapshot with write permissions (OK) - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_1\" }", - encodeBasicHeader("restoreuser", "restoreuser") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_1\" }", + encodeBasicHeader("restoreuser", "restoreuser") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_2\" }", - encodeBasicHeader("restoreuser", "restoreuser") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_2\" }", + encodeBasicHeader("restoreuser", "restoreuser") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_3\" }", - encodeBasicHeader("restoreuser", "restoreuser") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_3\" }", + encodeBasicHeader("restoreuser", "restoreuser") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_4\" }", - encodeBasicHeader("restoreuser", "restoreuser") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/vulcangov/vulcangov_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"$1_no_restore_4\" }", + encodeBasicHeader("restoreuser", "restoreuser") + ).getStatusCode() + ) ); } @@ -708,21 +780,25 @@ public void testSnapshotRestore() throws Exception { + "\"include_global_state\": false" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", - putSnapshot, - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePutRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", + putSnapshot, + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) ); putSnapshot = "{" @@ -731,40 +807,48 @@ public void testSnapshotRestore() throws Exception { + "\"include_global_state\": false" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", - putSnapshot, - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePutRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", + putSnapshot, + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) ); putSnapshot = "{" + "\"indices\": \"testsnap2\"," + "\"ignore_unavailable\": false," + "\"include_global_state\": true" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", - putSnapshot, - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePutRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", + putSnapshot, + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", - "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", + "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) ); } @@ -813,21 +897,25 @@ public void testSnapshotRestoreSpecialIndicesPatterns() throws Exception { RestHelper rh = nonSslRestHelper(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{\"indices\": \"b*,-bar\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"wild_first_restored_index_$1\"}", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{\"indices\": \"b*,-bar\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"wild_first_restored_index_$1\"}", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/all/all_1/_restore?wait_for_completion=true", - "{\"indices\": \"-bar,b*\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"neg_first_restored_index_$1\"}", - encodeBasicHeader("nagilum", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/all/all_1/_restore?wait_for_completion=true", + "{\"indices\": \"-bar,b*\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"neg_first_restored_index_$1\"}", + encodeBasicHeader("nagilum", "nagilum") + ).getStatusCode() + ) ); String wild_first_body = rh.executePostRequest( "_snapshot/all/all_1/_restore?wait_for_completion=true", @@ -849,7 +937,6 @@ public void testSnapshotRestoreSpecialIndicesPatterns() throws Exception { @Test public void testNoSnapshotRestore() throws Exception { - final Settings settings = Settings.builder() .putList("path.repo", repositoryPath.getRoot().getAbsolutePath()) .put("plugins.security.enable_snapshot_restore_privilege", false) @@ -893,21 +980,25 @@ public void testNoSnapshotRestore() throws Exception { + "\"include_global_state\": false" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", - putSnapshot, - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePutRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", + putSnapshot, + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) ); putSnapshot = "{" @@ -916,40 +1007,48 @@ public void testNoSnapshotRestore() throws Exception { + "\"include_global_state\": false" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", - putSnapshot, - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePutRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", + putSnapshot, + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) ); putSnapshot = "{" + "\"indices\": \"testsnap2\"," + "\"ignore_unavailable\": false," + "\"include_global_state\": true" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", - putSnapshot, - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() - ); - Assert.assertEquals( + is( + rh.executePutRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "?wait_for_completion=true&pretty", + putSnapshot, + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) + ); + assertThat( HttpStatus.SC_FORBIDDEN, - rh.executePostRequest( - "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", - "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", - encodeBasicHeader("snapresuser", "nagilum") - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/bckrepo/" + putSnapshot.hashCode() + "/_restore?wait_for_completion=true&pretty", + "{ \"include_global_state\": true, \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_$1\" }", + encodeBasicHeader("snapresuser", "nagilum") + ).getStatusCode() + ) ); } } diff --git a/src/test/java/org/opensearch/security/SystemIntegratorsTests.java b/src/test/java/org/opensearch/security/SystemIntegratorsTests.java index b927ceaba2..ec4f4f8ddb 100644 --- a/src/test/java/org/opensearch/security/SystemIntegratorsTests.java +++ b/src/test/java/org/opensearch/security/SystemIntegratorsTests.java @@ -39,6 +39,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SystemIntegratorsTests extends SingleClusterTest { @Test @@ -57,55 +60,55 @@ public void testInjectedUserMalformed() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, null) ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "|||") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "||127.0.0:80|") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "username||ip|") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "username||ip:port|") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "username||ip:80|") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "username||127.0.x:80|") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "username||127.0.0:80|key1,value1,key2") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); resc = rh.executeGetRequest( "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "||127.0.0:80|key1,value1,key2,value2") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); } @@ -125,7 +128,7 @@ public void testInjectedUser() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "admin||127.0.0:80|") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=admin, backend_roles=[], requestedTenant=null]")); Assert.assertTrue(resc.getBody().contains("\"remote_address\":\"127.0.0.0:80\"")); Assert.assertTrue(resc.getBody().contains("\"backend_roles\":[]")); @@ -135,7 +138,7 @@ public void testInjectedUser() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "admin|role1|127.0.0:80|key1,value1") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=admin, backend_roles=[role1], requestedTenant=null]")); Assert.assertTrue(resc.getBody().contains("\"remote_address\":\"127.0.0.0:80\"")); Assert.assertTrue(resc.getBody().contains("\"backend_roles\":[\"role1\"]")); @@ -145,7 +148,7 @@ public void testInjectedUser() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "admin|role1,role2||key1,value1") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=admin, backend_roles=[role1, role2], requestedTenant=null]")); // remote IP is assigned by XFFResolver Assert.assertFalse(resc.getBody().contains("\"remote_address\":null")); @@ -156,7 +159,7 @@ public void testInjectedUser() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "admin|role1,role2|8.8.8.8:8|key1,value1,key2,value2") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=admin, backend_roles=[role1, role2], requestedTenant=null]")); // remote IP is assigned by XFFResolver Assert.assertFalse(resc.getBody().contains("\"remote_address\":null")); @@ -167,7 +170,7 @@ public void testInjectedUser() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "nagilum|role1,role2|8.8.8.8:8|key1,value1,key2,value2") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=nagilum, backend_roles=[role1, role2], requestedTenant=null]")); // remote IP is assigned by XFFResolver Assert.assertTrue(resc.getBody().contains("\"remote_address\":\"8.8.8.8:8\"")); @@ -180,7 +183,7 @@ public void testInjectedUser() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "myuser|role1,vulcanadmin|8.8.8.8:8|key1,value1,key2,value2") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=myuser, backend_roles=[role1, vulcanadmin], requestedTenant=null]")); // remote IP is assigned by XFFResolver Assert.assertTrue(resc.getBody().contains("\"remote_address\":\"8.8.8.8:8\"")); @@ -197,7 +200,7 @@ public void testInjectedUser() throws Exception { "myuser|role1,vulcanadmin|8.8.8.8:8|key1,value1,key2,value2|" ) ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=myuser, backend_roles=[role1, vulcanadmin], requestedTenant=null]")); // remote IP is assigned by XFFResolver Assert.assertTrue(resc.getBody().contains("\"remote_address\":\"8.8.8.8:8\"")); @@ -213,7 +216,7 @@ public void testInjectedUser() throws Exception { "myuser|role1,vulcanadmin|8.8.8.8:8|key1,value1,key2,value2|mytenant" ) ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("User [name=myuser, backend_roles=[role1, vulcanadmin], requestedTenant=mytenant]")); // remote IP is assigned by XFFResolver Assert.assertTrue(resc.getBody().contains("\"remote_address\":\"8.8.8.8:8\"")); @@ -229,7 +232,7 @@ public void testInjectedUser() throws Exception { "myuser|role1,vulcanadmin|8.8.8.8:8||mytenant with whitespace" ) ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue( resc.getBody().contains("User [name=myuser, backend_roles=[role1, vulcanadmin], requestedTenant=mytenant with whitespace]") ); @@ -257,7 +260,7 @@ public void testInjectedUserDisabled() throws Exception { "_opendistro/_security/authinfo", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "admin|role1|127.0.0:80|key1,value1") ); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); } @Test @@ -282,7 +285,7 @@ public void testInjectedAdminUser() throws Exception { ".opendistro_security/_search?pretty", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "injectedadmin|role1|127.0.0:80|key1,value1") ); - Assert.assertEquals(HttpStatus.SC_OK, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(resc.getBody().contains("\"_id\" : \"config\"")); Assert.assertTrue(resc.getBody().contains("\"_id\" : \"roles\"")); Assert.assertTrue(resc.getBody().contains("\"_id\" : \"internalusers\"")); @@ -292,7 +295,7 @@ public void testInjectedAdminUser() throws Exception { ".opendistro_security/_search?pretty", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "wrongadmin|role1|127.0.0:80|key1,value1") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @@ -317,7 +320,7 @@ public void testInjectedAdminUserAdminInjectionDisabled() throws Exception { ".opendistro_security/_search?pretty", new BasicHeader(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "injectedadmin|role1|127.0.0:80|key1,value1") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertFalse(resc.getBody().contains("\"_id\" : \"config\"")); Assert.assertFalse(resc.getBody().contains("\"_id\" : \"roles\"")); Assert.assertFalse(resc.getBody().contains("\"_id\" : \"internalusers\"")); diff --git a/src/test/java/org/opensearch/security/TaskTests.java b/src/test/java/org/opensearch/security/TaskTests.java index e58fa5c6a9..daae9631d0 100644 --- a/src/test/java/org/opensearch/security/TaskTests.java +++ b/src/test/java/org/opensearch/security/TaskTests.java @@ -29,6 +29,9 @@ import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; import org.opensearch.tasks.Task; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class TaskTests extends SingleClusterTest { @Test @@ -37,13 +40,15 @@ public void testXOpaqueIdHeader() throws Exception { RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - "_tasks?group_by=parents&pretty", - encodeBasicHeader("nagilum", "nagilum"), - new BasicHeader(Task.X_OPAQUE_ID, "myOpaqueId12") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + "_tasks?group_by=parents&pretty", + encodeBasicHeader("nagilum", "nagilum"), + new BasicHeader(Task.X_OPAQUE_ID, "myOpaqueId12") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().split("X-Opaque-Id").length > 2); Assert.assertTrue(!res.getBody().contains("failures")); diff --git a/src/test/java/org/opensearch/security/TracingTests.java b/src/test/java/org/opensearch/security/TracingTests.java index 7ae663a41f..36ebbbf4fd 100644 --- a/src/test/java/org/opensearch/security/TracingTests.java +++ b/src/test/java/org/opensearch/security/TracingTests.java @@ -27,7 +27,6 @@ package org.opensearch.security; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; @@ -48,6 +47,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + @Ignore("subject for manual execution") public class TracingTests extends SingleClusterTest { @@ -389,7 +391,7 @@ public void testHTTPSingle() throws Exception { // end pause1 // search - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("_search", encodeBasicHeader("nagilum", "nagilum")).getStatusCode()); + assertThat(rh.executeGetRequest("_search", encodeBasicHeader("nagilum", "nagilum")).getStatusCode(), is(HttpStatus.SC_OK)); // search done // pause2 @@ -438,21 +440,26 @@ public void testSearchScroll() throws Exception { // search HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("nagilum", "nagilum"))).getStatusCode() + is( + (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("nagilum", "nagilum"))) + .getStatusCode() + ) ); int start = res.getBody().indexOf("_scroll_id") + 15; String scrollid = res.getBody().substring(start, res.getBody().indexOf("\"", start + 1)); // search scroll - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "/_search/scroll?pretty=true", - "{\"scroll_id\" : \"" + scrollid + "\"}", - encodeBasicHeader("nagilum", "nagilum") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/_search/scroll?pretty=true", + "{\"scroll_id\" : \"" + scrollid + "\"}", + encodeBasicHeader("nagilum", "nagilum") + )).getStatusCode() + ) ); // search done } diff --git a/src/test/java/org/opensearch/security/UserServiceUnitTests.java b/src/test/java/org/opensearch/security/UserServiceUnitTests.java index f68e1ce380..0cc758eff9 100644 --- a/src/test/java/org/opensearch/security/UserServiceUnitTests.java +++ b/src/test/java/org/opensearch/security/UserServiceUnitTests.java @@ -20,7 +20,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -77,27 +76,27 @@ public void setup() throws Exception { public void testServiceUserTypeFilter() { userService.includeAccountsIfType(config, UserFilterType.SERVICE); - Assert.assertEquals(SERVICE_ACCOUNTS_IN_SETTINGS, config.getCEntries().size()); - Assert.assertEquals(config.getCEntries().containsKey(serviceAccountUsername), true); - Assert.assertEquals(config.getCEntries().containsKey(internalAccountUsername), false); + assertThat(config.getCEntries().size(), is(SERVICE_ACCOUNTS_IN_SETTINGS)); + assertThat(true, is(config.getCEntries().containsKey(serviceAccountUsername))); + assertThat(false, is(config.getCEntries().containsKey(internalAccountUsername))); } @Test public void testInternalUserTypeFilter() { userService.includeAccountsIfType(config, UserFilterType.INTERNAL); - Assert.assertEquals(INTERNAL_ACCOUNTS_IN_SETTINGS, config.getCEntries().size()); - Assert.assertEquals(config.getCEntries().containsKey(serviceAccountUsername), false); - Assert.assertEquals(config.getCEntries().containsKey(internalAccountUsername), true); + assertThat(config.getCEntries().size(), is(INTERNAL_ACCOUNTS_IN_SETTINGS)); + assertThat(false, is(config.getCEntries().containsKey(serviceAccountUsername))); + assertThat(true, is(config.getCEntries().containsKey(internalAccountUsername))); } @Test public void testAnyUserTypeFilter() { userService.includeAccountsIfType(config, UserFilterType.ANY); - Assert.assertEquals(INTERNAL_ACCOUNTS_IN_SETTINGS + SERVICE_ACCOUNTS_IN_SETTINGS, config.getCEntries().size()); - Assert.assertEquals(config.getCEntries().containsKey(serviceAccountUsername), true); - Assert.assertEquals(config.getCEntries().containsKey(internalAccountUsername), true); + assertThat(config.getCEntries().size(), is(INTERNAL_ACCOUNTS_IN_SETTINGS + SERVICE_ACCOUNTS_IN_SETTINGS)); + assertThat(true, is(config.getCEntries().containsKey(serviceAccountUsername))); + assertThat(true, is(config.getCEntries().containsKey(internalAccountUsername))); } private SecurityDynamicConfiguration readConfigFromYml(String file, CType cType) throws Exception { @@ -109,7 +108,7 @@ private SecurityDynamicConfiguration readConfigFromYml(String file, CType cTy int configVersion = 1; if (jsonNode.get("_meta") != null) { - Assert.assertEquals(jsonNode.get("_meta").get("type").asText(), cType.toLCString()); + assertThat(cType.toLCString(), is(jsonNode.get("_meta").get("type").asText())); configVersion = jsonNode.get("_meta").get("config_version").asInt(); } return SecurityDynamicConfiguration.fromNode(jsonNode, cType, configVersion, 0, 0); diff --git a/src/test/java/org/opensearch/security/UtilTests.java b/src/test/java/org/opensearch/security/UtilTests.java index e545cde86f..cb98790632 100644 --- a/src/test/java/org/opensearch/security/UtilTests.java +++ b/src/test/java/org/opensearch/security/UtilTests.java @@ -37,7 +37,8 @@ import org.opensearch.security.support.SecurityUtils; import org.opensearch.security.support.WildcardMatcher; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -113,15 +114,15 @@ public void testWildcardMatchers() { @Test public void testEnvReplace() { Settings settings = Settings.EMPTY; - assertEquals("abv${env.MYENV}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV}xyz", settings)); - assertEquals("abv${envbc.MYENV}xyz", SecurityUtils.replaceEnvVars("abv${envbc.MYENV}xyz", settings)); - assertEquals("abvtTtxyz", SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz", settings)); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV}xyz", settings), is("abv${env.MYENV}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${envbc.MYENV}xyz", settings), is("abv${envbc.MYENV}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz", settings), is("abvtTtxyz")); assertTrue(passwordHasher.check("tTt".toCharArray(), SecurityUtils.replaceEnvVars("${envbc.MYENV:-tTt}", settings))); - assertEquals("abvtTtxyzxxx", SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz${env.MYENV:-xxx}", settings)); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz${env.MYENV:-xxx}", settings), is("abvtTtxyzxxx")); assertTrue(SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz${envbc.MYENV:-xxx}", settings).startsWith("abvtTtxyz$2y$")); - assertEquals("abv${env.MYENV:tTt}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV:tTt}xyz", settings)); - assertEquals("abv${env.MYENV-tTt}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV-tTt}xyz", settings)); - // assertEquals("abvabcdefgxyz", SecurityUtils.replaceEnvVars("abv${envbase64.B64TEST}xyz",settings)); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV:tTt}xyz", settings), is("abv${env.MYENV:tTt}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV-tTt}xyz", settings), is("abv${env.MYENV-tTt}xyz")); + // assertThat(SecurityUtils.replaceEnvVars("abv${envbase64.B64TEST}xyz",settings), is("abvabcdefgxyz")); Map env = System.getenv(); assertTrue(env.size() > 0); @@ -133,14 +134,14 @@ public void testEnvReplace() { if (val == null || val.isEmpty()) { continue; } - assertEquals("abv" + val + "xyz", SecurityUtils.replaceEnvVars("abv${env." + k + "}xyz", settings)); - assertEquals("abv${" + k + "}xyz", SecurityUtils.replaceEnvVars("abv${" + k + "}xyz", settings)); - assertEquals("abv" + val + "xyz", SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings)); - assertEquals( - "abv" + val + "xyzabv" + val + "xyz", - SecurityUtils.replaceEnvVars("abv${env." + k + "}xyzabv${env." + k + "}xyz", settings) + assertThat(SecurityUtils.replaceEnvVars("abv${env." + k + "}xyz", settings), is("abv" + val + "xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${" + k + "}xyz", settings), is("abv${" + k + "}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings), is("abv" + val + "xyz")); + assertThat( + SecurityUtils.replaceEnvVars("abv${env." + k + "}xyzabv${env." + k + "}xyz", settings), + is("abv" + val + "xyzabv" + val + "xyz") ); - assertEquals("abv" + val + "xyz", SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings)); + assertThat(SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings), is("abv" + val + "xyz")); assertTrue(passwordHasher.check(val.toCharArray(), SecurityUtils.replaceEnvVars("${envbc." + k + "}", settings))); checked = true; } @@ -151,33 +152,33 @@ public void testEnvReplace() { @Test public void testNoEnvReplace() { Settings settings = Settings.builder().put(ConfigConstants.SECURITY_DISABLE_ENVVAR_REPLACEMENT, true).build(); - assertEquals("abv${env.MYENV}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV}xyz", settings)); - assertEquals("abv${envbc.MYENV}xyz", SecurityUtils.replaceEnvVars("abv${envbc.MYENV}xyz", settings)); - assertEquals("abv${env.MYENV:-tTt}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz", settings)); - assertEquals( - "abv${env.MYENV:-tTt}xyz${env.MYENV:-xxx}", - SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz${env.MYENV:-xxx}", settings) + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV}xyz", settings), is("abv${env.MYENV}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${envbc.MYENV}xyz", settings), is("abv${envbc.MYENV}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz", settings), is("abv${env.MYENV:-tTt}xyz")); + assertThat( + SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz${env.MYENV:-xxx}", settings), + is("abv${env.MYENV:-tTt}xyz${env.MYENV:-xxx}") ); assertFalse(SecurityUtils.replaceEnvVars("abv${env.MYENV:-tTt}xyz${envbc.MYENV:-xxx}", settings).startsWith("abvtTtxyz$2y$")); - assertEquals("abv${env.MYENV:tTt}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV:tTt}xyz", settings)); - assertEquals("abv${env.MYENV-tTt}xyz", SecurityUtils.replaceEnvVars("abv${env.MYENV-tTt}xyz", settings)); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV:tTt}xyz", settings), is("abv${env.MYENV:tTt}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${env.MYENV-tTt}xyz", settings), is("abv${env.MYENV-tTt}xyz")); Map env = System.getenv(); assertTrue(env.size() > 0); for (String k : env.keySet()) { - assertEquals("abv${env." + k + "}xyz", SecurityUtils.replaceEnvVars("abv${env." + k + "}xyz", settings)); - assertEquals("abv${" + k + "}xyz", SecurityUtils.replaceEnvVars("abv${" + k + "}xyz", settings)); - assertEquals( - "abv${env." + k + ":-k182765ggh}xyz", - SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings) + assertThat(SecurityUtils.replaceEnvVars("abv${env." + k + "}xyz", settings), is("abv${env." + k + "}xyz")); + assertThat(SecurityUtils.replaceEnvVars("abv${" + k + "}xyz", settings), is("abv${" + k + "}xyz")); + assertThat( + SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings), + is("abv${env." + k + ":-k182765ggh}xyz") ); - assertEquals( - "abv${env." + k + "}xyzabv${env." + k + "}xyz", - SecurityUtils.replaceEnvVars("abv${env." + k + "}xyzabv${env." + k + "}xyz", settings) + assertThat( + SecurityUtils.replaceEnvVars("abv${env." + k + "}xyzabv${env." + k + "}xyz", settings), + is("abv${env." + k + "}xyzabv${env." + k + "}xyz") ); - assertEquals( - "abv${env." + k + ":-k182765ggh}xyz", - SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings) + assertThat( + SecurityUtils.replaceEnvVars("abv${env." + k + ":-k182765ggh}xyz", settings), + is("abv${env." + k + ":-k182765ggh}xyz") ); } } diff --git a/src/test/java/org/opensearch/security/auditlog/AuditTestUtils.java b/src/test/java/org/opensearch/security/auditlog/AuditTestUtils.java index ad3f6afbce..a832f9bf82 100644 --- a/src/test/java/org/opensearch/security/auditlog/AuditTestUtils.java +++ b/src/test/java/org/opensearch/security/auditlog/AuditTestUtils.java @@ -27,7 +27,8 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.threadpool.ThreadPool; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class AuditTestUtils { public static void updateAuditConfig(final RestHelper rh, final Settings settings) throws Exception { @@ -40,7 +41,7 @@ public static void updateAuditConfig(final RestHelper rh, final String payload) rh.sendAdminCertificate = true; rh.keystore = "auditlog/kirk-keystore.jks"; RestHelper.HttpResponse response = rh.executePutRequest("_opendistro/_security/api/audit/config", payload); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); rh.sendAdminCertificate = sendAdminCertificate; rh.keystore = keystore; } diff --git a/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java b/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java index 5ba95dc756..e86593a7b0 100644 --- a/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceAuditlogTest.java @@ -44,6 +44,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsEqual.equalTo; @@ -89,7 +90,7 @@ public void testSourceFilter() throws Exception { final AuditMessage message = TestAuditlogImpl.doThenWaitForMessage(() -> { final HttpResponse response = rh.executePostRequest("_search?pretty", search, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); }); assertThat(message.getCategory(), equalTo(AuditCategory.COMPLIANCE_DOC_READ)); @@ -229,7 +230,7 @@ public void testSourceFilterMsearch() throws Exception { final List messages = TestAuditlogImpl.doThenWaitForMessages(() -> { HttpResponse response = rh.executePostRequest("_msearch?pretty", search, encodeBasicHeader("admin", "admin")); assertNotContains(response, "*exception*"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); }, 2); final AuditMessage desginationMsg = messages.stream() @@ -333,7 +334,7 @@ public void testExternalConfig() throws Exception { } final HttpResponse response = rh.executeGetRequest("_search?pretty", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); }, 4); // Record the updated config, and then for each node record that the config was updated @@ -380,7 +381,7 @@ public void testUpdate() throws Exception { body, encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_CREATED)); }); }); assertThat(ex1.getMissingCount(), equalTo(1)); @@ -393,7 +394,7 @@ public void testUpdate() throws Exception { body, encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); }); }); assertThat(ex2.getMissingCount(), equalTo(1)); @@ -427,7 +428,7 @@ public void testWriteHistory() throws Exception { body, encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_CREATED)); }); Assert.assertTrue(TestAuditlogImpl.sb.toString().split(".*audit_compliance_diff_content.*replace.*").length == 1); @@ -438,7 +439,7 @@ public void testWriteHistory() throws Exception { body, encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); }); Assert.assertTrue(TestAuditlogImpl.sb.toString().split(".*audit_compliance_diff_content.*replace.*").length == 1); } diff --git a/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceConfigTest.java b/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceConfigTest.java index 302d26bb00..d503ef3a3e 100644 --- a/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceConfigTest.java +++ b/src/test/java/org/opensearch/security/auditlog/compliance/ComplianceConfigTest.java @@ -31,7 +31,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -57,8 +57,8 @@ public void testDefault() { assertFalse(complianceConfig.shouldLogReadMetadataOnly()); assertFalse(complianceConfig.shouldLogWriteMetadataOnly()); assertFalse(complianceConfig.shouldLogDiffsForWrite()); - assertEquals(defaultIgnoredUserMatcher, complianceConfig.getIgnoredComplianceUsersForReadMatcher()); - assertEquals(defaultIgnoredUserMatcher, complianceConfig.getIgnoredComplianceUsersForWriteMatcher()); + assertThat(complianceConfig.getIgnoredComplianceUsersForReadMatcher(), is(defaultIgnoredUserMatcher)); + assertThat(complianceConfig.getIgnoredComplianceUsersForWriteMatcher(), is(defaultIgnoredUserMatcher)); } @Test @@ -92,13 +92,13 @@ public void testConfig() { assertTrue(complianceConfig.shouldLogReadMetadataOnly()); assertTrue(complianceConfig.shouldLogWriteMetadataOnly()); assertFalse(complianceConfig.shouldLogDiffsForWrite()); - assertEquals( - WildcardMatcher.from(ImmutableSet.of("test-user-1", "test-user-2")), - complianceConfig.getIgnoredComplianceUsersForReadMatcher() + assertThat( + complianceConfig.getIgnoredComplianceUsersForReadMatcher(), + is(WildcardMatcher.from(ImmutableSet.of("test-user-1", "test-user-2"))) ); - assertEquals( - WildcardMatcher.from(ImmutableSet.of("test-user-3", "test-user-4")), - complianceConfig.getIgnoredComplianceUsersForWriteMatcher() + assertThat( + complianceConfig.getIgnoredComplianceUsersForWriteMatcher(), + is(WildcardMatcher.from(ImmutableSet.of("test-user-3", "test-user-4"))) ); // test write history diff --git a/src/test/java/org/opensearch/security/auditlog/compliance/RestApiComplianceAuditlogTest.java b/src/test/java/org/opensearch/security/auditlog/compliance/RestApiComplianceAuditlogTest.java index 784176e1dd..25295a2e05 100644 --- a/src/test/java/org/opensearch/security/auditlog/compliance/RestApiComplianceAuditlogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/compliance/RestApiComplianceAuditlogTest.java @@ -30,6 +30,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; public class RestApiComplianceAuditlogTest extends AbstractAuditlogiUnitTest { @@ -56,7 +57,7 @@ public void testRestApiRolesEnabled() throws Exception { body, encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_CREATED)); }); validateMsgs(List.of(message)); @@ -87,7 +88,7 @@ public void testRestApiRolesDisabled() throws Exception { final AuditMessage message = TestAuditlogImpl.doThenWaitForMessage(() -> { HttpResponse response = rh.executePutRequest("_opendistro/_security/api/internalusers/compuser?pretty", body); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_CREATED)); }); validateMsgs(List.of(message)); assertThat(message.toString(), containsString("COMPLIANCE_INTERNAL_CONFIG_WRITE")); @@ -115,7 +116,7 @@ public void testRestApiRolesDisabledGet() throws Exception { rh.keystore = "kirk-keystore.jks"; final AuditMessage message = TestAuditlogImpl.doThenWaitForMessage(() -> { HttpResponse response = rh.executeGetRequest("_opendistro/_security/api/rolesmapping/opendistro_security_all_access?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); }); validateMsgs(List.of(message)); assertThat(message.toString(), containsString("audit_request_effective_user")); @@ -167,7 +168,7 @@ public void testRestApiNewUser() throws Exception { body, encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(response.getBody(), HttpStatus.SC_CREATED, response.getStatusCode()); + assertThat(response.getBody(), response.getStatusCode(), is(HttpStatus.SC_CREATED)); }); validateMsgs(List.of(message)); assertThat(message.toString(), containsString("audit_request_effective_user")); @@ -199,7 +200,7 @@ public void testRestInternalConfigRead() throws Exception { final AuditMessage message = TestAuditlogImpl.doThenWaitForMessage(() -> { HttpResponse response = rh.executeGetRequest("_opendistro/_security/api/internalusers/admin?pretty"); String auditLogImpl = TestAuditlogImpl.sb.toString(); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(auditLogImpl.contains("COMPLIANCE_INTERNAL_CONFIG_READ")); }); validateMsgs(List.of(message)); diff --git a/src/test/java/org/opensearch/security/auditlog/config/AuditConfigFilterTest.java b/src/test/java/org/opensearch/security/auditlog/config/AuditConfigFilterTest.java index a28d940862..3f0a5a57fc 100644 --- a/src/test/java/org/opensearch/security/auditlog/config/AuditConfigFilterTest.java +++ b/src/test/java/org/opensearch/security/auditlog/config/AuditConfigFilterTest.java @@ -28,13 +28,13 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.auditlog.impl.AuditCategory.AUTHENTICATED; import static org.opensearch.security.auditlog.impl.AuditCategory.BAD_HEADERS; import static org.opensearch.security.auditlog.impl.AuditCategory.FAILED_LOGIN; import static org.opensearch.security.auditlog.impl.AuditCategory.GRANTED_PRIVILEGES; import static org.opensearch.security.auditlog.impl.AuditCategory.MISSING_PRIVILEGES; import static org.opensearch.security.auditlog.impl.AuditCategory.SSL_EXCEPTION; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -56,10 +56,10 @@ public void testDefault() { assertFalse(auditConfigFilter.shouldResolveBulkRequests()); assertTrue(auditConfigFilter.shouldExcludeSensitiveHeaders()); assertSame(WildcardMatcher.NONE, auditConfigFilter.getIgnoredAuditRequestsMatcher()); - assertEquals(defaultIgnoredUserMatcher, auditConfigFilter.getIgnoredAuditUsersMatcher()); + assertThat(auditConfigFilter.getIgnoredAuditUsersMatcher(), is(defaultIgnoredUserMatcher)); assertSame(WildcardMatcher.NONE, auditConfigFilter.getIgnoredCustomHeadersMatcher()); - assertEquals(auditConfigFilter.getDisabledRestCategories(), defaultDisabledCategories); - assertEquals(auditConfigFilter.getDisabledTransportCategories(), defaultDisabledCategories); + assertThat(defaultDisabledCategories, is(auditConfigFilter.getDisabledRestCategories())); + assertThat(defaultDisabledCategories, is(auditConfigFilter.getDisabledTransportCategories())); } @Test @@ -95,11 +95,11 @@ public void testConfig() { assertFalse(auditConfigFilter.shouldResolveIndices()); assertTrue(auditConfigFilter.shouldResolveBulkRequests()); assertFalse(auditConfigFilter.shouldExcludeSensitiveHeaders()); - assertEquals(WildcardMatcher.from(Collections.singleton("test-user")), auditConfigFilter.getIgnoredAuditUsersMatcher()); - assertEquals(WildcardMatcher.from(Collections.singleton("test-request")), auditConfigFilter.getIgnoredAuditRequestsMatcher()); - assertEquals(WildcardMatcher.from(Collections.singleton("test-header")), auditConfigFilter.getIgnoredCustomHeadersMatcher()); - assertEquals(auditConfigFilter.getDisabledRestCategories(), EnumSet.of(BAD_HEADERS, SSL_EXCEPTION)); - assertEquals(auditConfigFilter.getDisabledTransportCategories(), EnumSet.of(FAILED_LOGIN, MISSING_PRIVILEGES)); + assertThat(auditConfigFilter.getIgnoredAuditUsersMatcher(), is(WildcardMatcher.from(Collections.singleton("test-user")))); + assertThat(auditConfigFilter.getIgnoredAuditRequestsMatcher(), is(WildcardMatcher.from(Collections.singleton("test-request")))); + assertThat(auditConfigFilter.getIgnoredCustomHeadersMatcher(), is(WildcardMatcher.from(Collections.singleton("test-header")))); + assertThat(EnumSet.of(BAD_HEADERS, SSL_EXCEPTION), is(auditConfigFilter.getDisabledRestCategories())); + assertThat(EnumSet.of(FAILED_LOGIN, MISSING_PRIVILEGES), is(auditConfigFilter.getDisabledTransportCategories())); } @Test diff --git a/src/test/java/org/opensearch/security/auditlog/config/AuditConfigSerializeTest.java b/src/test/java/org/opensearch/security/auditlog/config/AuditConfigSerializeTest.java index 52cb39f41e..3d4748c7db 100644 --- a/src/test/java/org/opensearch/security/auditlog/config/AuditConfigSerializeTest.java +++ b/src/test/java/org/opensearch/security/auditlog/config/AuditConfigSerializeTest.java @@ -32,9 +32,10 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.support.WildcardMatcher; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.auditlog.impl.AuditCategory.AUTHENTICATED; import static org.opensearch.security.auditlog.impl.AuditCategory.GRANTED_PRIVILEGES; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -100,23 +101,23 @@ public void testDefaultDeserialize() throws IOException { final ComplianceConfig compliance = auditConfig.getCompliance(); // assert assertTrue(audit.isRestApiAuditEnabled()); - assertEquals(audit.getDisabledRestCategories(), EnumSet.of(AuditCategory.AUTHENTICATED, AuditCategory.GRANTED_PRIVILEGES)); + assertThat(audit.getDisabledRestCategories(), is(EnumSet.of(AuditCategory.AUTHENTICATED, AuditCategory.GRANTED_PRIVILEGES))); assertTrue(audit.isTransportApiAuditEnabled()); - assertEquals(audit.getDisabledTransportCategories(), EnumSet.of(AuditCategory.AUTHENTICATED, AuditCategory.GRANTED_PRIVILEGES)); + assertThat(audit.getDisabledTransportCategories(), is(EnumSet.of(AuditCategory.AUTHENTICATED, AuditCategory.GRANTED_PRIVILEGES))); assertFalse(audit.shouldResolveBulkRequests()); assertTrue(audit.shouldLogRequestBody()); assertTrue(audit.shouldResolveIndices()); assertTrue(audit.shouldExcludeSensitiveHeaders()); assertSame(WildcardMatcher.NONE, audit.getIgnoredAuditRequestsMatcher()); - assertEquals(DEFAULT_IGNORED_USER, audit.getIgnoredAuditUsersMatcher()); - assertEquals(WildcardMatcher.NONE, audit.getIgnoredCustomHeadersMatcher()); + assertThat(audit.getIgnoredAuditUsersMatcher(), is(DEFAULT_IGNORED_USER)); + assertThat(audit.getIgnoredCustomHeadersMatcher(), is(WildcardMatcher.NONE)); assertFalse(compliance.shouldLogExternalConfig()); assertFalse(compliance.shouldLogInternalConfig()); assertFalse(compliance.shouldLogReadMetadataOnly()); - assertEquals(DEFAULT_IGNORED_USER, compliance.getIgnoredComplianceUsersForReadMatcher()); + assertThat(compliance.getIgnoredComplianceUsersForReadMatcher(), is(DEFAULT_IGNORED_USER)); assertFalse(compliance.shouldLogWriteMetadataOnly()); assertFalse(compliance.shouldLogDiffsForWrite()); - assertEquals(DEFAULT_IGNORED_USER, compliance.getIgnoredComplianceUsersForWriteMatcher()); + assertThat(compliance.getIgnoredComplianceUsersForWriteMatcher(), is(DEFAULT_IGNORED_USER)); } @Test @@ -160,33 +161,33 @@ public void testDeserialize() throws IOException { final ComplianceConfig configCompliance = auditConfig.getCompliance(); // assert assertTrue(audit.isRestApiAuditEnabled()); - assertEquals(audit.getDisabledRestCategories(), EnumSet.of(AuditCategory.AUTHENTICATED)); + assertThat(EnumSet.of(AuditCategory.AUTHENTICATED), is(audit.getDisabledRestCategories())); assertTrue(audit.isTransportApiAuditEnabled()); - assertEquals(audit.getDisabledTransportCategories(), EnumSet.of(AuditCategory.SSL_EXCEPTION)); + assertThat(EnumSet.of(AuditCategory.SSL_EXCEPTION), is(audit.getDisabledTransportCategories())); assertTrue(audit.shouldResolveBulkRequests()); assertTrue(audit.shouldLogRequestBody()); assertTrue(audit.shouldResolveIndices()); assertTrue(audit.shouldExcludeSensitiveHeaders()); assertTrue(configCompliance.shouldLogExternalConfig()); assertTrue(configCompliance.shouldLogInternalConfig()); - assertEquals(WildcardMatcher.from(Collections.singleton("test-user-1")), audit.getIgnoredAuditUsersMatcher()); - assertEquals(WildcardMatcher.from(Collections.singleton("test-request")), audit.getIgnoredAuditRequestsMatcher()); + assertThat(audit.getIgnoredAuditUsersMatcher(), is(WildcardMatcher.from(Collections.singleton("test-user-1")))); + assertThat(audit.getIgnoredAuditRequestsMatcher(), is(WildcardMatcher.from(Collections.singleton("test-request")))); assertTrue(configCompliance.shouldLogReadMetadataOnly()); - assertEquals( + assertThat( WildcardMatcher.from(Collections.singleton("test-user-2")), - configCompliance.getIgnoredComplianceUsersForReadMatcher() + is(configCompliance.getIgnoredComplianceUsersForReadMatcher()) ); - assertEquals( + assertThat( Collections.singletonMap(WildcardMatcher.from("test-read-watch-field"), Collections.singleton("test-field-1")), - configCompliance.getReadEnabledFields() + is(configCompliance.getReadEnabledFields()) ); assertTrue(configCompliance.shouldLogWriteMetadataOnly()); assertFalse(configCompliance.shouldLogDiffsForWrite()); - assertEquals( + assertThat( WildcardMatcher.from(Collections.singleton("test-user-3")), - configCompliance.getIgnoredComplianceUsersForWriteMatcher() + is(configCompliance.getIgnoredComplianceUsersForWriteMatcher()) ); - assertEquals(WildcardMatcher.from("test-write-watch-index"), configCompliance.getWatchedWriteIndicesMatcher()); + assertThat(configCompliance.getWatchedWriteIndicesMatcher(), is(WildcardMatcher.from("test-write-watch-index"))); } @Test @@ -313,15 +314,15 @@ public void testNullDeSerialize() throws IOException { // assert final AuditConfig.Filter audit = auditConfig.getFilter(); final ComplianceConfig configCompliance = auditConfig.getCompliance(); - assertEquals(audit.getDisabledRestCategories(), EnumSet.of(GRANTED_PRIVILEGES, AUTHENTICATED)); - assertEquals(audit.getDisabledTransportCategories(), EnumSet.of(GRANTED_PRIVILEGES, AUTHENTICATED)); - assertEquals(DEFAULT_IGNORED_USER, audit.getIgnoredAuditUsersMatcher()); - assertEquals(WildcardMatcher.NONE, audit.getIgnoredAuditRequestsMatcher()); - assertEquals(DEFAULT_IGNORED_USER, configCompliance.getIgnoredComplianceUsersForReadMatcher()); - assertEquals(DEFAULT_IGNORED_USER, configCompliance.getIgnoredComplianceUsersForWriteMatcher()); + assertThat(EnumSet.of(AUTHENTICATED, GRANTED_PRIVILEGES), is(audit.getDisabledRestCategories())); + assertThat(EnumSet.of(AUTHENTICATED, GRANTED_PRIVILEGES), is(audit.getDisabledTransportCategories())); + assertThat(audit.getIgnoredAuditUsersMatcher(), is(DEFAULT_IGNORED_USER)); + assertThat(audit.getIgnoredAuditRequestsMatcher(), is(WildcardMatcher.NONE)); + assertThat(configCompliance.getIgnoredComplianceUsersForReadMatcher(), is(DEFAULT_IGNORED_USER)); + assertThat(configCompliance.getIgnoredComplianceUsersForWriteMatcher(), is(DEFAULT_IGNORED_USER)); assertTrue(configCompliance.getReadEnabledFields().isEmpty()); - assertEquals(WildcardMatcher.NONE, configCompliance.getWatchedWriteIndicesMatcher()); - assertEquals(".opendistro_security", configCompliance.getSecurityIndex()); + assertThat(configCompliance.getWatchedWriteIndicesMatcher(), is(WildcardMatcher.NONE)); + assertThat(configCompliance.getSecurityIndex(), is(".opendistro_security")); } @Test @@ -368,16 +369,16 @@ public void testCustomSettings() throws IOException { // assert final AuditConfig.Filter audit = auditConfig.getFilter(); final ComplianceConfig configCompliance = auditConfig.getCompliance(); - assertEquals(audit.getDisabledRestCategories(), EnumSet.of(GRANTED_PRIVILEGES, AUTHENTICATED)); - assertEquals(audit.getDisabledTransportCategories(), EnumSet.of(GRANTED_PRIVILEGES, AUTHENTICATED)); - assertEquals(DEFAULT_IGNORED_USER, audit.getIgnoredAuditUsersMatcher()); - assertEquals(WildcardMatcher.NONE, audit.getIgnoredAuditRequestsMatcher()); - assertEquals(DEFAULT_IGNORED_USER, configCompliance.getIgnoredComplianceUsersForReadMatcher()); - assertEquals(DEFAULT_IGNORED_USER, configCompliance.getIgnoredComplianceUsersForWriteMatcher()); + assertThat(EnumSet.of(AUTHENTICATED, GRANTED_PRIVILEGES), is(audit.getDisabledRestCategories())); + assertThat(EnumSet.of(AUTHENTICATED, GRANTED_PRIVILEGES), is(audit.getDisabledTransportCategories())); + assertThat(audit.getIgnoredAuditUsersMatcher(), is(DEFAULT_IGNORED_USER)); + assertThat(audit.getIgnoredAuditRequestsMatcher(), is(WildcardMatcher.NONE)); + assertThat(configCompliance.getIgnoredComplianceUsersForReadMatcher(), is(DEFAULT_IGNORED_USER)); + assertThat(configCompliance.getIgnoredComplianceUsersForWriteMatcher(), is(DEFAULT_IGNORED_USER)); assertTrue(configCompliance.getReadEnabledFields().isEmpty()); - assertEquals(WildcardMatcher.NONE, configCompliance.getWatchedWriteIndicesMatcher()); - assertEquals("test-security-index", configCompliance.getSecurityIndex()); - assertEquals("test-auditlog-index", configCompliance.getAuditLogIndex()); + assertThat(configCompliance.getWatchedWriteIndicesMatcher(), is(WildcardMatcher.NONE)); + assertThat(configCompliance.getSecurityIndex(), is("test-security-index")); + assertThat(configCompliance.getAuditLogIndex(), is("test-auditlog-index")); } private boolean compareJson(final String json1, final String json2) throws JsonProcessingException { diff --git a/src/test/java/org/opensearch/security/auditlog/config/ThreadPoolConfigTest.java b/src/test/java/org/opensearch/security/auditlog/config/ThreadPoolConfigTest.java index 83c5e9ae2a..d46e895f5f 100644 --- a/src/test/java/org/opensearch/security/auditlog/config/ThreadPoolConfigTest.java +++ b/src/test/java/org/opensearch/security/auditlog/config/ThreadPoolConfigTest.java @@ -17,7 +17,8 @@ import org.opensearch.common.settings.Settings; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class ThreadPoolConfigTest { @@ -66,8 +67,8 @@ public void testConfig() { ThreadPoolConfig config = new ThreadPoolConfig(5, 200); // assert - assertEquals(5, config.getThreadPoolSize()); - assertEquals(200, config.getThreadPoolMaxQueueLen()); + assertThat(config.getThreadPoolSize(), is(5)); + assertThat(config.getThreadPoolMaxQueueLen(), is(200)); } @Test @@ -80,7 +81,7 @@ public void testGenerationFromSettings() { // assert ThreadPoolConfig config = ThreadPoolConfig.getConfig(settings); - assertEquals(8, config.getThreadPoolSize()); - assertEquals(50, config.getThreadPoolMaxQueueLen()); + assertThat(config.getThreadPoolSize(), is(8)); + assertThat(config.getThreadPoolMaxQueueLen(), is(50)); } } diff --git a/src/test/java/org/opensearch/security/auditlog/impl/AuditCategoryTest.java b/src/test/java/org/opensearch/security/auditlog/impl/AuditCategoryTest.java index 18670f42cf..ddd1811ee4 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/AuditCategoryTest.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/AuditCategoryTest.java @@ -17,12 +17,13 @@ import java.util.List; import java.util.Set; -import org.junit.Assert; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.auditlog.impl.AuditCategory.AUTHENTICATED; import static org.opensearch.security.auditlog.impl.AuditCategory.BAD_HEADERS; @@ -73,7 +74,7 @@ public static Collection data() { @Test public void testAuditCategoryEnumSetGenerationWhenEmpty() { Set categories = AuditCategory.parse(input); - Assert.assertEquals(categories, expected); + assertThat(expected, is(categories)); } } diff --git a/src/test/java/org/opensearch/security/auditlog/impl/AuditMessageTest.java b/src/test/java/org/opensearch/security/auditlog/impl/AuditMessageTest.java index 08e4c2ea61..21cd9ce968 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/AuditMessageTest.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/AuditMessageTest.java @@ -38,7 +38,8 @@ import org.opensearch.security.filter.SecurityRequestFactory; import org.opensearch.security.securityconf.impl.CType; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -85,14 +86,14 @@ public void setUp() { public void testAuthorizationRestHeadersAreFiltered() { when(auditConfig.getFilter().shouldExcludeHeader("test-header")).thenReturn(false); message.addRestHeaders(TEST_REST_HEADERS, true, auditConfig.getFilter()); - assertEquals(message.getAsMap().get(AuditMessage.REST_REQUEST_HEADERS), ImmutableMap.of("test-header", ImmutableList.of("test-4"))); + assertThat(message.getAsMap().get(AuditMessage.REST_REQUEST_HEADERS), is(ImmutableMap.of("test-header", ImmutableList.of("test-4")))); } @Test public void testCustomRestHeadersAreFiltered() { when(auditConfig.getFilter().shouldExcludeHeader("test-header")).thenReturn(true); message.addRestHeaders(TEST_REST_HEADERS, true, auditConfig.getFilter()); - assertEquals(message.getAsMap().get(AuditMessage.REST_REQUEST_HEADERS), Map.of()); + assertThat(Map.of(), is(message.getAsMap().get(AuditMessage.REST_REQUEST_HEADERS))); } @Test @@ -107,7 +108,7 @@ public void testRestHeadersNull() { public void testRestHeadersAreNotFiltered() { when(auditConfig.getFilter().shouldExcludeHeader("test-header")).thenReturn(false); message.addRestHeaders(TEST_REST_HEADERS, false, null); - assertEquals(message.getAsMap().get(AuditMessage.REST_REQUEST_HEADERS), TEST_REST_HEADERS); + assertThat(TEST_REST_HEADERS, is(message.getAsMap().get(AuditMessage.REST_REQUEST_HEADERS))); } @Test @@ -121,13 +122,13 @@ public void testTransportHeadersNull() { @Test public void testTransportHeadersAreFiltered() { message.addTransportHeaders(TEST_TRANSPORT_HEADERS, true); - assertEquals(message.getAsMap().get(AuditMessage.TRANSPORT_REQUEST_HEADERS), ImmutableMap.of("test-header", "test-4")); + assertThat(message.getAsMap().get(AuditMessage.TRANSPORT_REQUEST_HEADERS), is(ImmutableMap.of("test-header", "test-4"))); } @Test public void testTransportHeadersAreNotFiltered() { message.addTransportHeaders(TEST_TRANSPORT_HEADERS, false); - assertEquals(message.getAsMap().get(AuditMessage.TRANSPORT_REQUEST_HEADERS), TEST_TRANSPORT_HEADERS); + assertThat(TEST_TRANSPORT_HEADERS, is(message.getAsMap().get(AuditMessage.TRANSPORT_REQUEST_HEADERS))); } @Test @@ -138,29 +139,29 @@ public void testBCryptHashIsRedacted() { // does not perform redaction for non-internal user doc message.addSecurityConfigContentToRequestBody(hash1, "test-doc"); - assertEquals(hash1, message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is(hash1)); // test hash redaction message.addSecurityConfigContentToRequestBody(hash1, internalUsersDocId); - assertEquals("__HASH__", message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is("__HASH__")); // test hash redaction in string message.addSecurityConfigContentToRequestBody("Hash " + hash2 + " is redacted", internalUsersDocId); - assertEquals("Hash __HASH__ is redacted", message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is("Hash __HASH__ is redacted")); // test hash redaction inline without spaces message.addSecurityConfigContentToRequestBody("Inline hash" + hash2 + "is redacted", internalUsersDocId); - assertEquals("Inline hash__HASH__is redacted", message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is("Inline hash__HASH__is redacted")); // test map redaction message.addSecurityConfigWriteDiffSource("Diff is " + hash2, internalUsersDocId); - assertEquals("Diff is __HASH__", message.getAsMap().get(AuditMessage.COMPLIANCE_DIFF_CONTENT)); + assertThat(message.getAsMap().get(AuditMessage.COMPLIANCE_DIFF_CONTENT), is("Diff is __HASH__")); // test tuple redaction final ByteBuffer[] byteBuffers = new ByteBuffer[] { ByteBuffer.wrap(("Hash in tuple is " + hash1).getBytes()) }; BytesReference ref = BytesReference.fromByteBuffers(byteBuffers); message.addSecurityConfigTupleToRequestBody(new Tuple<>(XContentType.JSON, ref), internalUsersDocId); - assertEquals("Hash in tuple is __HASH__", message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is("Hash in tuple is __HASH__")); } @Test @@ -187,7 +188,7 @@ public void testRequestBodyLoggingWithInvalidSourceOrContentTypeParam() { request = SecurityRequestFactory.from(restRequest); message.addRestRequestInfo(request, auditConfig.getFilter()); - assertEquals("ERROR: Unable to generate request body", message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is("ERROR: Unable to generate request body")); // No content, source parameter present but Invalid source-content-type parameter when(httpRequest.uri()).thenReturn("/aaaa?source=request_body"); @@ -197,6 +198,6 @@ public void testRequestBodyLoggingWithInvalidSourceOrContentTypeParam() { request = SecurityRequestFactory.from(restRequest); message.addRestRequestInfo(request, auditConfig.getFilter()); - assertEquals("ERROR: Unable to generate request body", message.getAsMap().get(AuditMessage.REQUEST_BODY)); + assertThat(message.getAsMap().get(AuditMessage.REQUEST_BODY), is("ERROR: Unable to generate request body")); } } diff --git a/src/test/java/org/opensearch/security/auditlog/impl/AuditlogTest.java b/src/test/java/org/opensearch/security/auditlog/impl/AuditlogTest.java index 935fb924a3..80beb3fdfa 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/AuditlogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/AuditlogTest.java @@ -29,6 +29,8 @@ import org.opensearch.security.test.AbstractSecurityUnitTest; import org.opensearch.transport.TransportRequest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -55,7 +57,7 @@ public void testClusterHealthRequest() { AbstractAuditLog al = AuditTestUtils.createAuditLog(settings, null, null, AbstractSecurityUnitTest.MOCK_POOL, null, cs); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", new ClusterHealthRequest(), null); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); } @Test @@ -71,7 +73,7 @@ public void testSearchRequest() { AbstractAuditLog al = AuditTestUtils.createAuditLog(settings, null, null, AbstractSecurityUnitTest.MOCK_POOL, null, cs); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); } @Test @@ -87,7 +89,7 @@ public void testSslException() { TestAuditlogImpl.clear(); al.logSSLException(null, new Exception("test rest")); al.logSSLException(null, new Exception("test rest"), null, null); - Assert.assertEquals(2, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(2)); } @Test diff --git a/src/test/java/org/opensearch/security/auditlog/impl/DelegateTest.java b/src/test/java/org/opensearch/security/auditlog/impl/DelegateTest.java index fa176a2011..5067c80cb8 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/DelegateTest.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/DelegateTest.java @@ -40,7 +40,7 @@ private void testAuditType(String type, Class expectedCl auditLog.close(); // if (expectedClass != null) { // Assert.assertNotNull("delegate is null for type: "+type,auditLog.delegate); - // Assert.assertEquals(expectedClass, auditLog.delegate.getClass()); + // assertThat(auditLog.delegate.getClass(), is(expectedClass)); // } else { // Assert.assertNull(auditLog.delegate); // } diff --git a/src/test/java/org/opensearch/security/auditlog/impl/IgnoreAuditUsersTest.java b/src/test/java/org/opensearch/security/auditlog/impl/IgnoreAuditUsersTest.java index 8e33401c69..47a5a155d2 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/IgnoreAuditUsersTest.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/IgnoreAuditUsersTest.java @@ -13,7 +13,6 @@ import java.net.InetSocketAddress; -import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @@ -30,6 +29,8 @@ import org.opensearch.security.user.User; import org.opensearch.threadpool.ThreadPool; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -78,7 +79,7 @@ public void testConfiguredIgnoreUser() { ); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(0, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(0)); } @Test @@ -99,7 +100,7 @@ public void testNonConfiguredIgnoreUser() { ); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); } @Test @@ -119,7 +120,7 @@ public void testNonExistingIgnoreUser() { ); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); } @Test @@ -159,7 +160,7 @@ public void testWildcards() { ); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(0, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(0)); settings = Settings.builder() .put("plugins.security.audit.type", TestAuditlogImpl.class.getName()) @@ -184,7 +185,7 @@ public void testWildcards() { ); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); settings = Settings.builder() .put("plugins.security.audit.type", TestAuditlogImpl.class.getName()) @@ -211,7 +212,7 @@ public void testWildcards() { al.logGrantedPrivileges("indices:data/read/search", sr, null); al.logSecurityIndexAttempt(sr, "indices:data/read/search", null); al.logMissingPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(TestAuditlogImpl.messages.toString(), 0, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.toString(), TestAuditlogImpl.messages.size(), is(0)); settings = Settings.builder() .put("plugins.security.audit.type", TestAuditlogImpl.class.getName()) @@ -236,7 +237,7 @@ public void testWildcards() { ); TestAuditlogImpl.clear(); al.logGrantedPrivileges("indices:data/read/search", sr, null); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); } private static ThreadPool newThreadPool(Object... transients) { diff --git a/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java b/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java index 796c73b811..9853581960 100644 --- a/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java +++ b/src/test/java/org/opensearch/security/auditlog/impl/TracingTests.java @@ -32,6 +32,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class TracingTests extends SingleClusterTest { @Override @@ -282,7 +285,7 @@ public void testHTTPSingle() throws Exception { // end pause1 // search - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("_search", encodeBasicHeader("admin", "admin")).getStatusCode()); + assertThat(rh.executeGetRequest("_search", encodeBasicHeader("admin", "admin")).getStatusCode(), is(HttpStatus.SC_OK)); // search done // pause2 @@ -331,21 +334,23 @@ public void testSearchScroll() throws Exception { // search HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); int start = res.getBody().indexOf("_scroll_id") + 15; String scrollid = res.getBody().substring(start, res.getBody().indexOf("\"", start + 1)); // search scroll - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "/_search/scroll?pretty=true", - "{\"scroll_id\" : \"" + scrollid + "\"}", - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/_search/scroll?pretty=true", + "{\"scroll_id\" : \"" + scrollid + "\"}", + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); // search done @@ -452,27 +457,27 @@ public void testImmutableIndex() throws Exception { String data1 = FileHelper.loadFile("auditlog/data1.json"); String data2 = FileHelper.loadFile("auditlog/data1mod.json"); HttpResponse res = rh.executePutRequest("myindex1/_doc/1?refresh", data1, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(201, res.getStatusCode()); + assertThat(res.getStatusCode(), is(201)); res = rh.executePutRequest("myindex1/_doc/1?refresh", data2, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(409, res.getStatusCode()); + assertThat(res.getStatusCode(), is(409)); res = rh.executeDeleteRequest("myindex1/_doc/1?refresh", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(403, res.getStatusCode()); + assertThat(res.getStatusCode(), is(403)); res = rh.executeGetRequest("myindex1/_doc/1", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(200, res.getStatusCode()); + assertThat(res.getStatusCode(), is(200)); Assert.assertFalse(res.getBody().contains("city")); Assert.assertTrue(res.getBody().contains("\"found\":true,")); // immutable 2 res = rh.executePutRequest("myindex2/_doc/1?refresh", data1, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(201, res.getStatusCode()); + assertThat(res.getStatusCode(), is(201)); res = rh.executePutRequest("myindex2/_doc/1?refresh", data2, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(200, res.getStatusCode()); + assertThat(res.getStatusCode(), is(200)); res = rh.executeGetRequest("myindex2/_doc/1", encodeBasicHeader("admin", "admin")); Assert.assertTrue(res.getBody().contains("city")); res = rh.executeDeleteRequest("myindex2/_doc/1?refresh", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(200, res.getStatusCode()); + assertThat(res.getStatusCode(), is(200)); res = rh.executeGetRequest("myindex2/_doc/1", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(404, res.getStatusCode()); + assertThat(res.getStatusCode(), is(404)); } } diff --git a/src/test/java/org/opensearch/security/auditlog/integration/BasicAuditlogTest.java b/src/test/java/org/opensearch/security/auditlog/integration/BasicAuditlogTest.java index c4784d14b8..5420793789 100644 --- a/src/test/java/org/opensearch/security/auditlog/integration/BasicAuditlogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/integration/BasicAuditlogTest.java @@ -43,6 +43,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.rest.RestRequest.Method.DELETE; import static org.opensearch.rest.RestRequest.Method.GET; import static org.opensearch.rest.RestRequest.Method.PATCH; @@ -85,7 +86,7 @@ public void testAuditLogEnable() throws Exception { // assert no auditing TestAuditlogImpl.clear(); rh.executeGetRequest("_search", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(0, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(0)); } @Test @@ -141,12 +142,12 @@ public void testSSLPlainText() throws Exception { RuntimeException.class, () -> nonSslRestHelper().executeGetRequest("_search", encodeBasicHeader("admin", "admin")) ); - Assert.assertEquals("org.apache.hc.core5.http.NoHttpResponseException", ex.getCause().getClass().getName()); + assertThat(ex.getCause().getClass().getName(), is("org.apache.hc.core5.http.NoHttpResponseException")); }, 1); /* no retry on NotSslRecordException exceptions */ // All of the messages should be the same as the http client is attempting multiple times. messages.stream().forEach((message) -> { - Assert.assertEquals(AuditCategory.SSL_EXCEPTION, message.getCategory()); + assertThat(message.getCategory(), is(AuditCategory.SSL_EXCEPTION)); Assert.assertTrue(message.getExceptionStackTrace().contains("not an SSL/TLS record")); }); validateMsgs(messages); @@ -166,7 +167,7 @@ public void testTaskId() throws Exception { TestAuditlogImpl.clear(); HttpResponse response = rh.executeGetRequest("_search", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Thread.sleep(1500); String auditLogImpl = TestAuditlogImpl.sb.toString(); @@ -178,9 +179,9 @@ public void testTaskId() throws Exception { Assert.assertTrue(auditLogImpl.contains("\"audit_request_effective_user\" : \"admin\"")); Assert.assertTrue(auditLogImpl.contains("REST")); Assert.assertFalse(auditLogImpl.toLowerCase().contains("authorization")); - Assert.assertEquals( + assertThat( TestAuditlogImpl.messages.get(1).getAsMap().get(AuditMessage.TASK_ID), - TestAuditlogImpl.messages.get(1).getAsMap().get(AuditMessage.TASK_ID) + is(TestAuditlogImpl.messages.get(1).getAsMap().get(AuditMessage.TASK_ID)) ); validateMsgs(TestAuditlogImpl.messages); } @@ -199,11 +200,11 @@ public void testDefaultsRest() throws Exception { TestAuditlogImpl.clear(); HttpResponse response = rh.executeGetRequest("_search", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Thread.sleep(1500); String auditLogImpl = TestAuditlogImpl.sb.toString(); - Assert.assertEquals(2, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(2)); Assert.assertTrue(auditLogImpl.contains("GRANTED_PRIVILEGES")); Assert.assertTrue(auditLogImpl.contains("AUTHENTICATED")); Assert.assertTrue(auditLogImpl.contains("indices:data/read/search")); @@ -245,9 +246,9 @@ public void testMissingPrivilegesRest() throws Exception { private void testPrivilegeRest(final int expectedStatus, final String endpoint, final AuditCategory category) throws Exception { TestAuditlogImpl.clear(); final HttpResponse response = rh.executeGetRequest(endpoint, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); final String auditlog = TestAuditlogImpl.sb.toString(); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); Assert.assertTrue(auditlog.contains("\"audit_category\" : \"" + category + "\"")); Assert.assertTrue(auditlog.contains("\"audit_rest_request_path\" : \"" + endpoint + "\"")); Assert.assertTrue(auditlog.contains("\"audit_request_effective_user\" : \"admin\"")); @@ -310,25 +311,25 @@ public void testNonAuthenticated() throws Exception { public void testWrongUser() throws Exception { HttpResponse response = rh.executeGetRequest("", encodeBasicHeader("wronguser", "admin")); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); Thread.sleep(500); Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("FAILED_LOGIN")); Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("wronguser")); Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertFalse(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("AUTHENTICATED")); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); validateMsgs(TestAuditlogImpl.messages); } public void testUnknownAuthorization() throws Exception { HttpResponse response = rh.executeGetRequest("", encodeBasicHeader("unknown", "unknown")); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("FAILED_LOGIN")); Assert.assertFalse(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("Basic dW5rbm93bjp1bmtub3du")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertFalse(TestAuditlogImpl.sb.toString().contains("AUTHENTICATED")); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); validateMsgs(TestAuditlogImpl.messages); } @@ -336,9 +337,9 @@ public void testUnauthenticated() throws Exception { /// testUnauthenticated HttpResponse response = rh.executeGetRequest("_search"); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); Thread.sleep(1500); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertTrue(auditLogImpl.contains("FAILED_LOGIN")); Assert.assertTrue(auditLogImpl.contains("")); @@ -351,21 +352,21 @@ public void testUnauthenticated() throws Exception { public void testJustAuthenticated() throws Exception { HttpResponse response = rh.executeGetRequest("", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertEquals(0, TestAuditlogImpl.messages.size()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(TestAuditlogImpl.messages.size(), is(0)); validateMsgs(TestAuditlogImpl.messages); } public void testSecurityIndexAttempt() throws Exception { HttpResponse response = rh.executePutRequest(".opendistro_security/_doc/0", "{}", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("MISSING_PRIVILEGES")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("OPENDISTRO_SECURITY_INDEX_ATTEMPT")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("admin")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertFalse(TestAuditlogImpl.sb.toString().contains("AUTHENTICATED")); - Assert.assertEquals(2, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(2)); validateMsgs(TestAuditlogImpl.messages); } @@ -376,25 +377,25 @@ public void testBadHeader() throws Exception { new BasicHeader("_opendistro_security_bad", "bad"), encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertFalse(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("AUTHENTICATED")); Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("BAD_HEADERS")); Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("_opendistro_security_bad")); - Assert.assertEquals(TestAuditlogImpl.sb.toString(), 1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.messages.size(), is(1)); validateMsgs(TestAuditlogImpl.messages); } public void testMissingPriv() throws Exception { HttpResponse response = rh.executeGetRequest("sf/_search", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("MISSING_PRIVILEGES")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("indices:data/read/search")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("worf")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("\"sf\"")); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertFalse(TestAuditlogImpl.sb.toString().contains("AUTHENTICATED")); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); validateMsgs(TestAuditlogImpl.messages); } @@ -411,13 +412,13 @@ public void testMsearch() throws Exception { // msaerch HttpResponse response = rh.executePostRequest("_msearch?pretty", msearch, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(response.getStatusReason(), HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusReason(), response.getStatusCode(), is(HttpStatus.SC_OK)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertTrue(auditLogImpl, auditLogImpl.contains("indices:data/read/msearch")); Assert.assertTrue(auditLogImpl, auditLogImpl.contains("indices:data/read/search")); Assert.assertTrue(auditLogImpl, auditLogImpl.contains("match_all")); Assert.assertTrue(auditLogImpl.contains("audit_trace_task_id")); - Assert.assertEquals(auditLogImpl, 4, TestAuditlogImpl.messages.size()); + assertThat(auditLogImpl, TestAuditlogImpl.messages.size(), is(4)); Assert.assertFalse(auditLogImpl.toLowerCase().contains("authorization")); validateMsgs(TestAuditlogImpl.messages); } @@ -447,7 +448,7 @@ public void testBulkAuth() throws Exception { + System.lineSeparator(); HttpResponse response = rh.executePostRequest("_bulk", bulkBody, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"errors\":false")); Assert.assertTrue(response.getBody().contains("\"status\":201")); String auditLogImpl = TestAuditlogImpl.sb.toString(); @@ -486,7 +487,7 @@ public void testBulkNonAuth() throws Exception { HttpResponse response = rh.executePostRequest("_bulk", bulkBody, encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("\"errors\":true")); Assert.assertTrue(response.getBody().contains("\"status\":200")); Assert.assertTrue(response.getBody().contains("\"status\":403")); @@ -514,7 +515,7 @@ public void testUpdateSettings() throws Exception { "{\\\"persistent_settings\\\":{\\\"indices\\\":{\\\"recovery\\\":{\\\"*\\\":null}}},\\\"transient_settings\\\":{\\\"indices\\\":{\\\"recovery\\\":{\\\"*\\\":null}}}}"; HttpResponse response = rh.executePutRequest("_cluster/settings", json, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertTrue(auditLogImpl.contains("AUTHENTICATED")); Assert.assertTrue(auditLogImpl.contains("cluster:admin/settings/update")); @@ -613,13 +614,13 @@ public void testAliases() throws Exception { TestAuditlogImpl.clear(); HttpResponse response = rh.executeGetRequest("sf/_search?pretty", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertTrue(auditLogImpl.contains("starfleet_academy")); Assert.assertTrue(auditLogImpl.contains("starfleet_library")); Assert.assertTrue(auditLogImpl.contains("starfleet")); Assert.assertTrue(auditLogImpl.contains("sf")); - Assert.assertEquals(2, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(2)); validateMsgs(TestAuditlogImpl.messages); } @@ -646,36 +647,40 @@ public void testScroll() throws Exception { TestAuditlogImpl.clear(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); int start = res.getBody().indexOf("_scroll_id") + 15; String scrollid = res.getBody().substring(start, res.getBody().indexOf("\"", start + 1)); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "/_search/scroll?pretty=true", - "{\"scroll_id\" : \"" + scrollid + "\"}", - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/_search/scroll?pretty=true", + "{\"scroll_id\" : \"" + scrollid + "\"}", + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); - Assert.assertEquals(4, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(4)); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("vulcangov/_search?scroll=1m&pretty=true", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); start = res.getBody().indexOf("_scroll_id") + 15; scrollid = res.getBody().substring(start, res.getBody().indexOf("\"", start + 1)); TestAuditlogImpl.clear(); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (res = rh.executePostRequest( - "/_search/scroll?pretty=true", - "{\"scroll_id\" : \"" + scrollid + "\"}", - encodeBasicHeader("admin2", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/_search/scroll?pretty=true", + "{\"scroll_id\" : \"" + scrollid + "\"}", + encodeBasicHeader("admin2", "admin") + )).getStatusCode() + ) ); Thread.sleep(1000); String auditLogImpl = TestAuditlogImpl.sb.toString(); @@ -712,12 +717,12 @@ public void testAliasResolution() throws Exception { TestAuditlogImpl.clear(); HttpResponse response = rh.executeGetRequest("thealias/_search?pretty", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertTrue(auditLogImpl.contains("thealias")); Assert.assertTrue(auditLogImpl.contains("audit_trace_resolved_indices")); Assert.assertTrue(auditLogImpl.contains("vulcangov")); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); validateMsgs(TestAuditlogImpl.messages); TestAuditlogImpl.clear(); } @@ -741,12 +746,12 @@ public void testAliasBadHeaders() throws Exception { new BasicHeader("_opendistro_security_user", "xxx"), encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertFalse(auditLogImpl.contains("YWRtaW46YWRtaW4")); Assert.assertTrue(auditLogImpl.contains("BAD_HEADERS")); Assert.assertTrue(auditLogImpl.contains("xxx")); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); validateMsgs(TestAuditlogImpl.messages); TestAuditlogImpl.clear(); } @@ -773,9 +778,9 @@ public void testIndexCloseDelete() throws Exception { TestAuditlogImpl.clear(); HttpResponse response = rh.executeDeleteRequest("index1?pretty", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePostRequest("index2/_close?pretty", "", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); String auditLogImpl = TestAuditlogImpl.sb.toString(); Assert.assertTrue(auditLogImpl.contains("indices:admin/close")); Assert.assertTrue(auditLogImpl.contains("indices:admin/delete")); @@ -806,13 +811,15 @@ public void testDeleteByQuery() throws Exception { TestAuditlogImpl.clear(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "/vulcango*/_delete_by_query?refresh=true&wait_for_completion=true&pretty=true", - "{\"query\" : {\"match_all\" : {}}}", - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/vulcango*/_delete_by_query?refresh=true&wait_for_completion=true&pretty=true", + "{\"query\" : {\"match_all\" : {}}}", + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); assertContains(res, "*\"deleted\" : 3,*"); String auditlogContents = TestAuditlogImpl.sb.toString(); @@ -894,23 +901,23 @@ public void testRestMethod() throws Exception { // test GET messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executeGetRequest("test", adminHeader); }, 1); - Assert.assertEquals(GET, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getRequestMethod(), is(GET)); // test PUT messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executePutRequest("test/_doc/0", "{}", adminHeader); }, 1); - Assert.assertEquals(PUT, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getRequestMethod(), is(PUT)); // test DELETE messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executeDeleteRequest("test", adminHeader); }, 1); - Assert.assertEquals(DELETE, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getRequestMethod(), is(DELETE)); // test POST messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executePostRequest("test/_doc", "{}", adminHeader); }, 1); - Assert.assertEquals(POST, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getRequestMethod(), is(POST)); // test PATCH messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executePatchRequest("/_opendistro/_security/api/audit", "[]"); }, 1); - Assert.assertEquals(PATCH, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getRequestMethod(), is(PATCH)); // test MISSING_PRIVILEGES // admin does not have REST role here @@ -919,31 +926,31 @@ public void testRestMethod() throws Exception { 2 ); // The intital request is authenicated - Assert.assertEquals(PATCH, messages.get(0).getRequestMethod()); - Assert.assertEquals(AuditCategory.AUTHENTICATED, messages.get(0).getCategory()); + assertThat(messages.get(0).getRequestMethod(), is(PATCH)); + assertThat(messages.get(0).getCategory(), is(AuditCategory.AUTHENTICATED)); // The secondary request does not have permissions - Assert.assertEquals(PATCH, messages.get(1).getRequestMethod()); - Assert.assertEquals(AuditCategory.MISSING_PRIVILEGES, messages.get(1).getCategory()); + assertThat(messages.get(1).getRequestMethod(), is(PATCH)); + assertThat(messages.get(1).getCategory(), is(AuditCategory.MISSING_PRIVILEGES)); // test AUTHENTICATED messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executeGetRequest("test", adminHeader); }, 1); - Assert.assertEquals(AuditCategory.AUTHENTICATED, messages.get(0).getCategory()); - Assert.assertEquals(GET, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getCategory(), is(AuditCategory.AUTHENTICATED)); + assertThat(messages.get(0).getRequestMethod(), is(GET)); // test FAILED_LOGIN messages = TestAuditlogImpl.doThenWaitForMessages( () -> { rh.executeGetRequest("test", encodeBasicHeader("random", "random")); }, 1 ); - Assert.assertEquals(AuditCategory.FAILED_LOGIN, messages.get(0).getCategory()); - Assert.assertEquals(GET, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getCategory(), is(AuditCategory.FAILED_LOGIN)); + assertThat(messages.get(0).getRequestMethod(), is(GET)); // test BAD_HEADERS messages = TestAuditlogImpl.doThenWaitForMessages(() -> { rh.executeGetRequest("test", new BasicHeader("_opendistro_security_user", "xxx")); }, 1); - Assert.assertEquals(AuditCategory.BAD_HEADERS, messages.get(0).getCategory()); - Assert.assertEquals(GET, messages.get(0).getRequestMethod()); + assertThat(messages.get(0).getCategory(), is(AuditCategory.BAD_HEADERS)); + assertThat(messages.get(0).getRequestMethod(), is(GET)); } @Test @@ -961,7 +968,7 @@ public void testSensitiveMethodRedaction() throws Exception { // test PUT accounts API TestAuditlogImpl.clear(); rh.executePutRequest("/_opendistro/_security/api/account", "{\"password\":\"new-pass\", \"current_password\":\"curr-passs\"}"); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(expectedRequestBody)); // test PUT internal users API @@ -970,7 +977,7 @@ public void testSensitiveMethodRedaction() throws Exception { "/_opendistro/_security/api/internalusers/test1", "{\"password\":\"new-pass\", \"backend_roles\":[], \"attributes\": {}}" ); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(expectedRequestBody)); // test PATCH internal users API @@ -979,7 +986,7 @@ public void testSensitiveMethodRedaction() throws Exception { "/_opendistro/_security/api/internalusers/test1", "[{\"op\":\"add\", \"path\":\"/password\", \"value\": \"test-pass\"}]" ); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(expectedRequestBody)); // test PUT users API @@ -988,7 +995,7 @@ public void testSensitiveMethodRedaction() throws Exception { "/_opendistro/_security/api/user/test2", "{\"password\":\"new-pass\", \"backend_roles\":[], \"attributes\": {}}" ); - Assert.assertEquals(1, TestAuditlogImpl.messages.size()); + assertThat(TestAuditlogImpl.messages.size(), is(1)); Assert.assertTrue(TestAuditlogImpl.sb.toString().contains(expectedRequestBody)); } } diff --git a/src/test/java/org/opensearch/security/auditlog/integration/SSLAuditlogTest.java b/src/test/java/org/opensearch/security/auditlog/integration/SSLAuditlogTest.java index 0b92c952f6..62af705ebb 100644 --- a/src/test/java/org/opensearch/security/auditlog/integration/SSLAuditlogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/integration/SSLAuditlogTest.java @@ -27,6 +27,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SSLAuditlogTest extends AbstractAuditlogiUnitTest { private ClusterInfo monitoringClusterInfo; @@ -100,12 +103,12 @@ public void testExternalPemUserPass() throws Exception { setup(additionalSettings); HttpResponse response = rh.executeGetRequest("_search"); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); Thread.sleep(5000); response = rhMon.executeGetRequest("security-auditlog*/_refresh", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rhMon.executeGetRequest("security-auditlog*/_search", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); assertNotContains(response, "*\"hits\":{\"total\":0,*"); assertContains(response, "*\"failed\":0},\"hits\":*"); } @@ -144,12 +147,12 @@ public void testExternalPemClientAuth() throws Exception { setup(additionalSettings); HttpResponse response = rh.executeGetRequest("_search"); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); Thread.sleep(5000); response = rhMon.executeGetRequest("security-auditlog*/_refresh", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rhMon.executeGetRequest("security-auditlog*/_search", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); assertNotContains(response, "*\"hits\":{\"total\":0,*"); assertContains(response, "*\"failed\":0},\"hits\":*"); } @@ -183,12 +186,12 @@ public void testExternalPemUserPassTp() throws Exception { setup(additionalSettings); HttpResponse response = rh.executeGetRequest("_search"); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); Thread.sleep(5000); response = rhMon.executeGetRequest("security-auditlog*/_refresh", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rhMon.executeGetRequest("security-auditlog-*/_search", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); assertNotContains(response, "*\"hits\":{\"total\":0,*"); assertContains(response, "*\"failed\":0},\"hits\":*"); } diff --git a/src/test/java/org/opensearch/security/auditlog/routing/FallbackTest.java b/src/test/java/org/opensearch/security/auditlog/routing/FallbackTest.java index cf76dbc343..3f6de88dfd 100644 --- a/src/test/java/org/opensearch/security/auditlog/routing/FallbackTest.java +++ b/src/test/java/org/opensearch/security/auditlog/routing/FallbackTest.java @@ -30,6 +30,9 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FallbackTest extends AbstractAuditlogiUnitTest { @Test @@ -48,28 +51,28 @@ public void testFallback() throws Exception { // endpoint 1 is failing, endoint2 and default work List sinks = router.categorySinks.get(AuditCategory.MISSING_PRIVILEGES); - Assert.assertEquals(3, sinks.size()); + assertThat(sinks.size(), is(3)); // this sink has failed, message must be logged to fallback sink AuditLogSink sink = sinks.get(0); - Assert.assertEquals("endpoint1", sink.getName()); - Assert.assertEquals(FailingSink.class, sink.getClass()); + assertThat(sink.getName(), is("endpoint1")); + assertThat(sink.getClass(), is(FailingSink.class)); sink = sink.getFallbackSink(); - Assert.assertEquals("fallback", sink.getName()); - Assert.assertEquals(LoggingSink.class, sink.getClass()); + assertThat(sink.getName(), is("fallback")); + assertThat(sink.getClass(), is(LoggingSink.class)); LoggingSink loggingSkin = (LoggingSink) sink; - Assert.assertEquals(msg, loggingSkin.messages.get(0)); + assertThat(loggingSkin.messages.get(0), is(msg)); // this sink succeeds sink = sinks.get(1); - Assert.assertEquals("endpoint2", sink.getName()); - Assert.assertEquals(LoggingSink.class, sink.getClass()); + assertThat(sink.getName(), is("endpoint2")); + assertThat(sink.getClass(), is(LoggingSink.class)); loggingSkin = (LoggingSink) sink; - Assert.assertEquals(msg, loggingSkin.messages.get(0)); + assertThat(loggingSkin.messages.get(0), is(msg)); // default sink also succeeds sink = sinks.get(2); - Assert.assertEquals("default", sink.getName()); - Assert.assertEquals(LoggingSink.class, sink.getClass()); + assertThat(sink.getName(), is("default")); + assertThat(sink.getClass(), is(LoggingSink.class)); loggingSkin = (LoggingSink) sink; - Assert.assertEquals(msg, loggingSkin.messages.get(0)); + assertThat(loggingSkin.messages.get(0), is(msg)); // has only one end point which fails router = createMessageRouterComplianceEnabled(settings); @@ -77,13 +80,13 @@ public void testFallback() throws Exception { router.route(msg); sinks = router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_READ); sink = sinks.get(0); - Assert.assertEquals("endpoint3", sink.getName()); - Assert.assertEquals(FailingSink.class, sink.getClass()); + assertThat(sink.getName(), is("endpoint3")); + assertThat(sink.getClass(), is(FailingSink.class)); sink = sink.getFallbackSink(); - Assert.assertEquals("fallback", sink.getName()); - Assert.assertEquals(LoggingSink.class, sink.getClass()); + assertThat(sink.getName(), is("fallback")); + assertThat(sink.getClass(), is(LoggingSink.class)); loggingSkin = (LoggingSink) sink; - Assert.assertEquals(msg, loggingSkin.messages.get(0)); + assertThat(loggingSkin.messages.get(0), is(msg)); // has only default which succeeds router = createMessageRouterComplianceEnabled(settings); @@ -91,17 +94,17 @@ public void testFallback() throws Exception { router.route(msg); sinks = router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_WRITE); sink = sinks.get(0); - Assert.assertEquals("default", sink.getName()); - Assert.assertEquals(LoggingSink.class, sink.getClass()); + assertThat(sink.getName(), is("default")); + assertThat(sink.getClass(), is(LoggingSink.class)); loggingSkin = (LoggingSink) sink; - Assert.assertEquals(1, loggingSkin.messages.size()); - Assert.assertEquals(msg, loggingSkin.messages.get(0)); + assertThat(loggingSkin.messages.size(), is(1)); + assertThat(loggingSkin.messages.get(0), is(msg)); // fallback must be empty sink = sink.getFallbackSink(); - Assert.assertEquals("fallback", sink.getName()); - Assert.assertEquals(LoggingSink.class, sink.getClass()); + assertThat(sink.getName(), is("fallback")); + assertThat(sink.getClass(), is(LoggingSink.class)); loggingSkin = (LoggingSink) sink; - Assert.assertEquals(0, loggingSkin.messages.size()); + assertThat(loggingSkin.messages.size(), is(0)); // test non configured categories, must be logged to default only router = createMessageRouterComplianceEnabled(settings); @@ -109,8 +112,8 @@ public void testFallback() throws Exception { router.route(msg); Assert.assertNull(router.categorySinks.get(AuditCategory.FAILED_LOGIN)); loggingSkin = (LoggingSink) router.defaultSink; - Assert.assertEquals(1, loggingSkin.messages.size()); - Assert.assertEquals(msg, loggingSkin.messages.get(0)); + assertThat(loggingSkin.messages.size(), is(1)); + assertThat(loggingSkin.messages.get(0), is(msg)); // all others must be empty assertLoggingSinksEmpty(router); @@ -123,7 +126,7 @@ private void assertLoggingSinksEmpty(AuditMessageRouter router) { allSinks.removeAll(Collections.singleton(router.defaultSink)); for (AuditLogSink sink : allSinks) { LoggingSink loggingSink = (LoggingSink) sink; - Assert.assertEquals(0, loggingSink.messages.size()); + assertThat(loggingSink.messages.size(), is(0)); } } diff --git a/src/test/java/org/opensearch/security/auditlog/routing/RouterTest.java b/src/test/java/org/opensearch/security/auditlog/routing/RouterTest.java index 9ab7c0f93c..b217c9513a 100644 --- a/src/test/java/org/opensearch/security/auditlog/routing/RouterTest.java +++ b/src/test/java/org/opensearch/security/auditlog/routing/RouterTest.java @@ -31,6 +31,9 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class RouterTest extends AbstractAuditlogiUnitTest { @Test @@ -40,24 +43,24 @@ public void testValidConfiguration() throws Exception { .build(); AuditMessageRouter router = createMessageRouterComplianceEnabled(settings); // default - Assert.assertEquals("default", router.defaultSink.getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, router.defaultSink.getClass()); + assertThat(router.defaultSink.getName(), is("default")); + assertThat(router.defaultSink.getClass(), is(ExternalOpenSearchSink.class)); // test category sinks List sinks = router.categorySinks.get(AuditCategory.MISSING_PRIVILEGES); Assert.assertNotNull(sinks); // 3, since we include default as well - Assert.assertEquals(3, sinks.size()); - Assert.assertEquals("endpoint1", sinks.get(0).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(0).getClass()); - Assert.assertEquals("endpoint2", sinks.get(1).getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, sinks.get(1).getClass()); - Assert.assertEquals("default", sinks.get(2).getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, sinks.get(2).getClass()); + assertThat(sinks.size(), is(3)); + assertThat(sinks.get(0).getName(), is("endpoint1")); + assertThat(sinks.get(0).getClass(), is(InternalOpenSearchSink.class)); + assertThat(sinks.get(1).getName(), is("endpoint2")); + assertThat(sinks.get(1).getClass(), is(ExternalOpenSearchSink.class)); + assertThat(sinks.get(2).getName(), is("default")); + assertThat(sinks.get(2).getClass(), is(ExternalOpenSearchSink.class)); sinks = router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_READ); // 1, since we do not include default - Assert.assertEquals(1, sinks.size()); - Assert.assertEquals("endpoint3", sinks.get(0).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(0).getClass()); + assertThat(sinks.size(), is(1)); + assertThat(sinks.get(0).getName(), is("endpoint3")); + assertThat(sinks.get(0).getClass(), is(DebugSink.class)); } @Test @@ -113,8 +116,8 @@ private void testMessageDeliveredForCategory( // each sink must contain our message for (AuditLogSink sink : sinks) { LoggingSink logSink = (LoggingSink) sink; - Assert.assertEquals(1, logSink.messages.size()); - Assert.assertEquals(msg, logSink.messages.get(0)); + assertThat(logSink.messages.size(), is(1)); + assertThat(logSink.messages.get(0), is(msg)); Assert.assertTrue(logSink.sb.length() > 0); Assert.assertTrue(Arrays.stream(sinkNames).anyMatch(sink.getName()::equals)); } @@ -126,7 +129,7 @@ private void testMessageDeliveredForCategory( continue; } LoggingSink logSink = (LoggingSink) sink; - Assert.assertEquals(0, logSink.messages.size()); + assertThat(logSink.messages.size(), is(0)); Assert.assertTrue(logSink.sb.length() == 0); } } diff --git a/src/test/java/org/opensearch/security/auditlog/routing/RoutingConfigurationTest.java b/src/test/java/org/opensearch/security/auditlog/routing/RoutingConfigurationTest.java index 8ddb79bcba..bf60369afc 100644 --- a/src/test/java/org/opensearch/security/auditlog/routing/RoutingConfigurationTest.java +++ b/src/test/java/org/opensearch/security/auditlog/routing/RoutingConfigurationTest.java @@ -28,6 +28,10 @@ import org.opensearch.security.auditlog.sink.InternalOpenSearchSink; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; + public class RoutingConfigurationTest extends AbstractAuditlogiUnitTest { @Test @@ -37,24 +41,24 @@ public void testValidConfiguration() throws Exception { .build(); AuditMessageRouter router = createMessageRouterComplianceEnabled(settings); // default - Assert.assertEquals("default", router.defaultSink.getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, router.defaultSink.getClass()); + assertThat(router.defaultSink.getName(), is("default")); + assertThat(router.defaultSink.getClass(), is(ExternalOpenSearchSink.class)); // test category sinks List sinks = router.categorySinks.get(AuditCategory.MISSING_PRIVILEGES); Assert.assertNotNull(sinks); // 3, since we include default as well - Assert.assertEquals(3, sinks.size()); - Assert.assertEquals("endpoint1", sinks.get(0).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(0).getClass()); - Assert.assertEquals("endpoint2", sinks.get(1).getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, sinks.get(1).getClass()); - Assert.assertEquals("default", sinks.get(2).getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, sinks.get(2).getClass()); + assertThat(sinks.size(), is(3)); + assertThat(sinks.get(0).getName(), is("endpoint1")); + assertThat(sinks.get(0).getClass(), is(InternalOpenSearchSink.class)); + assertThat(sinks.get(1).getName(), is("endpoint2")); + assertThat(sinks.get(1).getClass(), is(ExternalOpenSearchSink.class)); + assertThat(sinks.get(2).getName(), is("default")); + assertThat(sinks.get(2).getClass(), is(ExternalOpenSearchSink.class)); sinks = router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_READ); // 1, since we do not include default - Assert.assertEquals(1, sinks.size()); - Assert.assertEquals("endpoint3", sinks.get(0).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(0).getClass()); + assertThat(sinks.size(), is(1)); + assertThat(sinks.get(0).getName(), is("endpoint3")); + assertThat(sinks.get(0).getClass(), is(DebugSink.class)); } @Test @@ -68,9 +72,9 @@ public void testNoDefaultSink() throws Exception { .build(); AuditMessageRouter router = new AuditMessageRouter(settings, null, null, null); // no default sink, audit log not enabled - Assert.assertEquals(false, router.isEnabled()); - Assert.assertEquals(null, router.defaultSink); - Assert.assertEquals(null, router.categorySinks); + assertThat(router.isEnabled(), is(false)); + assertThat(router.defaultSink, is(nullValue())); + assertThat(router.categorySinks, is(nullValue())); // make sure no exception is thrown router.route(MockAuditMessageFactory.validAuditMessage()); } @@ -82,20 +86,20 @@ public void testMissingEndpoints() throws Exception { .build(); AuditMessageRouter router = createMessageRouterComplianceEnabled(settings); // fallback to debug sink if no default is given - Assert.assertEquals(InternalOpenSearchSink.class, router.defaultSink.getClass()); + assertThat(router.defaultSink.getClass(), is(InternalOpenSearchSink.class)); // missing configuration for endpoint2 / External ES. Fallback to // localhost List sinks = router.categorySinks.get(AuditCategory.MISSING_PRIVILEGES); // 2 valid endpoints - Assert.assertEquals(2, sinks.size()); - Assert.assertEquals("endpoint1", sinks.get(0).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(0).getClass()); - Assert.assertEquals("endpoint3", sinks.get(1).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(1).getClass()); + assertThat(sinks.size(), is(2)); + assertThat(sinks.get(0).getName(), is("endpoint1")); + assertThat(sinks.get(0).getClass(), is(InternalOpenSearchSink.class)); + assertThat(sinks.get(1).getName(), is("endpoint3")); + assertThat(sinks.get(1).getClass(), is(DebugSink.class)); sinks = router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_WRITE); - Assert.assertEquals(1, sinks.size()); - Assert.assertEquals("default", sinks.get(0).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(0).getClass()); + assertThat(sinks.size(), is(1)); + assertThat(sinks.get(0).getName(), is("default")); + assertThat(sinks.get(0).getClass(), is(InternalOpenSearchSink.class)); // no valid end points for category, must use default Assert.assertNull(router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_READ)); } @@ -107,31 +111,31 @@ public void testWrongCategories() throws Exception { .build(); AuditMessageRouter router = createMessageRouterComplianceEnabled(settings); // no default sink, we fall back to debug sink - Assert.assertEquals(DebugSink.class, router.defaultSink.getClass()); + assertThat(router.defaultSink.getClass(), is(DebugSink.class)); List sinks = router.categorySinks.get(AuditCategory.MISSING_PRIVILEGES); // 3, since default is not valid but replaced with Debug - Assert.assertEquals(3, sinks.size()); - Assert.assertEquals("default", sinks.get(0).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(0).getClass()); - Assert.assertEquals("endpoint1", sinks.get(1).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(1).getClass()); - Assert.assertEquals("endpoint2", sinks.get(2).getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, sinks.get(2).getClass()); + assertThat(sinks.size(), is(3)); + assertThat(sinks.get(0).getName(), is("default")); + assertThat(sinks.get(0).getClass(), is(DebugSink.class)); + assertThat(sinks.get(1).getName(), is("endpoint1")); + assertThat(sinks.get(1).getClass(), is(InternalOpenSearchSink.class)); + assertThat(sinks.get(2).getName(), is("endpoint2")); + assertThat(sinks.get(2).getClass(), is(ExternalOpenSearchSink.class)); sinks = router.categorySinks.get(AuditCategory.GRANTED_PRIVILEGES); - Assert.assertEquals(3, sinks.size()); - Assert.assertEquals("endpoint1", sinks.get(0).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(0).getClass()); - Assert.assertEquals("endpoint3", sinks.get(1).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(1).getClass()); - Assert.assertEquals("default", sinks.get(2).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(2).getClass()); + assertThat(sinks.size(), is(3)); + assertThat(sinks.get(0).getName(), is("endpoint1")); + assertThat(sinks.get(0).getClass(), is(InternalOpenSearchSink.class)); + assertThat(sinks.get(1).getName(), is("endpoint3")); + assertThat(sinks.get(1).getClass(), is(DebugSink.class)); + assertThat(sinks.get(2).getName(), is("default")); + assertThat(sinks.get(2).getClass(), is(DebugSink.class)); sinks = router.categorySinks.get(AuditCategory.AUTHENTICATED); - Assert.assertEquals(1, sinks.size()); - Assert.assertEquals("endpoint1", sinks.get(0).getName()); - Assert.assertEquals(InternalOpenSearchSink.class, sinks.get(0).getClass()); + assertThat(sinks.size(), is(1)); + assertThat(sinks.get(0).getName(), is("endpoint1")); + assertThat(sinks.get(0).getClass(), is(InternalOpenSearchSink.class)); // bad headers has no valid endpoint, so we use default Assert.assertNull(router.categorySinks.get(AuditCategory.BAD_HEADERS)); @@ -148,22 +152,22 @@ public void testWrongEndpointTypes() throws Exception { .build(); AuditMessageRouter router = createMessageRouterComplianceEnabled(settings); // debug sink not valid, fallback to debug - Assert.assertEquals(DebugSink.class, router.defaultSink.getClass()); + assertThat(router.defaultSink.getClass(), is(DebugSink.class)); List sinks = router.categorySinks.get(AuditCategory.MISSING_PRIVILEGES); // 2 valid endpoints in config, default falls back to debug - Assert.assertEquals(3, sinks.size()); - Assert.assertEquals("endpoint2", sinks.get(0).getName()); - Assert.assertEquals(ExternalOpenSearchSink.class, sinks.get(0).getClass()); - Assert.assertEquals("endpoint3", sinks.get(1).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(1).getClass()); - Assert.assertEquals("default", sinks.get(2).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(2).getClass()); + assertThat(sinks.size(), is(3)); + assertThat(sinks.get(0).getName(), is("endpoint2")); + assertThat(sinks.get(0).getClass(), is(ExternalOpenSearchSink.class)); + assertThat(sinks.get(1).getName(), is("endpoint3")); + assertThat(sinks.get(1).getClass(), is(DebugSink.class)); + assertThat(sinks.get(2).getName(), is("default")); + assertThat(sinks.get(2).getClass(), is(DebugSink.class)); sinks = router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_WRITE); - Assert.assertEquals(1, sinks.size()); - Assert.assertEquals("default", sinks.get(0).getName()); - Assert.assertEquals(DebugSink.class, sinks.get(0).getClass()); + assertThat(sinks.size(), is(1)); + assertThat(sinks.get(0).getName(), is("default")); + assertThat(sinks.get(0).getClass(), is(DebugSink.class)); // no valid endpoints for category, must fallback to default Assert.assertNull(router.categorySinks.get(AuditCategory.COMPLIANCE_DOC_READ)); @@ -176,7 +180,7 @@ public void testNoMultipleEndpointsConfiguration() throws Exception { .build(); AuditMessageRouter router = createMessageRouterComplianceEnabled(settings); ThreadPoolConfig config = router.storagePool.getConfig(); - Assert.assertEquals(5, config.getThreadPoolSize()); - Assert.assertEquals(200000, config.getThreadPoolMaxQueueLen()); + assertThat(config.getThreadPoolSize(), is(5)); + assertThat(config.getThreadPoolMaxQueueLen(), is(200000)); } } diff --git a/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java b/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java index af856e2e90..0ced97cdb3 100644 --- a/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java +++ b/src/test/java/org/opensearch/security/auditlog/sink/KafkaSinkTest.java @@ -32,6 +32,9 @@ import org.springframework.kafka.test.rule.EmbeddedKafkaRule; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class KafkaSinkTest extends AbstractAuditlogiUnitTest { @ClassRule @@ -64,11 +67,11 @@ public void testKafka() throws Exception { SinkProvider provider = new SinkProvider(settings, null, null, null); AuditLogSink sink = provider.getDefaultSink(); try { - Assert.assertEquals(KafkaSink.class, sink.getClass()); + assertThat(sink.getClass(), is(KafkaSink.class)); boolean success = sink.doStore(MockAuditMessageFactory.validAuditMessage(AuditCategory.MISSING_PRIVILEGES)); Assert.assertTrue(success); ConsumerRecords records = consumer.poll(Duration.ofSeconds(10)); - Assert.assertEquals(1, records.count()); + assertThat(records.count(), is(1)); } finally { sink.close(); } diff --git a/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTLSTest.java b/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTLSTest.java index b7ebc12fb0..1e4f749271 100644 --- a/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTLSTest.java +++ b/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTLSTest.java @@ -36,6 +36,9 @@ import org.opensearch.security.auditlog.impl.AuditMessage; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SinkProviderTLSTest { protected HttpServer server = null; @@ -91,7 +94,7 @@ public void testTlsConfigurationNoFallback() throws Exception { SinkProvider provider = new SinkProvider(builder.build(), null, null, null); WebhookSink defaultSink = (WebhookSink) provider.defaultSink; - Assert.assertEquals(true, defaultSink.verifySSL); + assertThat(defaultSink.verifySSL, is(true)); AuditMessage msg = MockAuditMessageFactory.validAuditMessage(); provider.allSinks.get("endpoint1").store(msg); diff --git a/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTest.java b/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTest.java index af8204a5c7..aae986ad3e 100644 --- a/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTest.java +++ b/src/test/java/org/opensearch/security/auditlog/sink/SinkProviderTest.java @@ -12,12 +12,15 @@ package org.opensearch.security.auditlog.sink; import org.apache.logging.log4j.Level; -import org.junit.Assert; import org.junit.Test; import org.opensearch.common.settings.Settings; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; + public class SinkProviderTest { @Test @@ -29,70 +32,70 @@ public void testConfiguration() throws Exception { SinkProvider provider = new SinkProvider(settings, null, null, null); // make sure we have a debug sink as fallback - Assert.assertEquals(DebugSink.class, provider.fallbackSink.getClass()); + assertThat(provider.fallbackSink.getClass(), is(DebugSink.class)); AuditLogSink sink = provider.getSink("DefaULT"); - Assert.assertEquals(sink.getClass(), DebugSink.class); + assertThat(DebugSink.class, is(sink.getClass())); sink = provider.getSink("endpoint1"); - Assert.assertEquals(InternalOpenSearchSink.class, sink.getClass()); + assertThat(sink.getClass(), is(InternalOpenSearchSink.class)); sink = provider.getSink("endpoint2"); - Assert.assertEquals(ExternalOpenSearchSink.class, sink.getClass()); + assertThat(sink.getClass(), is(ExternalOpenSearchSink.class)); // todo: sink does not work sink = provider.getSink("endpoinT3"); - Assert.assertEquals(DebugSink.class, sink.getClass()); + assertThat(sink.getClass(), is(DebugSink.class)); // no valid type sink = provider.getSink("endpoint4"); - Assert.assertEquals(null, sink); + assertThat(sink, is(nullValue())); sink = provider.getSink("endpoint2"); - Assert.assertEquals(ExternalOpenSearchSink.class, sink.getClass()); + assertThat(sink.getClass(), is(ExternalOpenSearchSink.class)); // todo: sink does not work, no valid config // no valid type sink = provider.getSink("endpoint6"); - Assert.assertEquals(null, sink); + assertThat(sink, is(nullValue())); // no valid type sink = provider.getSink("endpoint7"); - Assert.assertEquals(null, sink); + assertThat(sink, is(nullValue())); sink = provider.getSink("endpoint8"); - Assert.assertEquals(DebugSink.class, sink.getClass()); + assertThat(sink.getClass(), is(DebugSink.class)); // wrong type in config sink = provider.getSink("endpoint9"); - Assert.assertEquals(ExternalOpenSearchSink.class, sink.getClass()); + assertThat(sink.getClass(), is(ExternalOpenSearchSink.class)); // log4j, valid configuration sink = provider.getSink("endpoint10"); - Assert.assertEquals(Log4JSink.class, sink.getClass()); + assertThat(sink.getClass(), is(Log4JSink.class)); Log4JSink lsink = (Log4JSink) sink; - Assert.assertEquals("loggername", lsink.loggerName); - Assert.assertEquals(Level.WARN, lsink.logLevel); + assertThat(lsink.loggerName, is("loggername")); + assertThat(lsink.logLevel, is(Level.WARN)); // log4j, no level, fallback to default sink = provider.getSink("endpoint11"); - Assert.assertEquals(Log4JSink.class, sink.getClass()); + assertThat(sink.getClass(), is(Log4JSink.class)); lsink = (Log4JSink) sink; - Assert.assertEquals("loggername", lsink.loggerName); - Assert.assertEquals(Level.INFO, lsink.logLevel); + assertThat(lsink.loggerName, is("loggername")); + assertThat(lsink.logLevel, is(Level.INFO)); // log4j, wrong level, fallback to log4j default sink = provider.getSink("endpoint12"); - Assert.assertEquals(Log4JSink.class, sink.getClass()); + assertThat(sink.getClass(), is(Log4JSink.class)); lsink = (Log4JSink) sink; - Assert.assertEquals("loggername", lsink.loggerName); - Assert.assertEquals(Level.DEBUG, lsink.logLevel); + assertThat(lsink.loggerName, is("loggername")); + assertThat(lsink.logLevel, is(Level.DEBUG)); sink = provider.getSink("endpoint13"); - Assert.assertEquals(Log4JSink.class, sink.getClass()); + assertThat(sink.getClass(), is(Log4JSink.class)); lsink = (Log4JSink) sink; - Assert.assertEquals("audit", lsink.loggerName); - Assert.assertEquals(Level.INFO, lsink.logLevel); + assertThat(lsink.loggerName, is("audit")); + assertThat(lsink.logLevel, is(Level.INFO)); } @@ -103,8 +106,8 @@ public void testNoMultipleEndpointsConfiguration() throws Exception { .build(); SinkProvider provider = new SinkProvider(settings, null, null, null); InternalOpenSearchSink sink = (InternalOpenSearchSink) provider.defaultSink; - Assert.assertEquals("myownindex", sink.index); - Assert.assertEquals("auditevents", sink.type); + assertThat(sink.index, is("myownindex")); + assertThat(sink.type, is("auditevents")); } } diff --git a/src/test/java/org/opensearch/security/auditlog/sink/WebhookAuditLogTest.java b/src/test/java/org/opensearch/security/auditlog/sink/WebhookAuditLogTest.java index a7d6919e0f..f0dfe123ae 100644 --- a/src/test/java/org/opensearch/security/auditlog/sink/WebhookAuditLogTest.java +++ b/src/test/java/org/opensearch/security/auditlog/sink/WebhookAuditLogTest.java @@ -44,6 +44,9 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class WebhookAuditLogTest { protected HttpServer server = null; @@ -78,8 +81,8 @@ public void invalidConfFallbackTest() throws Exception { // Webhook sink has failed ... Assert.assertNull(auditlog.webhookFormat); // ... so message must be stored in fallback - Assert.assertEquals(1, fallback.messages.size()); - Assert.assertEquals(msg, fallback.messages.get(0)); + assertThat(fallback.messages.size(), is(1)); + assertThat(fallback.messages.get(0), is(msg)); } @@ -102,8 +105,8 @@ public void formatsTest() throws Exception { MockWebhookAuditLog auditlog = new MockWebhookAuditLog(settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null); auditlog.store(msg); - Assert.assertEquals(WebhookFormat.TEXT, auditlog.webhookFormat); - Assert.assertEquals(ContentType.TEXT_PLAIN, auditlog.webhookFormat.getContentType()); + assertThat(auditlog.webhookFormat, is(WebhookFormat.TEXT)); + assertThat(auditlog.webhookFormat.getContentType(), is(ContentType.TEXT_PLAIN)); Assert.assertFalse(auditlog.payload, auditlog.payload.startsWith("{\"text\":")); // provide faulty format, defaults to TEXT @@ -118,8 +121,8 @@ public void formatsTest() throws Exception { .build(); auditlog = new MockWebhookAuditLog(settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null); auditlog.store(msg); - Assert.assertEquals(WebhookFormat.TEXT, auditlog.webhookFormat); - Assert.assertEquals(ContentType.TEXT_PLAIN, auditlog.webhookFormat.getContentType()); + assertThat(auditlog.webhookFormat, is(WebhookFormat.TEXT)); + assertThat(auditlog.webhookFormat.getContentType(), is(ContentType.TEXT_PLAIN)); Assert.assertFalse(auditlog.payload, auditlog.payload.startsWith("{\"text\":")); auditlog.close(); @@ -135,8 +138,8 @@ public void formatsTest() throws Exception { .build(); auditlog = new MockWebhookAuditLog(settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null); auditlog.store(msg); - Assert.assertEquals(WebhookFormat.TEXT, auditlog.webhookFormat); - Assert.assertEquals(ContentType.TEXT_PLAIN, auditlog.webhookFormat.getContentType()); + assertThat(auditlog.webhookFormat, is(WebhookFormat.TEXT)); + assertThat(auditlog.webhookFormat.getContentType(), is(ContentType.TEXT_PLAIN)); Assert.assertFalse(auditlog.payload, auditlog.payload.startsWith("{\"text\":")); Assert.assertTrue(auditlog.payload, auditlog.payload.contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertTrue(auditlog.payload, auditlog.payload.contains("audit_request_remote_address")); @@ -153,8 +156,8 @@ public void formatsTest() throws Exception { .build(); auditlog = new MockWebhookAuditLog(settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null); auditlog.store(msg); - Assert.assertEquals(WebhookFormat.JSON, auditlog.webhookFormat); - Assert.assertEquals(ContentType.APPLICATION_JSON, auditlog.webhookFormat.getContentType()); + assertThat(auditlog.webhookFormat, is(WebhookFormat.JSON)); + assertThat(auditlog.webhookFormat.getContentType(), is(ContentType.APPLICATION_JSON)); Assert.assertFalse(auditlog.payload, auditlog.payload.startsWith("{\"text\":")); Assert.assertTrue(auditlog.payload, auditlog.payload.contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertTrue(auditlog.payload, auditlog.payload.contains("audit_request_remote_address")); @@ -171,8 +174,8 @@ public void formatsTest() throws Exception { .build(); auditlog = new MockWebhookAuditLog(settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null); auditlog.store(msg); - Assert.assertEquals(WebhookFormat.SLACK, auditlog.webhookFormat); - Assert.assertEquals(ContentType.APPLICATION_JSON, auditlog.webhookFormat.getContentType()); + assertThat(auditlog.webhookFormat, is(WebhookFormat.SLACK)); + assertThat(auditlog.webhookFormat.getContentType(), is(ContentType.APPLICATION_JSON)); Assert.assertTrue(auditlog.payload, auditlog.payload.startsWith("{\"text\":")); Assert.assertTrue(auditlog.payload, auditlog.payload.contains(AuditMessage.UTC_TIMESTAMP)); Assert.assertTrue(auditlog.payload, auditlog.payload.contains("audit_request_remote_address")); @@ -200,8 +203,8 @@ public void invalidUrlTest() throws Exception { Assert.assertNull(auditlog.payload); Assert.assertNull(auditlog.webhookUrl); // message must be stored in fallback - Assert.assertEquals(1, fallback.messages.size()); - Assert.assertEquals(msg, fallback.messages.get(0)); + assertThat(fallback.messages.size(), is(1)); + assertThat(fallback.messages.get(0), is(msg)); } @Test @@ -223,10 +226,10 @@ public void noServerRunningHttpTest() throws Exception { AuditMessage msg = MockAuditMessageFactory.validAuditMessage(); auditlog.store(msg); // can't connect, no server running ... - Assert.assertEquals("http://localhost:8080/endpoint", auditlog.webhookUrl); + assertThat(auditlog.webhookUrl, is("http://localhost:8080/endpoint")); // ... message must be stored in fallback - Assert.assertEquals(1, fallback.messages.size()); - Assert.assertEquals(msg, fallback.messages.get(0)); + assertThat(fallback.messages.size(), is(1)); + assertThat(fallback.messages.get(0), is(msg)); } @Test @@ -259,12 +262,12 @@ public void postGetHttpTest() throws Exception { WebhookSink auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); AuditMessage msg = MockAuditMessageFactory.validAuditMessage(); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.startsWith("{\"text\":")); assertStringContainsAllKeysAndValues(handler.body); // no message stored on fallback - Assert.assertEquals(0, fallback.messages.size()); + assertThat(fallback.messages.size(), is(0)); handler.reset(); // TEXT @@ -280,7 +283,7 @@ public void postGetHttpTest() throws Exception { auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertFalse(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -299,7 +302,7 @@ public void postGetHttpTest() throws Exception { auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -318,8 +321,8 @@ public void postGetHttpTest() throws Exception { auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); - Assert.assertEquals("", handler.body); + assertThat(handler.method, is("POST")); + assertThat(handler.body, is("")); Assert.assertFalse(handler.body.contains("{")); assertStringContainsAllKeysAndValues(URLDecoder.decode(handler.uri, StandardCharsets.UTF_8.displayName())); handler.reset(); @@ -337,7 +340,7 @@ public void postGetHttpTest() throws Exception { auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("GET", handler.method); + assertThat(handler.method, is("GET")); Assert.assertNull(handler.body); assertStringContainsAllKeysAndValues(URLDecoder.decode(handler.uri, StandardCharsets.UTF_8.displayName())); server.awaitTermination(TimeValue.ofSeconds(3)); @@ -377,8 +380,8 @@ public void httpsTestWithoutTLSServer() throws Exception { Assert.assertNull(handler.body); Assert.assertNull(handler.uri); // ... so message must be stored in fallback - Assert.assertEquals(1, fallback.messages.size()); - Assert.assertEquals(msg, fallback.messages.get(0)); + assertThat(fallback.messages.size(), is(1)); + assertThat(fallback.messages.get(0), is(msg)); server.awaitTermination(TimeValue.ofSeconds(3)); } @@ -413,8 +416,8 @@ public void httpsTest() throws Exception { Assert.assertNull(handler.method); Assert.assertNull(handler.body); // message must be stored in fallback - Assert.assertEquals(1, fallback.messages.size()); - Assert.assertEquals(msg, fallback.messages.get(0)); + assertThat(fallback.messages.size(), is(1)); + assertThat(fallback.messages.get(0), is(msg)); // disable ssl verification, no ca, call must succeed handler.reset(); @@ -426,7 +429,7 @@ public void httpsTest() throws Exception { .build(); auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -445,7 +448,7 @@ public void httpsTest() throws Exception { .build(); auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -502,7 +505,7 @@ public void httpsTestPemDefault() throws Exception { .build(); AuditLogSink auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -521,7 +524,7 @@ public void httpsTestPemDefault() throws Exception { .build(); auditlog = new WebhookSink("name", settings, ConfigConstants.SECURITY_AUDIT_CONFIG_DEFAULT, null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -631,7 +634,7 @@ public void httpsTestPemEndpoint() throws Exception { .build(); AuditLogSink auditlog = new WebhookSink("name", settings, "plugins.security.audit.endpoints.endpoint1.config", null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -650,7 +653,7 @@ public void httpsTestPemEndpoint() throws Exception { .build(); auditlog = new WebhookSink("name", settings, "plugins.security.audit.endpoints.endpoint1.config", null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); @@ -739,7 +742,7 @@ public void httpsTestPemContentEndpoint() throws Exception { AuditLogSink auditlog = new WebhookSink("name", settings, "plugins.security.audit.endpoints.endpoint1.config", null, fallback); auditlog.store(msg); - Assert.assertEquals("POST", handler.method); + assertThat(handler.method, is("POST")); Assert.assertNotNull(handler.body); Assert.assertTrue(handler.body.contains("{")); assertStringContainsAllKeysAndValues(handler.body); diff --git a/src/test/java/org/opensearch/security/auth/RolesInjectorTest.java b/src/test/java/org/opensearch/security/auth/RolesInjectorTest.java index 4e893547d2..26b033729a 100644 --- a/src/test/java/org/opensearch/security/auth/RolesInjectorTest.java +++ b/src/test/java/org/opensearch/security/auth/RolesInjectorTest.java @@ -30,8 +30,10 @@ import org.opensearch.tasks.Task; import org.opensearch.transport.TransportRequest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; import static org.opensearch.security.support.ConfigConstants.OPENDISTRO_SECURITY_INJECTED_ROLES; -import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; public class RolesInjectorTest { @@ -52,9 +54,9 @@ public void testNotInjected() { ThreadContext threadContext = new ThreadContext(Settings.EMPTY); RolesInjector rolesInjector = new RolesInjector(auditLog); Set roles = rolesInjector.injectUserAndRoles(transportRequest, "action0", task, threadContext); - assertEquals(null, roles); + assertThat(roles, is(nullValue())); User user = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - assertEquals(null, user); + assertThat(user, is(nullValue())); } @Test @@ -66,11 +68,11 @@ public void testInjected() { Set roles = rolesInjector.injectUserAndRoles(transportRequest, "action0", task, threadContext); User user = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - assertEquals("user1", user.getName()); - assertEquals(0, user.getRoles().size()); - assertEquals(2, roles.size()); - assertEquals(true, roles.contains("role_1")); - assertEquals(true, roles.contains("role_2")); + assertThat(user.getName(), is("user1")); + assertThat(user.getRoles().size(), is(0)); + assertThat(roles.size(), is(2)); + assertThat(roles.contains("role_1"), is(true)); + assertThat(roles.contains("role_2"), is(true)); } @Test @@ -84,9 +86,9 @@ public void testCorruptedInjection() { RolesInjector rolesInjector = new RolesInjector(auditLog); Set roles = rolesInjector.injectUserAndRoles(transportRequest, "action0", task, threadContext); - assertEquals(null, roles); + assertThat(roles, is(nullValue())); User user = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - assertEquals(null, user); + assertThat(user, is(nullValue())); }); } } diff --git a/src/test/java/org/opensearch/security/auth/UserInjectorTest.java b/src/test/java/org/opensearch/security/auth/UserInjectorTest.java index 6338ef68a7..74b48d54e5 100644 --- a/src/test/java/org/opensearch/security/auth/UserInjectorTest.java +++ b/src/test/java/org/opensearch/security/auth/UserInjectorTest.java @@ -30,7 +30,8 @@ import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.mock; @@ -60,8 +61,8 @@ public void testValidInjectUser() { roles.addAll(Arrays.asList("role1", "role2")); threadContext.putTransient(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "user|role1,role2"); User injectedUser = userInjector.getInjectedUser(); - assertEquals(injectedUser.getName(), "user"); - assertEquals(injectedUser.getRoles(), roles); + assertThat("user", is(injectedUser.getName())); + assertThat(roles, is(injectedUser.getRoles())); } @Test @@ -73,9 +74,9 @@ public void testValidInjectUserIpV6() { "user|role1,role2|2001:db8:3333:4444:5555:6666:7777:8888:9200" ); UserInjector.InjectedUser injectedUser = userInjector.getInjectedUser(); - assertEquals("user", injectedUser.getName()); - assertEquals(9200, injectedUser.getTransportAddress().getPort()); - assertEquals("2001:db8:3333:4444:5555:6666:7777:8888", injectedUser.getTransportAddress().getAddress()); + assertThat(injectedUser.getName(), is("user")); + assertThat(injectedUser.getTransportAddress().getPort(), is(9200)); + assertThat(injectedUser.getTransportAddress().getAddress(), is("2001:db8:3333:4444:5555:6666:7777:8888")); } @Test @@ -84,9 +85,9 @@ public void testValidInjectUserIpV6ShortFormat() { roles.addAll(Arrays.asList("role1", "role2")); threadContext.putTransient(ConfigConstants.OPENDISTRO_SECURITY_INJECTED_USER, "user|role1,role2|2001:db8::1:9200"); UserInjector.InjectedUser injectedUser = userInjector.getInjectedUser(); - assertEquals("user", injectedUser.getName()); - assertEquals(9200, injectedUser.getTransportAddress().getPort()); - assertEquals("2001:db8::1", injectedUser.getTransportAddress().getAddress()); + assertThat(injectedUser.getName(), is("user")); + assertThat(injectedUser.getTransportAddress().getPort(), is(9200)); + assertThat(injectedUser.getTransportAddress().getAddress(), is("2001:db8::1")); } @Test @@ -110,10 +111,10 @@ public void testValidInjectUserBracketsIpV6() { "user|role1,role2|[2001:db8:3333:4444:5555:6666:7777:8888]:9200" ); UserInjector.InjectedUser injectedUser = userInjector.getInjectedUser(); - assertEquals("user", injectedUser.getName()); - assertEquals(roles, injectedUser.getRoles()); - assertEquals(9200, injectedUser.getTransportAddress().getPort()); - assertEquals("2001:db8:3333:4444:5555:6666:7777:8888", injectedUser.getTransportAddress().getAddress()); + assertThat(injectedUser.getName(), is("user")); + assertThat(injectedUser.getRoles(), is(roles)); + assertThat(injectedUser.getTransportAddress().getPort(), is(9200)); + assertThat(injectedUser.getTransportAddress().getAddress(), is("2001:db8:3333:4444:5555:6666:7777:8888")); } @Test @@ -144,19 +145,19 @@ public void testMapFromArray() { map = userInjector.mapFromArray("key", "value"); assertNotNull(map); - assertEquals(1, map.size()); - assertEquals("value", map.get("key")); + assertThat(map.size(), is(1)); + assertThat(map.get("key"), is("value")); map = userInjector.mapFromArray("key", "value", "key", "value"); assertNotNull(map); - assertEquals(1, map.size()); - assertEquals("value", map.get("key")); + assertThat(map.size(), is(1)); + assertThat(map.get("key"), is("value")); map = userInjector.mapFromArray("key1", "value1", "key2", "value2"); assertNotNull(map); - assertEquals(2, map.size()); - assertEquals("value1", map.get("key1")); - assertEquals("value2", map.get("key2")); + assertThat(map.size(), is(2)); + assertThat(map.get("key1"), is("value1")); + assertThat(map.get("key2"), is("value2")); } diff --git a/src/test/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtilsTest.java b/src/test/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtilsTest.java index df6456303a..d9f663d9fe 100644 --- a/src/test/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtilsTest.java +++ b/src/test/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtilsTest.java @@ -16,6 +16,9 @@ import org.junit.Assert; import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class EncryptionDecryptionUtilsTest { @Test @@ -28,7 +31,7 @@ public void testEncryptDecrypt() { String encryptedString = util.encrypt(data); String decryptedString = util.decrypt(encryptedString); - Assert.assertEquals(data, decryptedString); + assertThat(decryptedString, is(data)); } @Test @@ -43,7 +46,7 @@ public void testDecryptingWithWrongKey() { EncryptionDecryptionUtil util2 = new EncryptionDecryptionUtil(secret2); RuntimeException ex = Assert.assertThrows(RuntimeException.class, () -> util2.decrypt(encryptedString)); - Assert.assertEquals("Error processing data with cipher", ex.getMessage()); + assertThat(ex.getMessage(), is("Error processing data with cipher")); } @Test @@ -54,7 +57,7 @@ public void testDecryptingCorruptedData() { EncryptionDecryptionUtil util = new EncryptionDecryptionUtil(secret); RuntimeException ex = Assert.assertThrows(RuntimeException.class, () -> util.decrypt(corruptedEncryptedString)); - Assert.assertEquals("Last unit does not have enough valid bits", ex.getMessage()); + assertThat(ex.getMessage(), is("Last unit does not have enough valid bits")); } @Test @@ -66,7 +69,7 @@ public void testEncryptDecryptEmptyString() { String encryptedString = util.encrypt(data); String decryptedString = util.decrypt(encryptedString); - Assert.assertEquals(data, decryptedString); + assertThat(decryptedString, is(data)); } @Test(expected = NullPointerException.class) diff --git a/src/test/java/org/opensearch/security/authtoken/jwt/JwtVendorTest.java b/src/test/java/org/opensearch/security/authtoken/jwt/JwtVendorTest.java index 76a3847084..ca8b4ad14d 100644 --- a/src/test/java/org/opensearch/security/authtoken/jwt/JwtVendorTest.java +++ b/src/test/java/org/opensearch/security/authtoken/jwt/JwtVendorTest.java @@ -44,7 +44,6 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.core.IsNull.notNullValue; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -65,8 +64,8 @@ public void testCreateJwkFromSettings() { final Settings settings = Settings.builder().put("signing_key", signingKeyB64Encoded).build(); final Tuple jwk = JwtVendor.createJwkFromSettings(settings); - Assert.assertEquals("HS512", jwk.v1().getAlgorithm().getName()); - Assert.assertEquals("sig", jwk.v1().getKeyUse().toString()); + assertThat(jwk.v1().getAlgorithm().getName(), is("HS512")); + assertThat(jwk.v1().getKeyUse().toString(), is("sig")); Assert.assertTrue(jwk.v1().toOctetSequenceKey().getKeyValue().decodeToString().startsWith(signingKey)); } @@ -173,7 +172,7 @@ public void testCreateJwtWithNegativeExpiry() { throw new RuntimeException(e); } }); - assertEquals("java.lang.IllegalArgumentException: The expiration time should be a positive integer", exception.getMessage()); + assertThat(exception.getMessage(), is("java.lang.IllegalArgumentException: The expiration time should be a positive integer")); } @Test @@ -212,7 +211,7 @@ public void testCreateJwtWithBadEncryptionKey() { throw new RuntimeException(e); } }); - assertEquals("java.lang.IllegalArgumentException: encryption_key cannot be null", exception.getMessage()); + assertThat(exception.getMessage(), is("java.lang.IllegalArgumentException: encryption_key cannot be null")); } @Test @@ -233,7 +232,7 @@ public void testCreateJwtWithBadRoles() { throw new RuntimeException(e); } }); - assertEquals("java.lang.IllegalArgumentException: Roles cannot be null", exception.getMessage()); + assertThat(exception.getMessage(), is("java.lang.IllegalArgumentException: Roles cannot be null")); } @Test diff --git a/src/test/java/org/opensearch/security/authtoken/jwt/KeyPaddingUtilTest.java b/src/test/java/org/opensearch/security/authtoken/jwt/KeyPaddingUtilTest.java index 2633c75c2f..0fbf549bdd 100644 --- a/src/test/java/org/opensearch/security/authtoken/jwt/KeyPaddingUtilTest.java +++ b/src/test/java/org/opensearch/security/authtoken/jwt/KeyPaddingUtilTest.java @@ -15,7 +15,8 @@ import com.nimbusds.jose.JWSAlgorithm; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; public class KeyPaddingUtilTest { @@ -28,7 +29,7 @@ public void testPadSecretForHS256() { // For HS256, HMAC using SHA-256, typical key length is 256 bits or 32 bytes int expectedLength = 32; - assertEquals(expectedLength, paddedKey.length()); + assertThat(paddedKey.length(), is(expectedLength)); } @Test @@ -38,6 +39,6 @@ public void testPadSecretForHS384() { // For HS384, HMAC using SHA-384, typical key length is 384 bits or 48 bytes int expectedLength = 48; - assertEquals(expectedLength, paddedKey.length()); + assertThat(paddedKey.length(), is(expectedLength)); } } diff --git a/src/test/java/org/opensearch/security/cache/CachingTest.java b/src/test/java/org/opensearch/security/cache/CachingTest.java index cb71be78e1..04bf303896 100644 --- a/src/test/java/org/opensearch/security/cache/CachingTest.java +++ b/src/test/java/org/opensearch/security/cache/CachingTest.java @@ -13,7 +13,6 @@ import org.apache.hc.core5.http.message.BasicHeader; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -23,6 +22,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class CachingTest extends SingleClusterTest { @Override @@ -43,16 +45,16 @@ public void testRestCaching() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig(), Settings.EMPTY); final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); - Assert.assertEquals(3, DummyHTTPAuthenticator.getCount()); - Assert.assertEquals(1, DummyAuthorizer.getCount()); - Assert.assertEquals(3, DummyAuthenticationBackend.getAuthCount()); - Assert.assertEquals(0, DummyAuthenticationBackend.getExistsCount()); + assertThat(DummyHTTPAuthenticator.getCount(), is(3L)); + assertThat(DummyAuthorizer.getCount(), is(1L)); + assertThat(DummyAuthenticationBackend.getAuthCount(), is(3L)); + assertThat(DummyAuthenticationBackend.getExistsCount(), is(0L)); } @Test @@ -61,16 +63,16 @@ public void testRestNoCaching() throws Exception { setup(Settings.EMPTY, new DynamicSecurityConfig(), settings); final RestHelper rh = nonSslRestHelper(); HttpResponse res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty"); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); - Assert.assertEquals(3, DummyHTTPAuthenticator.getCount()); - Assert.assertEquals(3, DummyAuthorizer.getCount()); - Assert.assertEquals(3, DummyAuthenticationBackend.getAuthCount()); - Assert.assertEquals(0, DummyAuthenticationBackend.getExistsCount()); + assertThat(DummyHTTPAuthenticator.getCount(), is(3L)); + assertThat(DummyAuthorizer.getCount(), is(3L)); + assertThat(DummyAuthenticationBackend.getAuthCount(), is(3L)); + assertThat(DummyAuthenticationBackend.getExistsCount(), is(0L)); } @Test @@ -82,26 +84,26 @@ public void testRestCachingWithImpersonation() throws Exception { "_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest( "_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest( "_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); res = rh.executeGetRequest( "_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser2") ); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); - Assert.assertEquals(4, DummyHTTPAuthenticator.getCount()); - Assert.assertEquals(3, DummyAuthorizer.getCount()); - Assert.assertEquals(4, DummyAuthenticationBackend.getAuthCount()); - Assert.assertEquals(2, DummyAuthenticationBackend.getExistsCount()); + assertThat(DummyHTTPAuthenticator.getCount(), is(4L)); + assertThat(DummyAuthorizer.getCount(), is(3L)); + assertThat(DummyAuthenticationBackend.getAuthCount(), is(4L)); + assertThat(DummyAuthenticationBackend.getExistsCount(), is(2L)); } } diff --git a/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java b/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java index 0bf9e0e9df..32ab78dbdf 100644 --- a/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java +++ b/src/test/java/org/opensearch/security/ccstest/CrossClusterSearchTests.java @@ -65,6 +65,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; public class CrossClusterSearchTests extends AbstractSecurityUnitTest { @@ -131,7 +132,7 @@ private void setupCcs( String json = "{" + "\"persistent\" : {" + "\"cluster.remote.cross_cluster_two.seeds\" : [\"" + seed + "\"]" + "}" + "}"; HttpResponse response = rh1.executePutRequest("_cluster/settings", json, encodeBasicHeader("sarek", "sarek")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } private Tuple setupCluster( @@ -204,7 +205,7 @@ public void testCcs() throws Exception { "cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("crl1")); Assert.assertTrue(ccs.getBody().contains("crl2")); Assert.assertTrue(ccs.getBody().contains("twitter")); @@ -215,7 +216,7 @@ public void testCcs() throws Exception { encodeBasicHeader("nagilum", "nagilum") ); // TODO fix exception nesting - // Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, ccs.getStatusCode()); + // assertThat(ccs.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); // Assert.assertTrue(ccs.getBody().contains("Can not filter indices; index cross_cluster_two:xx exists but there is also a remote // cluster named: cross_cluster_two")); @@ -224,7 +225,7 @@ public void testCcs() throws Exception { "cross_cluster_two:abcnonext/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); Assert.assertTrue(ccs.getBody().contains("index_not_found_exception")); // query 6 @@ -232,7 +233,7 @@ public void testCcs() throws Exception { "cross_cluster_two:twitter,twutter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("\"timed_out\" : false")); Assert.assertTrue(ccs.getBody().contains("crl1")); @@ -299,34 +300,34 @@ public void testCcsNonadmin() throws Exception { "cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // query 2 ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twit*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); // query 3 ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter,twitter,twutter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // query 4 ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); @@ -335,7 +336,7 @@ public void testCcsNonadmin() throws Exception { "cross_cluster_two:twutter,twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // query 6 String msearchBody = "{}" @@ -348,7 +349,7 @@ public void testCcsNonadmin() throws Exception { msearchBody, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); // query 7 msearchBody = "{}" @@ -361,135 +362,135 @@ public void testCcsNonadmin() throws Exception { msearchBody, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "_all/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "*:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "hfghgtdhfhuth/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "hfghgtdhfhuth*/_search", encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("\"hits\":[]")); // TODO: Change for 25.0 to be forbidden (Indices options) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest(":*/_search", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("\"hits\":[]")); // TODO: Change for 25.0 to be forbidden (Indices options) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "*:/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E,%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); // Alias both ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "notexist,coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // TODO Fix for 25.0 to resolve coordalias (Indices options) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("crusherw", "crusherw") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -551,7 +552,7 @@ public void testCcsNonadminDnfof() throws Exception { "cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); @@ -560,14 +561,14 @@ public void testCcsNonadminDnfof() throws Exception { "cross_cluster_two:twit*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); // query 3 ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter,twitter,twutter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("twutter")); // query 4 @@ -575,7 +576,7 @@ public void testCcsNonadminDnfof() throws Exception { "cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); @@ -584,7 +585,7 @@ public void testCcsNonadminDnfof() throws Exception { "cross_cluster_two:twutter,twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // query 6 String msearchBody = "{}" @@ -597,7 +598,7 @@ public void testCcsNonadminDnfof() throws Exception { msearchBody, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); // query 7 msearchBody = "{}" @@ -610,43 +611,43 @@ public void testCcsNonadminDnfof() throws Exception { msearchBody, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "_all/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter,twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:*,*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("crl1_")); Assert.assertTrue(ccs.getBody().contains("crl2_")); @@ -655,103 +656,103 @@ public void testCcsNonadminDnfof() throws Exception { "*cross*:*twit*,*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter,t*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "*:*/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "hfghgtdhfhuth/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "hfghgtdhfhuth*/_search", encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("\"hits\":[]")); // TODO: Change for 25.0 to be forbidden (Indices options) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest(":*/_search", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("\"hits\":[]")); // TODO: Change for 25.0 to be forbidden (Indices options) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "*:/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:%3Clogstash-%7Bnow%2Fd%7D%3E,%3Clogstash-%7Bnow%2Fd%7D%3E/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:remotealias,coordalias/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executeGetRequest( "cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("crusherw", "crusherw") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -785,7 +786,7 @@ public void testCcsEmptyCoord() throws Exception { "cross_cluster_two:twitter/_search?pretty&ccs_minimize_roundtrips=" + ccsMinimizeRoundtrips(), encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("\"timed_out\" : false")); Assert.assertFalse(ccs.getBody().contains("crl1")); @@ -839,7 +840,7 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertFalse(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("coordinating")); @@ -850,7 +851,7 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertFalse(ccs.getBody().contains("cross_cluster_two")); Assert.assertFalse(ccs.getBody().contains("coordinating")); @@ -861,13 +862,13 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:remo*,coo*/_search?pretty", dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("remote")); @@ -878,7 +879,7 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("remote")); @@ -889,7 +890,7 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("remote")); @@ -900,7 +901,7 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("remote")); @@ -911,7 +912,7 @@ public void testCcsDashboardsAggregations() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("remote")); @@ -976,7 +977,7 @@ public void testCcsDashboardsAggregationsNonAdminDnfof() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertFalse(ccs.getBody().contains("cross_cluster_two")); Assert.assertTrue(ccs.getBody().contains("twitter")); @@ -990,7 +991,7 @@ public void testCcsDashboardsAggregationsNonAdminDnfof() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertFalse(ccs.getBody().contains("cross_cluster_two")); Assert.assertFalse(ccs.getBody().contains("twitter")); @@ -1004,7 +1005,7 @@ public void testCcsDashboardsAggregationsNonAdminDnfof() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two:analytics")); Assert.assertTrue(ccs.getBody().contains("twitter")); @@ -1016,13 +1017,13 @@ public void testCcsDashboardsAggregationsNonAdminDnfof() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:ana*,twi*/_search?pretty", dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two:analytics")); Assert.assertTrue(ccs.getBody().contains("twitter")); @@ -1034,7 +1035,7 @@ public void testCcsDashboardsAggregationsNonAdminDnfof() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two:analytics")); Assert.assertFalse(ccs.getBody().contains("twitter")); @@ -1046,13 +1047,13 @@ public void testCcsDashboardsAggregationsNonAdminDnfof() throws Exception { dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:*/_search?pretty", dashboardsIndicesAgg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("cross_cluster_two:analytics")); Assert.assertFalse(ccs.getBody().contains("twitter")); @@ -1107,7 +1108,7 @@ public void testCcsAggregations() throws Exception { agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("\"timed_out\" : false")); Assert.assertTrue(ccs.getBody().contains("crl1")); @@ -1119,7 +1120,7 @@ public void testCcsAggregations() throws Exception { agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("\"timed_out\" : false")); Assert.assertTrue(ccs.getBody().contains("crl1")); @@ -1131,7 +1132,7 @@ public void testCcsAggregations() throws Exception { agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("\"timed_out\" : false")); Assert.assertFalse(ccs.getBody().contains("crl1")); @@ -1143,37 +1144,40 @@ public void testCcsAggregations() throws Exception { agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:*,notfound/_search?pretty", agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:notfound,notfound/_search?pretty", agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:notfou*,*/_search?pretty", agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode());// TODO: Change for 25.0 to be forbidden (Indices options) + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK));// TODO: Change for 25.0 to be forbidden (Indices options, + // is(HttpStatus.SC_OK)) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:*,notfou*/_search?pretty", agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode());// TODO: Change for 25.0 to be forbidden (Indices options) + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK));// TODO: Change for 25.0 to be forbidden (Indices options, + // is(HttpStatus.SC_OK)) ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:not*,notf*/_search?pretty", agg, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode());// TODO: Change for 25.0 to be forbidden (Indices options) + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK));// TODO: Change for 25.0 to be forbidden (Indices options, + // is(HttpStatus.SC_OK)) } @Test @@ -1233,13 +1237,13 @@ public void testCcsAggregationsDnfof() throws Exception { agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:notfound*,*/_search?pretty", agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(ccs.getBody().contains("security_exception")); Assert.assertTrue(ccs.getBody().contains("\"timed_out\" : false")); Assert.assertTrue(ccs.getBody().contains("crl1")); @@ -1251,31 +1255,31 @@ public void testCcsAggregationsDnfof() throws Exception { agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:notfound,notfound/_search?pretty", agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:notfou*,*/_search?pretty", agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:*,notfou*/_search?pretty", agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); ccs = new RestHelper(cl1Info, false, false, getResourceFolder()).executePostRequest( "cross_cluster_two:not*,notf*/_search?pretty", agg, encodeBasicHeader("twitter", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); } private ClusterTransportClientSettings getBaseSettingsWithDifferentCert() { @@ -1411,22 +1415,22 @@ public void testCcsWithDiffCertsWithNodesDnDynamicallyAdded() throws Exception { public void testCcsWithRoleInjection() throws Exception { setupCcs(new DynamicSecurityConfig().setSecurityRoles("roles.yml")); - Assert.assertEquals( + assertThat( cl1Info.numNodes, - cl1.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes() + is(cl1.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes()) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - cl1.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(cl1.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); - Assert.assertEquals( + assertThat( cl2Info.numNodes, - cl2.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes() + is(cl2.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes()) ); - Assert.assertEquals( + assertThat( ClusterHealthStatus.GREEN, - cl2.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus() + is(cl2.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus()) ); try (Client tc = cl2.nodeClient()) { @@ -1473,7 +1477,7 @@ public void testCcsWithRoleInjection() throws Exception { getReq.refresh(true); GetResponse getRes = remoteClient.get(getReq).actionGet(); - Assert.assertEquals(getRes.getId(), "0"); + assertThat("0", is(getRes.getId())); } catch (OpenSearchSecurityException ex) { exception = ex; log.warn(ex.toString()); @@ -1502,7 +1506,7 @@ public void testCcsWithRoleInjection() throws Exception { getReq.refresh(true); GetResponse getRes = remoteClient.get(getReq).actionGet(); - Assert.assertEquals(getRes.getId(), "0"); + assertThat("0", is(getRes.getId())); } catch (OpenSearchSecurityException ex) { Assert.assertNull(ex); log.warn(ex.toString()); diff --git a/src/test/java/org/opensearch/security/ccstest/RemoteReindexTests.java b/src/test/java/org/opensearch/security/ccstest/RemoteReindexTests.java index 15fe91d822..d6bc614366 100644 --- a/src/test/java/org/opensearch/security/ccstest/RemoteReindexTests.java +++ b/src/test/java/org/opensearch/security/ccstest/RemoteReindexTests.java @@ -44,6 +44,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class RemoteReindexTests extends AbstractSecurityUnitTest { private final ClusterHelper cl1 = new ClusterHelper( @@ -134,7 +137,7 @@ public void testNonSSLReindex() throws Exception { reindex, encodeBasicHeader("nagilum", "nagilum") ); - Assert.assertEquals(HttpStatus.SC_OK, ccs.getStatusCode()); + assertThat(ccs.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(ccs.getBody().contains("created\" : 1")); } } diff --git a/src/test/java/org/opensearch/security/configuration/ConfigurationRepositoryTest.java b/src/test/java/org/opensearch/security/configuration/ConfigurationRepositoryTest.java index 30cbbe6a01..ac1f57c0f1 100644 --- a/src/test/java/org/opensearch/security/configuration/ConfigurationRepositoryTest.java +++ b/src/test/java/org/opensearch/security/configuration/ConfigurationRepositoryTest.java @@ -53,7 +53,6 @@ import static org.hamcrest.Matchers.notNullValue; import static org.opensearch.security.support.ConfigConstants.OPENDISTRO_SECURITY_DEFAULT_CONFIG_INDEX; import static org.opensearch.security.support.ConfigConstants.SECURITY_ALLOW_DEFAULT_INIT_SECURITYINDEX; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; @@ -282,7 +281,7 @@ public void testExecuteConfigurationInitialization_executeInitializationOnlyOnce void assertClusterState(final ArgumentCaptor clusterStateUpdateTaskCaptor) throws Exception { final var initializedStateUpdate = clusterStateUpdateTaskCaptor.getValue(); - assertEquals(Priority.IMMEDIATE, initializedStateUpdate.priority()); + assertThat(initializedStateUpdate.priority(), is(Priority.IMMEDIATE)); var clusterState = initializedStateUpdate.execute(ClusterState.EMPTY_STATE); SecurityMetadata securityMetadata = clusterState.custom(SecurityMetadata.TYPE); assertNotNull(securityMetadata.created()); diff --git a/src/test/java/org/opensearch/security/configuration/SaltTest.java b/src/test/java/org/opensearch/security/configuration/SaltTest.java index 918a27e8c5..1a57a04629 100644 --- a/src/test/java/org/opensearch/security/configuration/SaltTest.java +++ b/src/test/java/org/opensearch/security/configuration/SaltTest.java @@ -21,9 +21,10 @@ import org.opensearch.common.settings.Settings; import org.opensearch.security.support.ConfigConstants; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.configuration.Salt.SALT_SIZE; import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; public class SaltTest { @@ -36,7 +37,7 @@ public void testDefault() { final Salt salt = Salt.from(Settings.EMPTY); // assert - assertEquals(SALT_SIZE, salt.getSalt16().length); + assertThat(salt.getSalt16().length, is(SALT_SIZE)); assertArrayEquals(ConfigConstants.SECURITY_COMPLIANCE_SALT_DEFAULT.getBytes(StandardCharsets.UTF_8), salt.getSalt16()); } @@ -51,7 +52,7 @@ public void testConfig() { // assert assertArrayEquals(testSalt.getBytes(StandardCharsets.UTF_8), salt.getSalt16()); - assertEquals(SALT_SIZE, salt.getSalt16().length); + assertThat(salt.getSalt16().length, is(SALT_SIZE)); } @Test @@ -63,7 +64,7 @@ public void testSaltUsesOnlyFirst16Bytes() { final Salt salt = Salt.from(settings); // assert - assertEquals(SALT_SIZE, salt.getSalt16().length); + assertThat(salt.getSalt16().length, is(SALT_SIZE)); assertArrayEquals(testSalt.substring(0, SALT_SIZE).getBytes(StandardCharsets.UTF_8), salt.getSalt16()); } diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/AbstractDlsFlsTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/AbstractDlsFlsTest.java index 0edb14ce73..3e51ea187a 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/AbstractDlsFlsTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/AbstractDlsFlsTest.java @@ -15,8 +15,6 @@ import java.util.Map; import java.util.Set; -import org.junit.Assert; - import org.opensearch.action.get.GetResponse; import org.opensearch.action.get.MultiGetResponse; import org.opensearch.action.search.MultiSearchResponse; @@ -34,6 +32,9 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public abstract class AbstractDlsFlsTest extends SingleClusterTest { protected RestHelper rh = null; @@ -77,7 +78,7 @@ protected final void setup(Settings override, DynamicSecurityConfig dynamicSecur protected SearchResponse executeSearch(String indexName, String user, String password) throws Exception { HttpResponse response = rh.executeGetRequest("/" + indexName + "/_search?from=0&size=50&pretty", encodeBasicHeader(user, password)); - Assert.assertEquals(200, response.getStatusCode()); + assertThat(response.getStatusCode(), is(200)); XContentParser xcp = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, response.getBody()); return SearchResponse.fromXContent(xcp); @@ -99,7 +100,7 @@ protected MultiSearchResponse executeMSearchMatchAll(String user, String passwor } HttpResponse response = rh.executePostRequest("/_msearch?pretty", body.toString(), encodeBasicHeader(user, password)); - Assert.assertEquals(200, response.getStatusCode()); + assertThat(response.getStatusCode(), is(200)); XContentParser xcp = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, response.getBody()); return MultiSearchResponse.fromXContext(xcp); @@ -114,7 +115,7 @@ protected MultiGetResponse executeMGet(String user, String password, Map h.getIndex().equals("tlqdummy")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 5, tlqdummyHits.size()); + assertThat(searchResponse.toString(), tlqdummyHits.size(), is(5)); // check 10 hits with code 1337 from tlqdocuments index. All other documents // must be filtered @@ -362,7 +364,7 @@ public void testSimpleSearch_AllIndices_All_AccessCodes_1337() throws Exception .stream() .filter((h) -> h.getIndex().equals("tlqdocuments")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 10, tlqdocumentHits.size()); + assertThat(searchResponse.toString(), tlqdocumentHits.size(), is(10)); assertAccessCodesMatch(tlqdocumentHits, new Integer[] { 1337 }); // check no access to user_access_codes index @@ -370,7 +372,7 @@ public void testSimpleSearch_AllIndices_All_AccessCodes_1337() throws Exception .stream() .filter((h) -> h.getIndex().equals("user_access_codes")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 0, userAccessCodesHits.size()); + assertThat(searchResponse.toString(), userAccessCodesHits.size(), is(0)); } @Test @@ -395,7 +397,7 @@ public void testSimpleSearch_AllIndicesWildcard_AccessCodes_1337() throws Except .stream() .filter((h) -> h.getIndex().equals("tlqdummy")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 5, tlqdummyHits.size()); + assertThat(searchResponse.toString(), tlqdummyHits.size(), is(5)); // check 10 hits with code 1337 from tlqdocuments index. All other documents // must be filtered @@ -403,7 +405,7 @@ public void testSimpleSearch_AllIndicesWildcard_AccessCodes_1337() throws Except .stream() .filter((h) -> h.getIndex().equals("tlqdocuments")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 10, tlqdocumentHits.size()); + assertThat(searchResponse.toString(), tlqdocumentHits.size(), is(10)); assertAccessCodesMatch(tlqdocumentHits, new Integer[] { 1337 }); // check no access to user_access_codes index @@ -411,7 +413,7 @@ public void testSimpleSearch_AllIndicesWildcard_AccessCodes_1337() throws Except .stream() .filter((h) -> h.getIndex().equals("user_access_codes")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 0, userAccessCodesHits.size()); + assertThat(searchResponse.toString(), userAccessCodesHits.size(), is(0)); } @Test @@ -436,7 +438,7 @@ public void testSimpleSearch_ThreeIndicesWildcard_AccessCodes_1337() throws Exce .stream() .filter((h) -> h.getIndex().equals("tlqdummy")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 5, tlqdummyHits.size()); + assertThat(searchResponse.toString(), tlqdummyHits.size(), is(5)); // check 10 hits with code 1337 from tlqdocuments index. All other documents // must be filtered @@ -444,7 +446,7 @@ public void testSimpleSearch_ThreeIndicesWildcard_AccessCodes_1337() throws Exce .stream() .filter((h) -> h.getIndex().equals("tlqdocuments")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 10, tlqdocumentHits.size()); + assertThat(searchResponse.toString(), tlqdocumentHits.size(), is(10)); assertAccessCodesMatch(tlqdocumentHits, new Integer[] { 1337 }); // check no access to user_access_codes index @@ -452,7 +454,7 @@ public void testSimpleSearch_ThreeIndicesWildcard_AccessCodes_1337() throws Exce .stream() .filter((h) -> h.getIndex().equals("user_access_codes")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 0, userAccessCodesHits.size()); + assertThat(searchResponse.toString(), userAccessCodesHits.size(), is(0)); } @@ -477,7 +479,7 @@ public void testSimpleSearch_TwoIndicesConcreteNames_AccessCodes_1337() throws E .stream() .filter((h) -> h.getIndex().equals("tlqdummy")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 5, tlqdummyHits.size()); + assertThat(searchResponse.toString(), tlqdummyHits.size(), is(5)); // ccheck 10 hits with code 1337 from tlqdocuments index. All other documents // must be filtered @@ -485,7 +487,7 @@ public void testSimpleSearch_TwoIndicesConcreteNames_AccessCodes_1337() throws E .stream() .filter((h) -> h.getIndex().equals("tlqdocuments")) .collect(Collectors.toSet()); - Assert.assertEquals(searchResponse.toString(), 10, tlqdocumentHits.size()); + assertThat(searchResponse.toString(), tlqdocumentHits.size(), is(10)); assertAccessCodesMatch(tlqdocumentHits, new Integer[] { 1337 }); } @@ -513,12 +515,12 @@ public void testMSearch_ThreeIndices_AccessCodes_1337() throws Exception { // check all 5 tlqdummy entries present List tlqdummyHits = Arrays.asList(responseItems[0].getResponse().getHits().getHits()); - Assert.assertEquals(searchResponse.toString(), 5, tlqdummyHits.size()); + assertThat(searchResponse.toString(), tlqdummyHits.size(), is(5)); // check 10 hits with code 1337 from tlqdocuments index. All other documents // must be filtered List tlqdocumentHits = Arrays.asList(responseItems[1].getResponse().getHits().getHits()); - Assert.assertEquals(searchResponse.toString(), 10, tlqdocumentHits.size()); + assertThat(searchResponse.toString(), tlqdocumentHits.size(), is(10)); assertAccessCodesMatch(tlqdocumentHits, new Integer[] { 1337 }); // check no access to user_access_codes index, just two indices in the response @@ -647,7 +649,7 @@ public void testGet_UserAccessCodesIndex_1337() throws Exception { // we expect a security exception here, user has no direct access to // user_access_codes index HttpResponse response = rh.executeGetRequest("/user_access_codes/_doc/tlq_1337", encodeBasicHeader("tlq_1337", "password")); - Assert.assertEquals(403, response.getStatusCode()); + assertThat(response.getStatusCode(), is(403)); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/DlsTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/DlsTest.java index e4dffcc31f..06e5e51ab0 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/DlsTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/DlsTest.java @@ -23,6 +23,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class DlsTest extends AbstractDlsFlsTest { @Override @@ -66,17 +69,17 @@ public void testDlsAggregations() throws Exception { + "}"; HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"value\" : 1500.0")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"value\" : 1510.0")); @@ -103,32 +106,32 @@ public void testDls() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals(res.getHeaders().toString(), 3, res.getHeaders().size()); + assertThat(res.getHeaders().toString(), res.getHeaders().size(), is(3)); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -147,9 +150,9 @@ public void testDls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -168,23 +171,26 @@ public void testDls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?q=amount:10&pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?q=amount:10&pretty", encodeBasicHeader("dept_manager", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -198,16 +204,16 @@ public void testDls() throws Exception { res = rh.executeGetRequest("/deals/_doc/1?pretty", encodeBasicHeader("dept_manager", "password")); Assert.assertTrue(res.getBody().contains("\"found\" : true")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"count\" : 2,")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"count\" : 1,")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -223,9 +229,9 @@ public void testDls() throws Exception { + "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}" + System.lineSeparator(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertFalse(res.getBody().contains("_opendistro_security_dls_query")); Assert.assertFalse(res.getBody().contains("_opendistro_security_fls_fields")); @@ -245,9 +251,9 @@ public void testDls() throws Exception { + "]" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertFalse(res.getBody().contains("_opendistro_security_dls_query")); Assert.assertFalse(res.getBody().contains("_opendistro_security_fls_fields")); @@ -263,22 +269,22 @@ public void testDlsWithTermsQuery() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/terms/_search?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/terms/_search?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); - Assert.assertEquals(res.getTextFromJsonBody("/hits/total/value"), "1"); - Assert.assertEquals(res.getTextFromJsonBody("/_shards/failed"), "0"); + assertThat("1", is(res.getTextFromJsonBody("/hits/total/value"))); + assertThat("0", is(res.getTextFromJsonBody("/_shards/failed"))); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/terms/_doc/0", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/terms/_doc/0", encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); - Assert.assertEquals(res.getTextFromJsonBody("/_source/foo"), "bar"); + assertThat("bar", is(res.getTextFromJsonBody("/_source/foo"))); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - rh.executeGetRequest("/terms/_doc/1", encodeBasicHeader("dept_manager", "password")).getStatusCode() + is(rh.executeGetRequest("/terms/_doc/1", encodeBasicHeader("dept_manager", "password")).getStatusCode()) ); } @@ -303,9 +309,9 @@ public void testNonDls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -318,16 +324,16 @@ public void testDlsCache() throws Exception { setup(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -399,7 +405,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response1 = rh.executePostRequest("logs*/_search", query1, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response1.getStatusCode()); + assertThat(response1.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); Assert.assertTrue(response1.getBody(), response1.getBody().contains("min_doc_count 0 is not supported when DLS is activated")); // Non-admin user without setting "min_doc_count". Expected to only have access to buckets for dept_manager excluding E with 0 @@ -430,7 +436,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response2 = rh.executePostRequest("logs*/_search", query2, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusCode()); + assertThat(response2.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response2.getBody(), response2.getBody().contains("\"key\":\"A\"")); Assert.assertFalse(response2.getBody(), response2.getBody().contains("\"key\":\"B\"")); Assert.assertFalse(response2.getBody(), response2.getBody().contains("\"key\":\"C\"")); @@ -440,7 +446,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin with setting "min_doc_count":0. Expected to have access to all buckets". HttpResponse response3 = rh.executePostRequest("logs*/_search", query1, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response3.getStatusCode()); + assertThat(response3.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response3.getBody(), response3.getBody().contains("\"key\":\"A\"")); Assert.assertTrue(response3.getBody(), response3.getBody().contains("\"key\":\"B\"")); Assert.assertTrue(response3.getBody(), response3.getBody().contains("\"key\":\"C\"")); @@ -450,7 +456,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin without setting "min_doc_count". Expected to have access to all buckets excluding E with 0 doc_count". HttpResponse response4 = rh.executePostRequest("logs*/_search", query2, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response4.getStatusCode()); + assertThat(response4.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response4.getBody(), response4.getBody().contains("\"key\":\"A\"")); Assert.assertTrue(response4.getBody(), response4.getBody().contains("\"key\":\"B\"")); Assert.assertTrue(response4.getBody(), response4.getBody().contains("\"key\":\"C\"")); @@ -463,7 +469,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { "{\"size\":100,\"aggregations\":{\"significant_termX\":{\"significant_terms\":{\"field\":\"termX.keyword\",\"min_doc_count\":0}}}}"; HttpResponse response5 = rh.executePostRequest("logs*/_search", query3, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response5.getStatusCode()); + assertThat(response5.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response5.getBody(), response5.getBody().contains("\"termX\":\"A\"")); Assert.assertFalse(response5.getBody(), response5.getBody().contains("\"termX\":\"B\"")); Assert.assertFalse(response5.getBody(), response5.getBody().contains("\"termX\":\"C\"")); @@ -475,7 +481,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response6 = rh.executePostRequest("logs*/_search", query4, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response6.getStatusCode()); + assertThat(response6.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response6.getBody(), response6.getBody().contains("\"termX\":\"A\"")); Assert.assertFalse(response6.getBody(), response6.getBody().contains("\"termX\":\"B\"")); Assert.assertFalse(response6.getBody(), response6.getBody().contains("\"termX\":\"C\"")); @@ -485,7 +491,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin with setting "min_doc_count":0. Expected to have access to all buckets". HttpResponse response7 = rh.executePostRequest("logs*/_search", query3, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response7.getStatusCode()); + assertThat(response7.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response7.getBody(), response7.getBody().contains("\"termX\":\"A\"")); Assert.assertTrue(response7.getBody(), response7.getBody().contains("\"termX\":\"B\"")); Assert.assertTrue(response7.getBody(), response7.getBody().contains("\"termX\":\"C\"")); @@ -495,7 +501,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin without setting "min_doc_count". Expected to have access to all buckets". HttpResponse response8 = rh.executePostRequest("logs*/_search", query4, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response8.getStatusCode()); + assertThat(response8.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response8.getBody(), response8.getBody().contains("\"termX\":\"A\"")); Assert.assertTrue(response8.getBody(), response8.getBody().contains("\"termX\":\"B\"")); Assert.assertTrue(response8.getBody(), response8.getBody().contains("\"termX\":\"C\"")); @@ -508,7 +514,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response9 = rh.executePostRequest("logs*/_search", query5, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response9.getStatusCode()); + assertThat(response9.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response9.getBody(), response9.getBody().contains("\"termX\":\"A\"")); Assert.assertFalse(response9.getBody(), response9.getBody().contains("\"termX\":\"B\"")); Assert.assertFalse(response9.getBody(), response9.getBody().contains("\"termX\":\"C\"")); @@ -520,7 +526,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response10 = rh.executePostRequest("logs*/_search", query6, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response10.getStatusCode()); + assertThat(response10.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response10.getBody(), response10.getBody().contains("\"termX\":\"A\"")); Assert.assertFalse(response10.getBody(), response10.getBody().contains("\"termX\":\"B\"")); Assert.assertFalse(response10.getBody(), response10.getBody().contains("\"termX\":\"C\"")); @@ -530,7 +536,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin with setting "min_doc_count":0. Expected to have access to all buckets". HttpResponse response11 = rh.executePostRequest("logs*/_search", query5, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response11.getStatusCode()); + assertThat(response11.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response11.getBody(), response11.getBody().contains("\"termX\":\"A\"")); Assert.assertTrue(response11.getBody(), response11.getBody().contains("\"termX\":\"B\"")); Assert.assertTrue(response11.getBody(), response11.getBody().contains("\"termX\":\"C\"")); @@ -540,7 +546,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin without setting "min_doc_count". Expected to have access to all buckets". HttpResponse response12 = rh.executePostRequest("logs*/_search", query6, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response12.getStatusCode()); + assertThat(response12.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response12.getBody(), response12.getBody().contains("\"termX\":\"A\"")); Assert.assertTrue(response12.getBody(), response12.getBody().contains("\"termX\":\"B\"")); Assert.assertTrue(response12.getBody(), response12.getBody().contains("\"termX\":\"C\"")); @@ -554,7 +560,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response13 = rh.executePostRequest("logs*/_search", query7, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response13.getStatusCode()); + assertThat(response13.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response13.getBody(), response13.getBody().contains("\"termX\":\"A\"")); Assert.assertFalse(response13.getBody(), response13.getBody().contains("\"termX\":\"B\"")); Assert.assertFalse(response13.getBody(), response13.getBody().contains("\"termX\":\"C\"")); @@ -567,7 +573,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { HttpResponse response14 = rh.executePostRequest("logs*/_search", query8, encodeBasicHeader("dept_manager", "password")); - Assert.assertEquals(HttpStatus.SC_OK, response14.getStatusCode()); + assertThat(response14.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response14.getBody(), response14.getBody().contains("\"termX\":\"A\"")); Assert.assertFalse(response14.getBody(), response14.getBody().contains("\"termX\":\"B\"")); Assert.assertFalse(response14.getBody(), response14.getBody().contains("\"termX\":\"C\"")); @@ -577,7 +583,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin with setting "min_doc_count":0. Expected to have access to all buckets". HttpResponse response15 = rh.executePostRequest("logs*/_search", query7, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response15.getStatusCode()); + assertThat(response15.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response15.getBody(), response15.getBody().contains("\"termX\":\"A\"")); Assert.assertTrue(response15.getBody(), response15.getBody().contains("\"termX\":\"B\"")); Assert.assertTrue(response15.getBody(), response15.getBody().contains("\"termX\":\"C\"")); @@ -587,7 +593,7 @@ public void testDlsWithMinDocCountZeroAggregations() throws Exception { // Admin without setting "min_doc_count". Expected to have access to all buckets". HttpResponse response16 = rh.executePostRequest("logs*/_search", query8, encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_OK, response16.getStatusCode()); + assertThat(response16.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response16.getBody(), response16.getBody().contains("\"termX\":\"A\"")); Assert.assertTrue(response16.getBody(), response16.getBody().contains("\"termX\":\"B\"")); Assert.assertTrue(response16.getBody(), response16.getBody().contains("\"termX\":\"C\"")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FieldMaskedTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FieldMaskedTest.java index c83388345a..8fcfffc051 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FieldMaskedTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FieldMaskedTest.java @@ -24,6 +24,9 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FieldMaskedTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -74,14 +77,16 @@ public void testMaskedAggregations() throws Exception { + "}" + "}"; - // Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, + // assertThat(HttpStatus.SC_OK, (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, // encodeBasicHeader("admin", "admin"))).getStatusCode()); - // Assert.assertTrue(res.getBody().contains("100.100")); + // Asseis(rt.assertTrue(res.getBody().contains("100.100"));) - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("100.100")); @@ -102,10 +107,12 @@ public void testMaskedAggregations() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("100.100")); @@ -126,10 +133,12 @@ public void testMaskedAggregations() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("100.100")); } @@ -146,9 +155,9 @@ public void testMaskedAggregationsRace() throws Exception { + "}"; HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("100.100")); Assert.assertTrue(res.getBody().contains("200.100")); @@ -158,10 +167,12 @@ public void testMaskedAggregationsRace() throws Exception { Assert.assertFalse(res.getBody().contains("26a8671e57fefc13504f8c61ced67ac98338261ace1e5bf462038b2f2caae16e")); Assert.assertFalse(res.getBody().contains("87873bdb698e5f0f60e0b02b76dad1ec11b2787c628edbc95b7ff0e82274b140")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("user_masked", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"doc_count\" : 30")); Assert.assertTrue(res.getBody().contains("\"doc_count\" : 1")); @@ -172,9 +183,12 @@ public void testMaskedAggregationsRace() throws Exception { Assert.assertTrue(res.getBody().contains("87873bdb698e5f0f60e0b02b76dad1ec11b2787c628edbc95b7ff0e82274b140")); for (int i = 0; i < 10; i++) { - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty&size=0", query, encodeBasicHeader("admin", "admin"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("100.100")); Assert.assertTrue(res.getBody().contains("200.100")); @@ -194,9 +208,9 @@ public void testMaskedSearch() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 32,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -206,9 +220,9 @@ public void testMaskedSearch() throws Exception { Assert.assertTrue(res.getBody().contains("100.100.2.2")); Assert.assertFalse(res.getBody().contains("87873bdb698e5f0f60e0b02b76dad1ec11b2787c628edbc95b7ff0e82274b140")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("user_masked", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("user_masked", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 32,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -228,9 +242,9 @@ public void testMaskedSearchWithClusterDefaultSHA512() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 32,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -241,9 +255,9 @@ public void testMaskedSearchWithClusterDefaultSHA512() throws Exception { Assert.assertFalse(res.getBody().contains("87873bdb698e5f0f60e0b02b76dad1ec11b2787c628edbc95b7ff0e82274b140")); Assert.assertFalse(res.getBody().contains(DigestUtils.sha512Hex("100.100.1.1"))); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("user_masked", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=100", encodeBasicHeader("user_masked", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 32,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -263,9 +277,9 @@ public void testMaskedGet() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -274,9 +288,9 @@ public void testMaskedGet() throws Exception { Assert.assertFalse(res.getBody().contains("100.100.2.2")); Assert.assertFalse(res.getBody().contains("87873bdb698e5f0f60e0b02b76dad1ec11b2787c628edbc95b7ff0e82274b140")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("user_masked", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("user_masked", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -294,9 +308,9 @@ public void testMaskedGetWithClusterDefaultSHA512() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -307,9 +321,9 @@ public void testMaskedGetWithClusterDefaultSHA512() throws Exception { Assert.assertFalse(res.getBody().contains(DigestUtils.sha3_224Hex("100.100.1.1"))); Assert.assertFalse(res.getBody().contains(DigestUtils.sha512Hex("100.100.1.1"))); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("user_masked", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("user_masked", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); @@ -330,9 +344,9 @@ public void testMaskedGetWithClusterDefaultSHA3() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -343,9 +357,9 @@ public void testMaskedGetWithClusterDefaultSHA3() throws Exception { Assert.assertFalse(res.getBody().contains(DigestUtils.sha3_224Hex("100.100.1.1"))); Assert.assertFalse(res.getBody().contains(DigestUtils.sha512Hex("100.100.1.1"))); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("user_masked", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("user_masked", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/Fls983Test.java b/src/test/java/org/opensearch/security/dlic/dlsfls/Fls983Test.java index c17b5c9f0c..fb10cdce9c 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/Fls983Test.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/Fls983Test.java @@ -22,6 +22,9 @@ import org.opensearch.security.test.DynamicSecurityConfig; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class Fls983Test extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -38,10 +41,12 @@ public void test() throws Exception { String doc = "{\"doc\" : {" + "\"x\" : \"y\"" + "}}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/.kibana/_update/0?pretty", doc, encodeBasicHeader("human_resources_trainee", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/.kibana/_update/0?pretty", doc, encodeBasicHeader("human_resources_trainee", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("updated")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestAB.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestAB.java index 33b8296814..ff65381f44 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestAB.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestAB.java @@ -23,6 +23,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsDlsTestAB extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -75,9 +78,9 @@ public void testDlsFlsAB() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/aaa,bbb/_search?pretty", encodeBasicHeader("user_aaa", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/aaa,bbb/_search?pretty", encodeBasicHeader("user_aaa", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -91,9 +94,9 @@ public void testDlsFlsAB() throws Exception { Assert.assertTrue(res.getBody().contains("f3_b")); Assert.assertFalse(res.getBody().contains("f1_b")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/abalias/_search?pretty", encodeBasicHeader("user_aaa", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/abalias/_search?pretty", encodeBasicHeader("user_aaa", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -107,9 +110,9 @@ public void testDlsFlsAB() throws Exception { Assert.assertTrue(res.getBody().contains("f3_b")); Assert.assertFalse(res.getBody().contains("f1_b")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/aaa,bbb/_search?pretty", encodeBasicHeader("user_bbb", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/aaa,bbb/_search?pretty", encodeBasicHeader("user_bbb", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -123,9 +126,9 @@ public void testDlsFlsAB() throws Exception { Assert.assertFalse(res.getBody().contains("f3_b")); Assert.assertTrue(res.getBody().contains("f1_b")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/abalias/_search?pretty", encodeBasicHeader("user_bbb", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/abalias/_search?pretty", encodeBasicHeader("user_bbb", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestForbiddenField.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestForbiddenField.java index fd164802d3..c75c31bcb0 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestForbiddenField.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestForbiddenField.java @@ -21,6 +21,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsDlsTestForbiddenField extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -56,18 +59,20 @@ public void testDlsAggregations() throws Exception { + "}"; HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_fls_dls", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_fls_dls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"value\" : 0")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"value\" : 1510.0")); @@ -80,17 +85,19 @@ public void testDls() throws Exception { setup(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("dept_manager_fls_dls", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("dept_manager_fls_dls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -109,10 +116,12 @@ public void testDls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_fls_dls", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_fls_dls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -131,25 +140,29 @@ public void testDls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_fls_dls", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_fls_dls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?q=amount:10&pretty", encodeBasicHeader("dept_manager_fls_dls", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?q=amount:10&pretty", encodeBasicHeader("dept_manager_fls_dls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 0,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -166,16 +179,16 @@ public void testDls() throws Exception { res = rh.executeGetRequest("/deals/_doc/1?pretty", encodeBasicHeader("dept_manager_fls_dls", "password")); Assert.assertTrue(res.getBody().contains("\"found\" : false")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"count\" : 2,")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("dept_manager_fls_dls", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("dept_manager_fls_dls", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"count\" : 0,")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -188,9 +201,9 @@ public void testCombined() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("user_combined", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("user_combined", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestMulti.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestMulti.java index 5cc9f7423a..c32cc9414a 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestMulti.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsDlsTestMulti.java @@ -21,6 +21,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsDlsTestMulti extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -66,18 +69,20 @@ public void testDlsAggregations() throws Exception { + "}"; HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 3,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"value\" : 1710.0")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"value\" : 21711.0")); @@ -91,25 +96,27 @@ public void testDlsFls() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager_multi", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager_multi", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("ctype")); Assert.assertFalse(res.getBody().contains("secret")); Assert.assertTrue(res.getBody().contains("zip")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 3,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=0", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -128,10 +135,12 @@ public void testDlsFls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -150,25 +159,29 @@ public void testDlsFls() throws Exception { + "}" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?q=amount:10&pretty", encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?q=amount:10&pretty", encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -182,16 +195,16 @@ public void testDlsFls() throws Exception { res = rh.executeGetRequest("/deals/_doc/1?pretty", encodeBasicHeader("dept_manager_multi", "password")); Assert.assertTrue(res.getBody().contains("\"found\" : true")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"count\" : 4,")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("dept_manager_multi", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_count?pretty", encodeBasicHeader("dept_manager_multi", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"count\" : 3,")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -205,10 +218,12 @@ public void testDlsFls() throws Exception { // "{\"index\":\".opendistro_security\", \"type\":\"_doc\", \"ignore_unavailable\": true}"+System.lineSeparator()+ // "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}"+System.lineSeparator(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody(), res.getBody().contains("\"value\" : 3,\n \"relation")); Assert.assertFalse(res.getBody().contains("_opendistro_security_dls_query")); @@ -240,9 +255,9 @@ public void testDlsFls() throws Exception { + "]" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("dept_manager_multi", "password"))).getStatusCode() + is((res = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("dept_manager_multi", "password"))).getStatusCode()) ); Assert.assertFalse(res.getBody().contains("_opendistro_security_dls_query")); Assert.assertFalse(res.getBody().contains("_opendistro_security_fls_fields")); @@ -281,16 +296,18 @@ public void testDlsSuggest() throws Exception { + " }" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("thesuggestion")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("thesuggestion")); } @@ -314,16 +331,18 @@ public void testDlsSuggestOnly() throws Exception { + " }" + "}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("thesuggestion")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) - .getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("dept_manager_multi", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("thesuggestion")); } diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsExistsFieldsTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsExistsFieldsTest.java index b58b80368a..c937cc8734 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsExistsFieldsTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsExistsFieldsTest.java @@ -22,6 +22,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsExistsFieldsTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -105,9 +108,9 @@ public void testExistsField() throws Exception { + "}"; HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/data/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/data/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("a-normal-0")); @@ -116,9 +119,9 @@ public void testExistsField() throws Exception { // only see's - timestamp and host field // therefore non-existing does not exist so we expect c-missing2-0 to be returned - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/data/_search?pretty", query, encodeBasicHeader("fls_exists", "password"))).getStatusCode() + is((res = rh.executePostRequest("/data/_search?pretty", query, encodeBasicHeader("fls_exists", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("a-normal-0")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsTest.java index 5681479085..8fa0da9708 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsTest.java @@ -25,6 +25,9 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsFieldsTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -56,18 +59,18 @@ public void testFields() throws Exception { String query = FileHelper.loadFile("dlsfls/flsquery.json"); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("secret")); Assert.assertTrue(res.getBody().contains("@timestamp")); Assert.assertTrue(res.getBody().contains("\"timestamp")); Assert.assertTrue(res.getBody().contains("numfield5")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("fls_fields", "password"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("fls_fields", "password"))).getStatusCode()) ); Assert.assertFalse(res.getBody().contains("customer")); Assert.assertFalse(res.getBody().contains("secret")); @@ -82,17 +85,20 @@ public void testFields2() throws Exception { String query = FileHelper.loadFile("dlsfls/flsquery2.json"); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty=true", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty=true", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("secret")); Assert.assertTrue(res.getBody().contains("@timestamp")); Assert.assertTrue(res.getBody().contains("\"timestamp")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty=true", query, encodeBasicHeader("fls_fields", "password"))).getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty=true", query, encodeBasicHeader("fls_fields", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("customer")); Assert.assertFalse(res.getBody().contains("secret")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsWcTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsWcTest.java index 2c3235cf27..da544b861f 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsWcTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsFieldsWcTest.java @@ -25,6 +25,9 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsFieldsWcTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -56,17 +59,20 @@ public void testFields() throws Exception { String query = FileHelper.loadFile("dlsfls/flsquery.json"); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("secret")); Assert.assertTrue(res.getBody().contains("@timestamp")); Assert.assertTrue(res.getBody().contains("\"timestamp")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("fls_fields_wc", "password"))).getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("fls_fields_wc", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("customer")); Assert.assertFalse(res.getBody().contains("secret")); @@ -81,17 +87,20 @@ public void testFields2() throws Exception { String query = FileHelper.loadFile("dlsfls/flsquery2.json"); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("secret")); Assert.assertTrue(res.getBody().contains("@timestamp")); Assert.assertTrue(res.getBody().contains("\"timestamp")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("fls_fields_wc", "password"))).getStatusCode() + is( + (res = rh.executePostRequest("/deals/_search?pretty", query, encodeBasicHeader("fls_fields_wc", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("customer")); Assert.assertFalse(res.getBody().contains("secret")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsPerfTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsPerfTest.java index 81553662fd..e756f53e12 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsPerfTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsPerfTest.java @@ -29,6 +29,9 @@ import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + @Ignore public class FlsPerfTest extends AbstractDlsFlsTest { @@ -90,9 +93,9 @@ public void testFlsPerfNamed() throws Exception { StopWatch sw = new StopWatch("testFlsPerfNamed"); sw.start("non fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is(is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode())) ); sw.stop(); Assert.assertTrue(res.getBody().contains("field1\"")); @@ -101,10 +104,12 @@ public void testFlsPerfNamed() throws Exception { Assert.assertTrue(res.getBody().contains("field997\"")); sw.start("with fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_only", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_only", "password"))) + .getStatusCode() + ) ); sw.stop(); Assert.assertFalse(res.getBody().contains("field1\"")); @@ -114,10 +119,12 @@ public void testFlsPerfNamed() throws Exception { sw.start("with fls 2 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_only", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_only", "password"))) + .getStatusCode() + ) ); sw.stop(); @@ -128,10 +135,12 @@ public void testFlsPerfNamed() throws Exception { sw.start("with fls 3 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_only", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_only", "password"))) + .getStatusCode() + ) ); sw.stop(); @@ -150,9 +159,9 @@ public void testFlsPerfWcEx() throws Exception { StopWatch sw = new StopWatch("testFlsPerfWcEx"); sw.start("non fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is(is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode())) ); sw.stop(); Assert.assertTrue(res.getBody().contains("field1\"")); @@ -161,9 +170,14 @@ public void testFlsPerfWcEx() throws Exception { Assert.assertTrue(res.getBody().contains("field997\"")); sw.start("with fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_ex", "password"))).getStatusCode() + is( + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_ex", "password"))) + .getStatusCode() + ) + ) ); sw.stop(); Assert.assertTrue(res.getBody().contains("field1\"")); @@ -173,9 +187,14 @@ public void testFlsPerfWcEx() throws Exception { sw.start("with fls 2 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_ex", "password"))).getStatusCode() + is( + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_ex", "password"))) + .getStatusCode() + ) + ) ); sw.stop(); @@ -186,9 +205,9 @@ public void testFlsPerfWcEx() throws Exception { sw.start("with fls 3 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_ex", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_ex", "password"))).getStatusCode()) ); sw.stop(); @@ -207,9 +226,9 @@ public void testFlsPerfNamedEx() throws Exception { StopWatch sw = new StopWatch("testFlsPerfNamedEx"); sw.start("non fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); sw.stop(); Assert.assertTrue(res.getBody().contains("field1\"")); @@ -218,9 +237,12 @@ public void testFlsPerfNamedEx() throws Exception { Assert.assertTrue(res.getBody().contains("field997\"")); sw.start("with fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_ex", "password"))).getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_ex", "password"))) + .getStatusCode() + ) ); sw.stop(); Assert.assertTrue(res.getBody().contains("field1\"")); @@ -230,9 +252,12 @@ public void testFlsPerfNamedEx() throws Exception { sw.start("with fls 2 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_ex", "password"))).getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_ex", "password"))) + .getStatusCode() + ) ); sw.stop(); @@ -243,9 +268,12 @@ public void testFlsPerfNamedEx() throws Exception { sw.start("with fls 3 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_ex", "password"))).getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_named_ex", "password"))) + .getStatusCode() + ) ); sw.stop(); @@ -264,9 +292,9 @@ public void testFlsWcIn() throws Exception { StopWatch sw = new StopWatch("testFlsWcIn"); sw.start("non fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); sw.stop(); Assert.assertTrue(res.getBody().contains("field1\"")); @@ -275,9 +303,9 @@ public void testFlsWcIn() throws Exception { Assert.assertTrue(res.getBody().contains("field997\"")); sw.start("with fls"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_in", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_in", "password"))).getStatusCode()) ); sw.stop(); Assert.assertFalse(res.getBody().contains("field0\"")); @@ -286,9 +314,9 @@ public void testFlsWcIn() throws Exception { sw.start("with fls 2 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_in", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_in", "password"))).getStatusCode()) ); sw.stop(); @@ -298,9 +326,9 @@ public void testFlsWcIn() throws Exception { sw.start("with fls 3 after warmup"); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_in", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty&size=1000", encodeBasicHeader("perf_wc_in", "password"))).getStatusCode()) ); sw.stop(); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsTest.java index a2787af61c..0d765964cc 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/FlsTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/FlsTest.java @@ -21,6 +21,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlsTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -47,9 +50,9 @@ public void testFieldCapabilities() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_field_caps?fields=*&pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_field_caps?fields=*&pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("customer")); Assert.assertTrue(res.getBody().contains("customer.name")); @@ -58,10 +61,12 @@ public void testFieldCapabilities() throws Exception { Assert.assertTrue(res.getBody().contains("amount")); Assert.assertTrue(res.getBody().contains("secret")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_field_caps?fields=*&pretty", encodeBasicHeader("dept_manager_fls", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_field_caps?fields=*&pretty", encodeBasicHeader("dept_manager_fls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("customer")); Assert.assertTrue(res.getBody().contains("customer.name")); @@ -70,12 +75,14 @@ public void testFieldCapabilities() throws Exception { Assert.assertFalse(res.getBody().contains("amount")); Assert.assertFalse(res.getBody().contains("secret")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - "/deals/_field_caps?fields=*&pretty", - encodeBasicHeader("dept_manager_fls_reversed_fields", "password") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + "/deals/_field_caps?fields=*&pretty", + encodeBasicHeader("dept_manager_fls_reversed_fields", "password") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("customer")); Assert.assertFalse(res.getBody().contains("customer.name")); @@ -92,9 +99,9 @@ public void testMapping() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_mapping?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_mapping?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("customer")); Assert.assertTrue(res.getBody().contains("name")); @@ -103,9 +110,9 @@ public void testMapping() throws Exception { Assert.assertTrue(res.getBody().contains("amount")); Assert.assertTrue(res.getBody().contains("secret")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_mapping?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_mapping?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("customer")); Assert.assertTrue(res.getBody().contains("name")); @@ -114,10 +121,12 @@ public void testMapping() throws Exception { Assert.assertFalse(res.getBody().contains("amount")); Assert.assertFalse(res.getBody().contains("secret")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_mapping?pretty", encodeBasicHeader("dept_manager_fls_reversed_fields", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_mapping?pretty", encodeBasicHeader("dept_manager_fls_reversed_fields", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("customer")); Assert.assertFalse(res.getBody().contains("name")); @@ -134,9 +143,9 @@ public void testFlsSearch() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -147,9 +156,9 @@ public void testFlsSearch() throws Exception { Assert.assertTrue(res.getBody().contains("amount")); Assert.assertTrue(res.getBody().contains("secret")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -160,10 +169,12 @@ public void testFlsSearch() throws Exception { Assert.assertFalse(res.getBody().contains("amount")); Assert.assertFalse(res.getBody().contains("secret")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager_fls_reversed_fields", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_search?pretty", encodeBasicHeader("dept_manager_fls_reversed_fields", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -182,9 +193,9 @@ public void testFlsGet() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -193,9 +204,9 @@ public void testFlsGet() throws Exception { Assert.assertFalse(res.getBody().contains("ctype")); Assert.assertTrue(res.getBody().contains("amount")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/deals/_doc/0?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -204,10 +215,12 @@ public void testFlsGet() throws Exception { Assert.assertFalse(res.getBody().contains("ctype")); Assert.assertFalse(res.getBody().contains("amount")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/deals/_doc/0?realtime=true&pretty", encodeBasicHeader("dept_manager_fls", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/deals/_doc/0?realtime=true&pretty", encodeBasicHeader("dept_manager_fls", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertTrue(res.getBody().contains("cust1")); @@ -216,12 +229,14 @@ public void testFlsGet() throws Exception { Assert.assertFalse(res.getBody().contains("ctype")); Assert.assertFalse(res.getBody().contains("amount")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - "/deals/_doc/0?realtime=true&pretty", - encodeBasicHeader("dept_manager_fls_reversed_fields", "password") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + "/deals/_doc/0?realtime=true&pretty", + encodeBasicHeader("dept_manager_fls_reversed_fields", "password") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"found\" : true")); Assert.assertFalse(res.getBody().contains("cust1")); @@ -239,21 +254,28 @@ public void testFlsUpdate() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("/deals/_update/0?pretty", "{\"doc\": {\"zip\": \"98765\"}}", encodeBasicHeader("admin", "admin"))) - .getStatusCode() + is( + (res = rh.executePostRequest( + "/deals/_update/0?pretty", + "{\"doc\": {\"zip\": \"98765\"}}", + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"_version\" : 2")); Assert.assertFalse(res.getBody(), res.getBody().contains("\"successful\" : 0")); - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - (res = rh.executePostRequest( - "/deals/_update/0?pretty", - "{\"doc\": {\"zip\": \"98765000\"}}", - encodeBasicHeader("dept_manager_fls", "password") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/deals/_update/0?pretty", + "{\"doc\": {\"zip\": \"98765000\"}}", + encodeBasicHeader("dept_manager_fls", "password") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("Update is not supported")); } @@ -265,13 +287,15 @@ public void testFlsUpdateIndex() throws Exception { HttpResponse res = null; - Assert.assertEquals( + assertThat( HttpStatus.SC_INTERNAL_SERVER_ERROR, - (res = rh.executePostRequest( - "/deals/_update/0?pretty", - "{\"doc\": {\"zip\": \"98765000\"}}", - encodeBasicHeader("dept_manager_fls", "password") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "/deals/_update/0?pretty", + "{\"doc\": {\"zip\": \"98765000\"}}", + encodeBasicHeader("dept_manager_fls", "password") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("Update is not supported")); } diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/IndexPatternTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/IndexPatternTest.java index 29b1a44bcb..e6f4e0285b 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/IndexPatternTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/IndexPatternTest.java @@ -21,6 +21,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class IndexPatternTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -50,9 +53,9 @@ public void testSearch() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-2016/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/logstash-2016/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -61,10 +64,12 @@ public void testSearch() throws Exception { Assert.assertTrue(res.getBody().contains("mymsg")); Assert.assertTrue(res.getBody().contains("msgid")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-2016/_search?pretty", encodeBasicHeader("opendistro_security_logstash", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/logstash-2016/_search?pretty", encodeBasicHeader("opendistro_security_logstash", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 1,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -81,20 +86,25 @@ public void testFieldCaps() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-2016/_field_caps?fields=*&pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is( + (res = rh.executeGetRequest("/logstash-2016/_field_caps?fields=*&pretty", encodeBasicHeader("admin", "admin"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("ipaddr")); Assert.assertTrue(res.getBody().contains("message")); Assert.assertTrue(res.getBody().contains("msgid")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - "/logstash-2016/_field_caps?fields=*&pretty", - encodeBasicHeader("opendistro_security_logstash", "password") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + "/logstash-2016/_field_caps?fields=*&pretty", + encodeBasicHeader("opendistro_security_logstash", "password") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("ipaddr")); Assert.assertFalse(res.getBody().contains("message")); @@ -108,9 +118,9 @@ public void testSearchWc() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -119,10 +129,12 @@ public void testSearchWc() throws Exception { Assert.assertTrue(res.getBody().contains("mymsg")); Assert.assertTrue(res.getBody().contains("msgid")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("opendistro_security_logstash", "password"))) - .getStatusCode() + is( + (res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("opendistro_security_logstash", "password"))) + .getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -139,9 +151,9 @@ public void testSearchWcRegex() throws Exception { HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode() + is((res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("admin", "admin"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 4,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -150,9 +162,9 @@ public void testSearchWcRegex() throws Exception { Assert.assertTrue(res.getBody().contains("mymsg")); Assert.assertTrue(res.getBody().contains("msgid")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("regex", "password"))).getStatusCode() + is((res = rh.executeGetRequest("/logstash-20*/_search?pretty", encodeBasicHeader("regex", "password"))).getStatusCode()) ); Assert.assertTrue(res.getBody().contains("\"value\" : 2,\n \"relation")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); diff --git a/src/test/java/org/opensearch/security/dlic/dlsfls/MFlsTest.java b/src/test/java/org/opensearch/security/dlic/dlsfls/MFlsTest.java index f5408113b6..c52e9d5bb7 100644 --- a/src/test/java/org/opensearch/security/dlic/dlsfls/MFlsTest.java +++ b/src/test/java/org/opensearch/security/dlic/dlsfls/MFlsTest.java @@ -21,6 +21,9 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class MFlsTest extends AbstractDlsFlsTest { protected void populateData(Client tc) { @@ -51,9 +54,12 @@ public void testFlsMGetSearch() throws Exception { HttpResponse res; // normal search - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest("deals,finance/_search?pretty", encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode() + is( + (res = rh.executeGetRequest("deals,finance/_search?pretty", encodeBasicHeader("dept_manager_fls", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("_opendistro_security_")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -76,9 +82,12 @@ public void testFlsMGetSearch() throws Exception { + System.lineSeparator(); // msearch - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode() + is( + (res = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("dept_manager_fls", "password"))) + .getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("_opendistro_security_")); Assert.assertTrue(res.getBody().contains("\"failed\" : 0")); @@ -103,9 +112,9 @@ public void testFlsMGetSearch() throws Exception { + "}"; // mget - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode() + is((res = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("dept_manager_fls", "password"))).getStatusCode()) ); Assert.assertFalse(res.getBody().contains("_opendistro_security_")); Assert.assertTrue(res.getBody().contains("\"found\" : true")); diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AbstractApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AbstractApiActionValidationTest.java index e6c4bb17d0..065df4e5a5 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AbstractApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AbstractApiActionValidationTest.java @@ -37,7 +37,8 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @@ -112,13 +113,13 @@ protected CType getConfigType() { }.createEndpointValidator(); var result = defaultPessimisticValidator.onConfigChange(SecurityConfiguration.of(null, configuration)); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); result = defaultPessimisticValidator.onConfigDelete(SecurityConfiguration.of(null, configuration)); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); result = defaultPessimisticValidator.onConfigLoad(SecurityConfiguration.of(null, configuration)); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AbstractRestApiUnitTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AbstractRestApiUnitTest.java index c3c2106b05..989e9933e9 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AbstractRestApiUnitTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AbstractRestApiUnitTest.java @@ -32,6 +32,8 @@ import org.opensearch.security.test.helper.rest.RestHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_SCORE_BASED_VALIDATION_STRENGTH; public abstract class AbstractRestApiUnitTest extends SingleClusterTest { @@ -115,7 +117,7 @@ protected void deleteUser(String username) throws Exception { boolean sendAdminCertificate = rh.sendAdminCertificate; rh.sendAdminCertificate = true; HttpResponse response = rh.executeDeleteRequest("/_opendistro/_security/api/internalusers/" + username, new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); rh.sendAdminCertificate = sendAdminCertificate; } @@ -131,7 +133,7 @@ protected void addUserWithPassword(String username, String password, int status, "{\"password\": \"" + password + "\"}", new Header[0] ); - Assert.assertEquals(status, response.getStatusCode()); + assertThat(response.getStatusCode(), is(status)); rh.sendAdminCertificate = sendAdminCertificate; if (Objects.nonNull(message)) { Assert.assertTrue(response.getBody().contains(message)); @@ -150,7 +152,7 @@ protected void addUserWithPassword(String username, String password, String[] ro } payload += "]}"; HttpResponse response = rh.executePutRequest("/_opendistro/_security/api/internalusers/" + username, payload, new Header[0]); - Assert.assertEquals(status, response.getStatusCode()); + assertThat(response.getStatusCode(), is(status)); rh.sendAdminCertificate = sendAdminCertificate; } @@ -166,7 +168,7 @@ protected void addUserWithoutPasswordOrHash(String username, String[] roles, int } payload += "]}"; HttpResponse response = rh.executePutRequest("/_opendistro/_security/api/internalusers/" + username, payload, new Header[0]); - Assert.assertEquals(status, response.getStatusCode()); + assertThat(response.getStatusCode(), is(status)); rh.sendAdminCertificate = sendAdminCertificate; } @@ -182,7 +184,7 @@ protected void addUserWithHash(String username, String hash, int status) throws "{\"hash\": \"" + hash + "\"}", new Header[0] ); - Assert.assertEquals(status, response.getStatusCode()); + assertThat(response.getStatusCode(), is(status)); rh.sendAdminCertificate = sendAdminCertificate; } @@ -194,14 +196,14 @@ protected void addUserWithPasswordAndHash(String username, String password, Stri "{\"hash\": \"" + hash + "\", \"password\": \"" + password + "\"}", new Header[0] ); - Assert.assertEquals(status, response.getStatusCode()); + assertThat(response.getStatusCode(), is(status)); rh.sendAdminCertificate = sendAdminCertificate; } protected void checkGeneralAccess(int status, String username, String password) throws Exception { boolean sendAdminCertificate = rh.sendAdminCertificate; rh.sendAdminCertificate = false; - Assert.assertEquals(status, rh.executeGetRequest("", encodeBasicHeader(username, password)).getStatusCode()); + assertThat(rh.executeGetRequest("", encodeBasicHeader(username, password)).getStatusCode(), is(status)); rh.sendAdminCertificate = sendAdminCertificate; } @@ -211,7 +213,7 @@ protected String checkReadAccess(int status, String username, String password, S String action = indexName + "/" + actionType + "/" + id; HttpResponse response = rh.executeGetRequest(action, encodeBasicHeader(username, password)); int returnedStatus = response.getStatusCode(); - Assert.assertEquals(status, returnedStatus); + assertThat(returnedStatus, is(status)); return response.getBody(); } @@ -223,7 +225,7 @@ protected String checkWriteAccess(int status, String username, String password, String payload = "{\"value\" : \"true\"}"; HttpResponse response = rh.executePutRequest(action, payload, encodeBasicHeader(username, password)); int returnedStatus = response.getStatusCode(); - Assert.assertEquals(response.getBody(), status, returnedStatus); + assertThat(response.getBody(), returnedStatus, is(status)); return response.getBody(); } @@ -237,15 +239,12 @@ protected void setupStarfleetIndex() throws Exception { } protected void assertHealthy() throws Exception { - Assert.assertEquals(HttpStatus.SC_OK, rh.executeGetRequest("_opendistro/_security/health?pretty").getStatusCode()); - Assert.assertEquals( + assertThat(rh.executeGetRequest("_opendistro/_security/health?pretty").getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("admin", "admin")).getStatusCode() - ); - Assert.assertEquals( - HttpStatus.SC_OK, - rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("admin", "admin")).getStatusCode() + is(rh.executeGetRequest("_opendistro/_security/authinfo?pretty", encodeBasicHeader("admin", "admin")).getStatusCode()) ); + assertThat(HttpStatus.SC_OK, is(rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("admin", "admin")).getStatusCode())); } String createRestAdminPermissionsPayload(String... additionPerms) throws JsonProcessingException { diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiActionValidationTest.java index 908448f91b..72d77b9a68 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/ActionGroupsApiActionValidationTest.java @@ -18,7 +18,8 @@ import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -45,7 +46,7 @@ public void hasNoRightsToChangeImmutableEntityFoAdminUser() throws Exception { SecurityConfiguration.of("ag", configuration) ); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -62,7 +63,7 @@ public void hasNoRightsToChangeImmutableEntityForRegularUser() throws Exception SecurityConfiguration.of("ag", configuration) ); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -78,8 +79,8 @@ public void onConfigChangeActionGroupHasSameNameAsRole() throws Exception { final var result = actionGroupsApiActionEndpointValidator.onConfigChange(SecurityConfiguration.of(ag,"kibana_read_only", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.BAD_REQUEST, result.status()); - assertEquals("kibana_read_only is an existing role. A action group cannot be named with an existing role name.", xContentToJsonNode(result.errorMessage()).get("message").asText()); + assertThat(result.status(), is(RestStatus.BAD_REQUEST)); + assertThat(xContentToJsonNode(result.errorMessage()).get("message").asText(), is("kibana_read_only is an existing role. A action group cannot be named with an existing role name.")); } @Test @@ -96,8 +97,8 @@ public void onConfigChangeActionGroupHasSelfReference() throws Exception { final var result = actionGroupsApiActionEndpointValidator .onConfigChange(SecurityConfiguration.of(ag,"ag", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.BAD_REQUEST, result.status()); - assertEquals("ag cannot be an allowed_action of itself", xContentToJsonNode(result.errorMessage()).get("message").asText()); + assertThat(result.status(), is(RestStatus.BAD_REQUEST)); + assertThat(xContentToJsonNode(result.errorMessage()).get("message").asText(), is("ag cannot be an allowed_action of itself")); } @Test @@ -114,8 +115,8 @@ public void validateInvalidType() throws Exception { final var result = actionGroupsApiActionEndpointValidator .onConfigChange(SecurityConfiguration.of(ag,"ag", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.BAD_REQUEST, result.status()); - assertEquals("Invalid action group type: some_type_we_know_nothing_about. Supported types are: cluster, index.", xContentToJsonNode(result.errorMessage()).get("message").asText()); + assertThat(result.status(), is(RestStatus.BAD_REQUEST)); + assertThat(xContentToJsonNode(result.errorMessage()).get("message").asText(), is("Invalid action group type: some_type_we_know_nothing_about. Supported types are: cluster, index.")); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AllowlistApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AllowlistApiTest.java index 567421e426..ff8c1b9ce3 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AllowlistApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AllowlistApiTest.java @@ -34,8 +34,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_ADMIN_ENABLED; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** @@ -70,9 +70,9 @@ private void checkGetAndPutAllowlistPermissions(final int expectedStatus, final assertThat(response.getBody(), response.getStatusCode(), equalTo(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { // Note: the response has no whitespaces, so the .json file does not have whitespaces - Assert.assertEquals( + assertThat( FileHelper.loadFile("restapi/whitelist_response_success.json"), - FileHelper.loadFile("restapi/whitelist_response_success.json") + is(FileHelper.loadFile("restapi/whitelist_response_success.json")) ); } // FORBIDDEN FOR NON SUPER ADMIN @@ -97,7 +97,7 @@ public void testResponseDoesNotContainMetaHeader() throws Exception { rh.sendAdminCertificate = true; RestHelper.HttpResponse response = rh.executeGetRequest(ENDPOINT); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(response.getHeaders().contains("_meta")); } @@ -111,7 +111,7 @@ public void testPutUnknownKey() throws Exception { ENDPOINT, "{ \"unknownkey\": true, \"requests\": {\"/_cat/nodes\": [\"GET\"],\"/_cat/indices\": [\"GET\"] }}" ); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); assertTrue(response.getBody().contains("invalid_keys")); assertHealthy(); } @@ -125,7 +125,7 @@ public void testPutInvalidJson() throws Exception { ENDPOINT, "{ \"invalid\"::{{ [\"*\"], \"requests\": {\"/_cat/nodes\": [\"GET\"],\"/_cat/indices\": [\"GET\"] }}" ); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); assertHealthy(); } @@ -140,9 +140,9 @@ public void testPayloadMandatory() throws Exception { rh.sendAdminCertificate = true; response = rh.executePutRequest(ENDPOINT, "", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); JsonNode settings = DefaultObjectMapper.readTree(response.getBody()); - Assert.assertEquals(RequestContentValidator.ValidationError.PAYLOAD_MANDATORY.message(), settings.get("reason").asText()); + assertThat(settings.get("reason").asText(), is(RequestContentValidator.ValidationError.PAYLOAD_MANDATORY.message())); } /** @@ -257,11 +257,11 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"replace\", \"path\": \"/config\", \"value\": {\"enabled\": true, \"requests\": {\"/_cat/nodes\": [\"GET\"],\"/_cat/indices\": [\"PUT\"] }}}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); - assertEquals( + assertThat( response.getBody(), - "{\"config\":{\"enabled\":true,\"requests\":{\"/_cat/nodes\":[\"GET\"],\"/_cat/indices\":[\"PUT\"]}}}" + is("{\"config\":{\"enabled\":true,\"requests\":{\"/_cat/nodes\":[\"GET\"],\"/_cat/indices\":[\"PUT\"]}}}") ); // PATCH just requests @@ -270,7 +270,7 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"replace\", \"path\": \"/config/requests\", \"value\": {\"/_cat/nodes\": [\"GET\"]}}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); assertTrue(response.getBody().contains("\"requests\":{\"/_cat/nodes\":[\"GET\"]}")); @@ -280,19 +280,19 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"replace\", \"path\": \"/config/enabled\", \"value\": false}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); assertTrue(response.getBody().contains("\"enabled\":false")); // PATCH just enabled using "add" operation when it is currently false - works correctly response = rh.executePatchRequest(ENDPOINT, "[{ \"op\": \"add\", \"path\": \"/config/enabled\", \"value\": true}]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); assertTrue(response.getBody().contains("\"enabled\":true")); // PATCH just enabled using "add" operation when it is currently true - works correctly response = rh.executePatchRequest(ENDPOINT, "[{ \"op\": \"add\", \"path\": \"/config/enabled\", \"value\": false}]", new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); assertTrue(response.getBody().contains("\"enabled\":false")); diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionRequestContentValidatorTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionRequestContentValidatorTest.java index bc43b3a56a..644d962589 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionRequestContentValidatorTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionRequestContentValidatorTest.java @@ -28,7 +28,8 @@ import org.opensearch.security.compliance.ComplianceConfig; import org.opensearch.security.util.FakeRestRequest; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; public class AuditApiActionRequestContentValidatorTest extends AbstractApiActionValidationTest { @@ -53,7 +54,7 @@ public void validateAuditDisabledRestCategories() throws IOException { final var content = DefaultObjectMapper.writeValueAsString(objectMapper.valueToTree(auditConfig), false); var result = auditApiActionRequestContentValidator.validate(FakeRestRequest.builder().withContent(new BytesArray(content)).build()); assertFalse(result.isValid()); - assertEquals(RestStatus.BAD_REQUEST, result.status()); + assertThat(result.status(), is(RestStatus.BAD_REQUEST)); } @Test @@ -76,6 +77,6 @@ public void validateAuditDisabledTransportCategories() throws IOException { final var content = DefaultObjectMapper.writeValueAsString(objectMapper.valueToTree(auditConfig), false); var result = auditApiActionRequestContentValidator.validate(FakeRestRequest.builder().withContent(new BytesArray(content)).build()); assertFalse(result.isValid()); - assertEquals(RestStatus.BAD_REQUEST, result.status()); + assertThat(result.status(), is(RestStatus.BAD_REQUEST)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java index 929f58c23c..ffc7b4a22d 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionTest.java @@ -13,10 +13,8 @@ import java.io.IOException; import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; @@ -41,10 +39,12 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.DefaultObjectMapper.readTree; import static org.opensearch.security.DefaultObjectMapper.writeValueAsString; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AuditApiActionTest extends AbstractRestApiUnitTest { @@ -87,19 +87,19 @@ public void testInvalidPath() throws Exception { // should have /config for put request response = rh.executePutRequest(ENDPOINT, "{\"xxx\": 1}"); - assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_METHOD_NOT_ALLOWED)); // no post supported response = rh.executePostRequest(ENDPOINT, "{\"xxx\": 1}"); - assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_METHOD_NOT_ALLOWED)); // should have /config for patch request response = rh.executePatchRequest(ENDPOINT, "{\"xxx\": 1}"); - assertEquals(response.getBody(), HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getBody(), response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); // no delete supported response = rh.executeDeleteRequest(ENDPOINT); - assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_METHOD_NOT_ALLOWED)); } @Test @@ -119,7 +119,7 @@ public void testDisabledCategoryOrder() throws Exception { List actual = Streams.stream(readTree(response.getBody()).at("/config/audit/disabled_rest_categories").iterator()) .map(JsonNode::textValue) .collect(Collectors.toList()); - assertEquals(testCategories, actual); + assertThat(actual, is(testCategories)); } @Test @@ -135,7 +135,7 @@ public void testInvalidDisabledCategories() throws Exception { ); ObjectNode json = DefaultObjectMapper.objectMapper.valueToTree(auditConfig); RestHelper.HttpResponse response = rh.executePutRequest(CONFIG_ENDPOINT, writeValueAsString(json, false)); - assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); // test success for REST disabled categories auditConfig = new AuditConfig( @@ -157,7 +157,7 @@ public void testInvalidDisabledCategories() throws Exception { ); json = DefaultObjectMapper.objectMapper.valueToTree(auditConfig); response = rh.executePutRequest(CONFIG_ENDPOINT, writeValueAsString(json, false)); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // test bad request for transport disabled categories auditConfig = new AuditConfig( @@ -169,7 +169,7 @@ public void testInvalidDisabledCategories() throws Exception { ); json = DefaultObjectMapper.objectMapper.valueToTree(auditConfig); response = rh.executePutRequest(CONFIG_ENDPOINT, writeValueAsString(json, false)); - assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); // test success for transport disabled categories auditConfig = new AuditConfig( @@ -193,7 +193,7 @@ public void testInvalidDisabledCategories() throws Exception { ); json = DefaultObjectMapper.objectMapper.valueToTree(auditConfig); response = rh.executePutRequest(CONFIG_ENDPOINT, writeValueAsString(json, false)); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test @@ -211,11 +211,11 @@ public void testReadonlyApi() throws Exception { // test get RestHelper.HttpResponse response = rh.executeGetRequest(ENDPOINT, adminCredsHeader); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); List actual = Streams.stream(readTree(response.getBody()).get("_readonly").iterator()) .map(JsonNode::textValue) .collect(Collectors.toList()); - assertEquals(readonlyFields, actual); + assertThat(actual, is(readonlyFields)); // test config final AuditConfig auditConfig = AuditConfig.from(Settings.EMPTY); @@ -261,7 +261,7 @@ private void testPutRequest(final JsonNode json, final int expectedStatus, final throws Exception { rh.sendAdminCertificate = sendAdminCertificate; RestHelper.HttpResponse response = rh.executePutRequest(CONFIG_ENDPOINT, writeValueAsString(json, false), header); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); } private void testReadonlyBoolean(final ObjectNode json, final String config, final String resource) throws Exception { @@ -345,7 +345,7 @@ private void testReadonlyMap(final ObjectNode json, final String config, final S "[{\"op\": \"add\",\"path\": \"" + resourcePath + "\",\"value\": " + writeValueAsString(testMap, false) + "}]", adminCredsHeader ); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); assertTrue(response.getBody().contains("No updates required")); } @@ -397,12 +397,12 @@ public void testBadRequest() throws Exception { ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + "/config/audit/disabled_rest_categories" + "\",\"value\": " + jsonValue + "}]" ); - assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); response = rh.executePatchRequest( ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + "/config/audit/disabled_transport_categories" + "\",\"value\": " + jsonValue + "}]" ); - assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); } @Test @@ -438,17 +438,17 @@ private void testActions(final int expectedStatus, final boolean sendAdminCertif private void testPutAction(final String payload, final int expectedStatus, final Header... headers) throws Exception { RestHelper.HttpResponse response = rh.executePutRequest(CONFIG_ENDPOINT, payload, headers); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { response = rh.executeGetRequest(ENDPOINT, headers); - assertEquals(readTree(payload), readTree(response.getBody()).get("config")); + assertThat(readTree(response.getBody()).get("config"), is(readTree(payload))); } } private void testGetAction(final int expectedStatus, final Header... headers) throws Exception { RestHelper.HttpResponse response = rh.executeGetRequest(ENDPOINT, headers); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { JsonNode jsonNode = readTree(response.getBody()); @@ -518,9 +518,9 @@ private void testBooleanPatch(final String patchResource, final boolean value, f "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": " + value + "}]", headers ); - assertEquals(expected, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expected)); if (expected == HttpStatus.SC_OK) { - assertEquals(value, readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).asBoolean()); + assertThat(readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).asBoolean(), is(value)); } } @@ -545,9 +545,9 @@ private void testList(final String patchResource, final List expectedLis "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": []}]", headers ); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { - assertEquals(0, readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size()); + assertThat(readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size(), is(0)); } // add value @@ -556,7 +556,7 @@ private void testList(final String patchResource, final List expectedLis "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": " + jsonValue + "}]", headers ); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { final JsonNode responseJson = readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()); final List actualList = DefaultObjectMapper.readValue( @@ -564,15 +564,15 @@ private void testList(final String patchResource, final List expectedLis new TypeReference>() { } ); - assertEquals(expectedList.size(), actualList.size()); + assertThat(actualList.size(), is(expectedList.size())); assertTrue(actualList.containsAll(expectedList)); } // check null response = rh.executePatchRequest(ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": []}]", headers); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { - assertEquals(0, readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size()); + assertThat(readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size(), is(0)); } } @@ -590,11 +590,9 @@ private void testMap( "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": {}}]", headers ); - Set expectedSet = new HashSet<>(List.of(expectedStatus)); - expectedSet.add(HttpStatus.SC_BAD_REQUEST); - assertTrue(expectedSet.contains(response.getStatusCode())); + assertThat(response.getStatusCode(), anyOf(is(expectedStatus), is(HttpStatus.SC_BAD_REQUEST))); if (expectedStatus == HttpStatus.SC_OK) { - assertEquals(0, readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size()); + assertThat(readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size(), is(0)); } // add value @@ -603,7 +601,7 @@ private void testMap( "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": " + jsonValue + "}]", headers ); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { final JsonNode responseJson = readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()); final Map> actualMap = DefaultObjectMapper.readValue( @@ -611,14 +609,14 @@ private void testMap( new TypeReference>>() { } ); - assertEquals(actualMap, expectedMap); + assertThat(expectedMap, is(actualMap)); } // check null response = rh.executePatchRequest(ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + patchResource + "\",\"value\": null}]", headers); - assertEquals(expectedStatus, response.getStatusCode()); + assertThat(response.getStatusCode(), is(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { - assertEquals(0, readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size()); + assertThat(readTree(rh.executeGetRequest(ENDPOINT, headers).getBody()).at(patchResource).size(), is(0)); } } @@ -665,26 +663,26 @@ public void testPatchRequest() throws Exception { // update config RestHelper.HttpResponse response = rh.executePutRequest(CONFIG_ENDPOINT, payload); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // make patch request response = rh.executePatchRequest(ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + "/config/enabled" + "\",\"value\": " + false + "}]"); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePatchRequest(ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + "/config/enabled" + "\",\"value\": " + true + "}]"); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePatchRequest(ENDPOINT, "[{\"op\": \"add\",\"path\": \"" + "/config/enabled" + "\",\"value\": " + true + "}]"); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); assertTrue(response.getBody().contains("No updates required")); // get config response = rh.executeGetRequest(ENDPOINT); - assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); final JsonNode configNode = readTree(response.getBody()).get("config"); // verify configs are same - assertEquals(readTree(payload), configNode); + assertThat(configNode, is(readTree(payload))); } private String getTestPayload() { diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionValidationTest.java index 20a450285c..7bf40994bd 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/AuditApiActionValidationTest.java @@ -22,7 +22,8 @@ import org.opensearch.security.securityconf.impl.SecurityDynamicConfiguration; import org.opensearch.security.util.FakeRestRequest; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; @@ -37,7 +38,7 @@ public void disabledAuditApi() { for (final var m : RequestHandler.RequestHandlersBuilder.SUPPORTED_METHODS) { final var result = auditApiAction.withEnabledAuditApi(FakeRestRequest.builder().withMethod(m).build()); assertFalse(result.isValid()); - assertEquals(RestStatus.NOT_IMPLEMENTED, result.status()); + assertThat(result.status(), is(RestStatus.NOT_IMPLEMENTED)); } } @@ -84,6 +85,6 @@ public void onChangeVerifyReadonlyFields() throws Exception { SecurityConfiguration.of(objectMapper.valueToTree(AuditConfig.from(Settings.EMPTY)), "config", dynamicConfiguration) ); assertFalse(result.isValid()); - assertEquals(RestStatus.CONFLICT, result.status()); + assertThat(result.status(), is(RestStatus.CONFLICT)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java index 8defebc6d1..6b5678d822 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/GetConfigurationApiTest.java @@ -21,6 +21,8 @@ import org.opensearch.security.DefaultObjectMapper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; public class GetConfigurationApiTest extends AbstractRestApiUnitTest { @@ -47,38 +49,38 @@ public void testGetConfiguration() throws Exception { // test that every config is accessible // config response = rh.executeGetRequest(ENDPOINT + "/securityconfig"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.getAsBoolean("config.dynamic.authc.authentication_domain_basic_internal.http_enabled", false), true); + assertThat(true, is(settings.getAsBoolean("config.dynamic.authc.authentication_domain_basic_internal.http_enabled", false))); Assert.assertNull(settings.get("_opendistro_security_meta.type")); // internalusers response = rh.executeGetRequest(ENDPOINT + "/internalusers"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("other.hash")); + assertThat(settings.get("admin.hash"), is("")); + assertThat(settings.get("other.hash"), is("")); Assert.assertNull(settings.get("_opendistro_security_meta.type")); // roles response = rh.executeGetRequest(ENDPOINT + "/roles"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); JsonNode jnode = DefaultObjectMapper.readTree(response.getBody()); - Assert.assertEquals(jnode.get("opendistro_security_all_access").get("cluster_permissions").get(0).asText(), "cluster:*"); + assertThat("cluster:*", is(jnode.get("opendistro_security_all_access").get("cluster_permissions").get(0).asText())); Assert.assertNull(settings.get("_opendistro_security_meta.type")); // roles response = rh.executeGetRequest(ENDPOINT + "/rolesmapping"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(0), "starfleet"); + assertThat("starfleet", is(settings.getAsList("opendistro_security_role_starfleet.backend_roles").get(0))); Assert.assertNull(settings.get("_opendistro_security_meta.type")); // action groups response = rh.executeGetRequest(ENDPOINT + "/actiongroups"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(settings.getAsList("ALL.allowed_actions").get(0), "indices:*"); + assertThat("indices:*", is(settings.getAsList("ALL.allowed_actions").get(0))); Assert.assertTrue(settings.hasValue("INTERNAL.allowed_actions")); Assert.assertNull(settings.get("_opendistro_security_meta.type")); } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java index 4632a3920f..fc09ffdae2 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/IndexMissingTest.java @@ -13,7 +13,6 @@ import org.apache.hc.core5.http.Header; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.security.DefaultObjectMapper; @@ -21,6 +20,8 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper.HttpResponse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; public class IndexMissingTest extends AbstractRestApiUnitTest { @@ -52,33 +53,33 @@ protected void testHttpOperations() throws Exception { // GET configuration HttpResponse response = rh.executeGetRequest(ENDPOINT + "/roles"); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); String errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + assertThat(errorString, is("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}")); // GET roles response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + assertThat(errorString, is("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}")); // GET rolesmapping response = rh.executeGetRequest(ENDPOINT + "/rolesmapping/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + assertThat(errorString, is("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}")); // GET actiongroups response = rh.executeGetRequest(ENDPOINT + "/actiongroups/READ"); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + assertThat(errorString, is("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}")); // GET internalusers response = rh.executeGetRequest(ENDPOINT + "/internalusers/picard"); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); errorString = response.getBody(); - Assert.assertEquals("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}", errorString); + assertThat(errorString, is("{\"status\":\"INTERNAL_SERVER_ERROR\",\"message\":\"Security index not initialized\"}")); // PUT request response = rh.executePutRequest( @@ -86,22 +87,22 @@ protected void testHttpOperations() throws Exception { FileHelper.loadFile("restapi/actiongroup_read.json"), new Header[0] ); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); // DELETE request response = rh.executeDeleteRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet", new Header[0]); - Assert.assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_INTERNAL_SERVER_ERROR)); // setup index now initialize(this.clusterHelper, this.clusterInfo); // GET configuration response = rh.executeGetRequest(ENDPOINT + "/roles"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); SecurityJsonNode securityJsonNode = new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())); - Assert.assertEquals( + assertThat( "OPENDISTRO_SECURITY_CLUSTER_ALL", - securityJsonNode.get("opendistro_security_admin").get("cluster_permissions").get(0).asString() + is(securityJsonNode.get("opendistro_security_admin").get("cluster_permissions").get(0).asString()) ); } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/InternalUsersApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/InternalUsersApiActionValidationTest.java index 8e6b5a0bb2..46d115f79e 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/InternalUsersApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/InternalUsersApiActionValidationTest.java @@ -36,7 +36,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -95,7 +95,7 @@ public void replacePasswordWithHash() throws Exception { configuration ); final var result = internalUsersApiActionEndpointValidator.onConfigChange(securityConfiguration); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); assertFalse(securityConfiguration.requestContent().has("password")); assertTrue(securityConfiguration.requestContent().has("hash")); assertTrue(passwordHasher.check("aaaaaa".toCharArray(), securityConfiguration.requestContent().get("hash").asText())); @@ -112,7 +112,7 @@ public void withAuthTokenPath() throws Exception { .build() ); assertFalse(result.isValid()); - assertEquals(RestStatus.NOT_IMPLEMENTED, result.status()); + assertThat(result.status(), is(RestStatus.NOT_IMPLEMENTED)); result = internalUsersApiAction.withAuthTokenPath( FakeRestRequest.builder() @@ -122,7 +122,7 @@ public void withAuthTokenPath() throws Exception { .build() ); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); } @Test @@ -140,7 +140,7 @@ public void validateAndUpdatePassword() throws Exception { SecurityConfiguration.of(objectMapper.createObjectNode(), "aaaa", configuration) ); assertFalse(result.isValid()); - assertEquals(RestStatus.INTERNAL_SERVER_ERROR, result.status()); + assertThat(result.status(), is(RestStatus.INTERNAL_SERVER_ERROR)); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiActionValidationTest.java index 822e29f976..813800797d 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiActionValidationTest.java @@ -15,7 +15,8 @@ import org.opensearch.core.rest.RestStatus; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; public class NodesDnApiActionValidationTest extends AbstractApiActionValidationTest { @@ -31,7 +32,7 @@ public void isNotAllowedToChangeImmutableEntity() throws Exception { ); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java index 8379a80989..39e170331e 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/NodesDnApiTest.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hc.core5.http.Header; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.common.settings.Settings; @@ -36,6 +35,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_ADMIN_ENABLED; @@ -123,8 +123,8 @@ private void checkNullElementsInArray(final Header headers) throws Exception { String body = FileHelper.loadFile("restapi/nodesdn_null_array_element.json"); HttpResponse response = rh.executePutRequest(ENDPOINT + "/nodesdn/cluster1", body, headers); Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); - Assert.assertEquals(RequestContentValidator.ValidationError.NULL_ARRAY_ELEMENT.message(), settings.get("reason")); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); + assertThat(settings.get("reason"), is(RequestContentValidator.ValidationError.NULL_ARRAY_ELEMENT.message())); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RequestHandlersBuilderTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RequestHandlersBuilderTest.java index d49bfbd25c..e380c22a7b 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RequestHandlersBuilderTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RequestHandlersBuilderTest.java @@ -31,7 +31,8 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.reset; @@ -73,9 +74,9 @@ public void checkPermissionsForAllMethodsOnDemand() throws IOException { final var responseBytes = responseArgumentCaptor.getValue(); final var json = DefaultObjectMapper.readTree(responseBytes.content().utf8ToString()); if (method == RestRequest.Method.POST) { - assertEquals(RestStatus.NOT_IMPLEMENTED.name(), json.get("status").asText()); + assertThat(json.get("status").asText(), is(RestStatus.NOT_IMPLEMENTED.name())); } else { - assertEquals(RestStatus.FORBIDDEN.name(), json.get("status").asText()); + assertThat(json.get("status").asText(), is(RestStatus.FORBIDDEN.name())); } reset(channel); } @@ -116,12 +117,12 @@ public void allSupportedMethodsNotImplementedByDefault() { .withSaveOrUpdateConfigurationHandler((client, configuration, indexResponseOnSucessActionListener) -> {}) .build(); - assertEquals( + assertThat( RequestHandler.RequestHandlersBuilder.SUPPORTED_METHODS.stream().sorted().collect(Collectors.toList()), - requestHandlers.keySet().stream().sorted().collect(Collectors.toList()) + is(requestHandlers.keySet().stream().sorted().collect(Collectors.toList())) ); requestHandlers.forEach( - ((method, requestOperationHandler) -> assertEquals(RequestHandler.methodNotImplementedHandler, requestOperationHandler)) + ((method, requestOperationHandler) -> assertThat(requestOperationHandler, is(RequestHandler.methodNotImplementedHandler))) ); } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java index 1f4d0ff247..535bbb247e 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RoleBasedAccessTest.java @@ -25,6 +25,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; public class RoleBasedAccessTest extends AbstractRestApiUnitTest { @@ -53,129 +54,129 @@ public void testActionGroupsApi() throws Exception { // legacy user API, accessible for worf, single user HttpResponse response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Settings settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); Assert.assertTrue(settings.get("admin.hash") != null); - Assert.assertEquals("", settings.get("admin.hash")); + assertThat(settings.get("admin.hash"), is("")); // new user API, accessible for worf, single user response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); Assert.assertTrue(settings.get("admin.hash") != null); // legacy user API, accessible for worf, get complete config response = rh.executeGetRequest(ENDPOINT + "/internalusers/", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); + assertThat(settings.get("admin.hash"), is("")); + assertThat(settings.get("sarek.hash"), is("")); + assertThat(settings.get("worf.hash"), is("")); // new user API, accessible for worf response = rh.executeGetRequest(ENDPOINT + "/internalusers/", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); + assertThat(settings.get("admin.hash"), is("")); + assertThat(settings.get("sarek.hash"), is("")); + assertThat(settings.get("worf.hash"), is("")); // legacy user API, accessible for worf, get complete config, no trailing slash response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); + assertThat(settings.get("admin.hash"), is("")); + assertThat(settings.get("sarek.hash"), is("")); + assertThat(settings.get("worf.hash"), is("")); // new user API, accessible for worf, get complete config, no trailing slash response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.get("admin.hash")); - Assert.assertEquals("", settings.get("sarek.hash")); - Assert.assertEquals("", settings.get("worf.hash")); + assertThat(settings.get("admin.hash"), is("")); + assertThat(settings.get("sarek.hash"), is("")); + assertThat(settings.get("worf.hash"), is("")); // roles API, GET accessible for worf response = rh.executeGetRequest(ENDPOINT + "/rolesmapping", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - Assert.assertEquals("", settings.getAsList("opendistro_security_all_access.users").get(0), "nagilum"); - Assert.assertEquals("", settings.getAsList("opendistro_security_role_starfleet_library.backend_roles").get(0), "starfleet*"); - Assert.assertEquals("", settings.getAsList("opendistro_security_zdummy_all.users").get(0), "bug108"); + assertThat("", "nagilum", is(settings.getAsList("opendistro_security_all_access.users").get(0))); + assertThat("", "starfleet*", is(settings.getAsList("opendistro_security_role_starfleet_library.backend_roles").get(0))); + assertThat("", "bug108", is(settings.getAsList("opendistro_security_zdummy_all.users").get(0))); // Deprecated get configuration API, acessible for sarek // response = rh.executeGetRequest("_opendistro/_security/api/configuration/internalusers", encodeBasicHeader("sarek", "sarek")); // settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - // Assert.assertEquals("", settings.get("admin.hash")); - // Assert.assertEquals("", settings.get("sarek.hash")); - // Assert.assertEquals("", settings.get("worf.hash")); + // assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); + // assertThat(settings.get("admin.hash"), is("")); + // assertThat(settings.get("sarek.hash"), is("")); + // assertThat(settings.get("worf.hash"), is("")); // Deprecated get configuration API, acessible for sarek // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("sarek", "sarek")); // settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - // Assert.assertEquals("", settings.getAsList("ALL").get(0), "indices:*"); - // Assert.assertEquals("", settings.getAsList("OPENDISTRO_SECURITY_CLUSTER_MONITOR").get(0), "cluster:monitor/*"); + // assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); + // assertThat("indices:*", is("", settings.getAsList("ALL").get(0))); + // assertThat("cluster:monitor/*", is("", settings.getAsList("OPENDISTRO_SECURITY_CLUSTER_MONITOR").get(0))); // new format for action groups - // Assert.assertEquals("", settings.getAsList("CRUD.permissions").get(0), "READ_UT"); + // assertThat("READ_UT", is("", settings.getAsList("CRUD.permissions").get(0))); // configuration API, not accessible for worf // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("worf", "worf")); - // Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + // assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CONFIGURATION")); // cache API, not accessible for worf since it's disabled globally response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CACHE")); // cache API, not accessible for sarek since it's disabled globally response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("sarek", "sarek")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any access to endpoint CACHE")); // Admin user has no eligible role at all response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); // Admin user has no eligible role at all response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); // Admin user has no eligible role at all response = rh.executeGetRequest(ENDPOINT + "/internalusers", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); // Admin user has no eligible role at all response = rh.executeGetRequest(ENDPOINT + "/roles", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); // --- DELETE --- // Admin user has no eligible role at all response = rh.executeDeleteRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("admin", "admin")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); Assert.assertTrue(response.getBody().contains("does not have any role privileged for admin access")); // Worf, has access to internalusers API, able to delete response = rh.executeDeleteRequest(ENDPOINT + "/internalusers/other", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("'other' deleted")); // Worf, has access to internalusers API, user "other" deleted now response = rh.executeGetRequest(ENDPOINT + "/internalusers/other", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); Assert.assertTrue(response.getBody().contains("'other' not found")); // Worf, has access to roles API, get captains role response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); assertThat( response.findArrayInJson("opendistro_security_role_starfleet_captains.cluster_permissions"), allOf(hasItem("*bulk*"), hasItem("cluster:monitor*")) @@ -186,21 +187,21 @@ public void testActionGroupsApi() throws Exception { ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' deleted")); // Worf, has access to roles API, captains role deleted now response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' not found")); // Worf, has no DELETE access to rolemappings API response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_unittest_1", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // Worf, has no DELETE access to rolemappings API, legacy endpoint response = rh.executeDeleteRequest(ENDPOINT + "/rolesmapping/opendistro_security_unittest_1", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // --- PUT --- @@ -210,7 +211,7 @@ public void testActionGroupsApi() throws Exception { FileHelper.loadFile("restapi/roles_captains_tenants.json"), encodeBasicHeader("admin", "admin") ); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // worf, restore role starfleet captains response = rh.executePutRequest( @@ -218,17 +219,17 @@ public void testActionGroupsApi() throws Exception { FileHelper.loadFile("restapi/roles_captains_different_content.json"), encodeBasicHeader("worf", "worf") ); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_CREATED)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); // starfleet role present again response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("worf", "worf")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); - Assert.assertEquals( + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( new SecurityJsonNode(DefaultObjectMapper.readTree(response.getBody())).getDotted( "opendistro_security_role_starfleet_captains.index_permissions" ).get(0).get("allowed_actions").get(0).asString(), - "blafasel" + is("blafasel") ); // Try the same, but now with admin certificate @@ -236,18 +237,18 @@ public void testActionGroupsApi() throws Exception { // admin response = rh.executeGetRequest(ENDPOINT + "/internalusers/admin", encodeBasicHeader("la", "lu")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); settings = Settings.builder().loadFromSource(response.getBody(), XContentType.JSON).build(); Assert.assertTrue(settings.get("admin.hash") != null); - Assert.assertEquals("", settings.get("admin.hash")); + assertThat(settings.get("admin.hash"), is("")); // worf and config // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("bla", "fasel")); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + // assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // cache response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("wrong", "wrong")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // -- test user, does not have any endpoints disabled, but has access to API, i.e. full access @@ -255,14 +256,14 @@ public void testActionGroupsApi() throws Exception { // GET actiongroups // response = rh.executeGetRequest("_opendistro/_security/api/configuration/actiongroups", encodeBasicHeader("test", "test")); - // Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + // assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest("_opendistro/_security/api/actiongroups", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // clear cache - globally disabled, has to fail response = rh.executeDeleteRequest("_opendistro/_security/api/cache", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // PUT roles response = rh.executePutRequest( @@ -270,23 +271,23 @@ public void testActionGroupsApi() throws Exception { FileHelper.loadFile("restapi/roles_captains_different_content.json"), encodeBasicHeader("test", "test") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // GET captions role response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); // Delete captions role response = rh.executeDeleteRequest( ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test") ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertTrue(response.getBody().contains("'opendistro_security_role_starfleet_captains' deleted")); // GET captions role response = rh.executeGetRequest(ENDPOINT + "/roles/opendistro_security_role_starfleet_captains", encodeBasicHeader("test", "test")); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_NOT_FOUND)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiActionValidationTest.java index 7fe089c0ba..a908ec348a 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RolesApiActionValidationTest.java @@ -18,7 +18,8 @@ import org.mockito.Mockito; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -52,7 +53,7 @@ public void isNotAllowedRightsToChangeImmutableEntity() throws Exception { final var result = rolesApiActionEndpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("sss", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiActionValidationTest.java index f7d1d4da0b..1caa39a4ff 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/RolesMappingApiActionValidationTest.java @@ -20,7 +20,8 @@ import org.opensearch.core.rest.RestStatus; import org.opensearch.security.securityconf.impl.CType; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -54,7 +55,7 @@ public void isNotAllowedNoRightsToChangeRoleEntity() throws Exception { SecurityConfiguration.of("rest_api_admin_role", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -69,7 +70,7 @@ public void onConfigChangeShouldCheckRoles() throws Exception { // no role var result = rolesApiActionEndpointValidator.onConfigChange(SecurityConfiguration.of("aaa", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.NOT_FOUND, result.status()); + assertThat(result.status(), is(RestStatus.NOT_FOUND)); //static role is ok result = rolesApiActionEndpointValidator.onConfigChange(SecurityConfiguration.of("all_access", configuration)); assertTrue(result.isValid()); @@ -82,7 +83,7 @@ public void onConfigChangeShouldCheckRoles() throws Exception { //hidden role is not ok result = rolesApiActionEndpointValidator.onConfigChange(SecurityConfiguration.of("some_hidden_role", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.NOT_FOUND, result.status()); + assertThat(result.status(), is(RestStatus.NOT_FOUND)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java index 1580d07524..173a0866ac 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityApiAccessTest.java @@ -12,9 +12,10 @@ package org.opensearch.security.dlic.rest.api; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; public class SecurityApiAccessTest extends AbstractRestApiUnitTest { @@ -34,14 +35,14 @@ public void testRestApi() throws Exception { setup(); // test with no cert, must fail - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest(ENDPOINT).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest(ENDPOINT, encodeBasicHeader("admin", "admin")).getStatusCode()); + assertThat(rh.executeGetRequest(ENDPOINT).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest(ENDPOINT, encodeBasicHeader("admin", "admin")).getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); // test with non-admin cert, must fail rh.keystore = "restapi/node-0-keystore.jks"; rh.sendAdminCertificate = true; - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, rh.executeGetRequest(ENDPOINT).getStatusCode()); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, rh.executeGetRequest(ENDPOINT, encodeBasicHeader("admin", "admin")).getStatusCode()); + assertThat(rh.executeGetRequest(ENDPOINT).getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); + assertThat(rh.executeGetRequest(ENDPOINT, encodeBasicHeader("admin", "admin")).getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigurationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigurationTest.java index a0f9cca833..d88c0bc117 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigurationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecurityConfigurationTest.java @@ -22,7 +22,8 @@ import org.opensearch.security.securityconf.impl.SecurityDynamicConfiguration; import org.opensearch.security.securityconf.impl.v7.RoleV7; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -57,25 +58,25 @@ public void failsIfConfigurationOrRequestContentNull() { public void testNewOrUpdatedEntity() { var securityConfiguration = SecurityConfiguration.of("security_rest_api_access", configuration); assertTrue(securityConfiguration.entityExists()); - assertEquals("security_rest_api_access", securityConfiguration.entityName()); + assertThat(securityConfiguration.entityName(), is("security_rest_api_access")); securityConfiguration = SecurityConfiguration.of("security_rest_api_access_v2", configuration); assertFalse(securityConfiguration.entityExists()); - assertEquals("security_rest_api_access_v2", securityConfiguration.entityName()); + assertThat(securityConfiguration.entityName(), is("security_rest_api_access_v2")); final var newRole = new RoleV7(); newRole.setCluster_permissions(List.of("cluster:admin/opendistro/alerting/alerts/get")); configuration.putCObject("security_rest_api_access_v2", newRole); assertTrue(configuration.exists("security_rest_api_access_v2")); assertFalse(securityConfiguration.entityExists()); - assertEquals("security_rest_api_access_v2", securityConfiguration.entityName()); + assertThat(securityConfiguration.entityName(), is("security_rest_api_access_v2")); } @Test public void testNoEntityNameConfiguration() { final var securityConfiguration = SecurityConfiguration.of(null, configuration); assertFalse(securityConfiguration.entityExists()); - assertEquals("empty", securityConfiguration.entityName()); + assertThat(securityConfiguration.entityName(), is("empty")); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/SecuritySSLCertsApiActionValidationTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/SecuritySSLCertsApiActionValidationTest.java index d59ccf116c..6ad50b5cb5 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/SecuritySSLCertsApiActionValidationTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/SecuritySSLCertsApiActionValidationTest.java @@ -17,9 +17,10 @@ import org.opensearch.rest.RestRequest; import org.opensearch.security.util.FakeRestRequest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.dlic.rest.api.RestApiAdminPrivilegesEvaluator.CERTS_INFO_ACTION; import static org.opensearch.security.dlic.rest.api.RestApiAdminPrivilegesEvaluator.RELOAD_CERTS_ACTION; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; @@ -37,7 +38,7 @@ public void withSecurityKeyStore() { ); final var result = securitySSLCertsApiAction.withSecurityKeyStore(); assertFalse(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); } @Test diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java index 2e47aae556..2448ad0778 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/TenantInfoActionTest.java @@ -13,13 +13,14 @@ import org.apache.hc.core5.http.Header; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Test; import org.opensearch.common.settings.Settings; import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; public class TenantInfoActionTest extends AbstractRestApiUnitTest { @@ -48,15 +49,15 @@ public void testTenantInfoAPIAccess() throws Exception { rh.keystore = "restapi/kirk-keystore.jks"; rh.sendAdminCertificate = true; RestHelper.HttpResponse response = rh.executeGetRequest(ENDPOINT); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); rh.sendAdminCertificate = false; response = rh.executeGetRequest(ENDPOINT); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); rh.sendHTTPClientCredentials = true; response = rh.executeGetRequest(ENDPOINT); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test @@ -76,13 +77,13 @@ public void testTenantInfoAPIUpdate() throws Exception { "[{\"op\": \"add\",\"path\": \"/config/dynamic/kibana/opendistro_role\"," + "\"value\": \"opendistro_security_internal\"}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executePutRequest(BASE_ENDPOINT + "/api/rolesmapping/opendistro_security_internal", payload, new Header[0]); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); rh.sendAdminCertificate = false; response = rh.executeGetRequest(ENDPOINT); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } } diff --git a/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java b/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java index 0e3d330b52..5b5db93851 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/api/WhitelistApiTest.java @@ -34,8 +34,8 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.OpenSearchSecurityPlugin.PLUGINS_PREFIX; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** @@ -77,9 +77,9 @@ private void checkGetAndPutWhitelistPermissions(final int expectedStatus, final assertThat(response.getBody(), response.getStatusCode(), equalTo(expectedStatus)); if (expectedStatus == HttpStatus.SC_OK) { // Note: the response has no whitespaces, so the .json file does not have whitespaces - Assert.assertEquals( + assertThat( FileHelper.loadFile("restapi/whitelist_response_success.json"), - FileHelper.loadFile("restapi/whitelist_response_success.json") + is(FileHelper.loadFile("restapi/whitelist_response_success.json")) ); } // FORBIDDEN FOR NON SUPER ADMIN @@ -104,7 +104,7 @@ public void testResponseDoesNotContainMetaHeader() throws Exception { rh.sendAdminCertificate = true; RestHelper.HttpResponse response = rh.executeGetRequest(ENDPOINT + "/whitelist"); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); Assert.assertFalse(response.getBody().contains("_meta")); } @@ -118,7 +118,7 @@ public void testPutUnknownKey() throws Exception { ENDPOINT + "/whitelist", "{ \"unknownkey\": true, \"requests\": {\"/_cat/nodes\": [\"GET\"],\"/_cat/indices\": [\"GET\"] }}" ); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); assertTrue(response.getBody().contains("invalid_keys")); assertHealthy(); } @@ -132,7 +132,7 @@ public void testPutInvalidJson() throws Exception { ENDPOINT + "/whitelist", "{ \"invalid\"::{{ [\"*\"], \"requests\": {\"/_cat/nodes\": [\"GET\"],\"/_cat/indices\": [\"GET\"] }}" ); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); assertHealthy(); } @@ -147,9 +147,9 @@ public void testPayloadMandatory() throws Exception { rh.sendAdminCertificate = true; response = rh.executePutRequest(ENDPOINT + "/whitelist", "", new Header[0]); - Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST)); JsonNode settings = DefaultObjectMapper.readTree(response.getBody()); - Assert.assertEquals(RequestContentValidator.ValidationError.PAYLOAD_MANDATORY.message(), settings.get("reason").asText()); + assertThat(settings.get("reason").asText(), is(RequestContentValidator.ValidationError.PAYLOAD_MANDATORY.message())); } /** @@ -241,11 +241,11 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"replace\", \"path\": \"/config\", \"value\": {\"enabled\": true, \"requests\": {\"/_cat/nodes\": [\"GET\"],\"/_cat/indices\": [\"PUT\"] }}}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT + "/whitelist", adminCredsHeader); - assertEquals( + assertThat( response.getBody(), - "{\"config\":{\"enabled\":true,\"requests\":{\"/_cat/nodes\":[\"GET\"],\"/_cat/indices\":[\"PUT\"]}}}" + is("{\"config\":{\"enabled\":true,\"requests\":{\"/_cat/nodes\":[\"GET\"],\"/_cat/indices\":[\"PUT\"]}}}") ); // PATCH just requests @@ -254,7 +254,7 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"replace\", \"path\": \"/config/requests\", \"value\": {\"/_cat/nodes\": [\"GET\"]}}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT + "/whitelist", adminCredsHeader); assertTrue(response.getBody().contains("\"requests\":{\"/_cat/nodes\":[\"GET\"]}")); @@ -264,7 +264,7 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"replace\", \"path\": \"/config/enabled\", \"value\": false}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT + "/whitelist", adminCredsHeader); assertTrue(response.getBody().contains("\"enabled\":false")); @@ -274,7 +274,7 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"add\", \"path\": \"/config/enabled\", \"value\": true}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT + "/whitelist", adminCredsHeader); assertTrue(response.getBody().contains("\"enabled\":true")); @@ -284,7 +284,7 @@ public void testPatchApi() throws Exception { "[{ \"op\": \"add\", \"path\": \"/config/enabled\", \"value\": false}]", new Header[0] ); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); response = rh.executeGetRequest(ENDPOINT + "/whitelist", adminCredsHeader); response = rh.executeGetRequest(ENDPOINT + "/whitelist", adminCredsHeader); assertTrue(response.getBody().contains("\"enabled\":false")); diff --git a/src/test/java/org/opensearch/security/dlic/rest/validation/EndpointValidatorTest.java b/src/test/java/org/opensearch/security/dlic/rest/validation/EndpointValidatorTest.java index 389c2b6ff4..69bdb6a1a3 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/validation/EndpointValidatorTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/validation/EndpointValidatorTest.java @@ -33,7 +33,8 @@ import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -74,11 +75,11 @@ public RequestContentValidator createRequestContentValidator(Object... params) { public void requiredEntityName() { var validationResult = endpointValidator.withRequiredEntityName(null); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.BAD_REQUEST, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.BAD_REQUEST)); validationResult = endpointValidator.withRequiredEntityName("a"); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -86,7 +87,7 @@ public void entityDoesNotExist() { when(configuration.exists("some_role")).thenReturn(false); final var validationResult = endpointValidator.entityExists(SecurityConfiguration.of("some_role", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.NOT_FOUND, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.NOT_FOUND)); } @Test @@ -94,7 +95,7 @@ public void entityExists() { when(configuration.exists("some_role")).thenReturn(true); final var validationResult = endpointValidator.entityExists(SecurityConfiguration.of("some_role", configuration)); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -102,7 +103,7 @@ public void entityExistsSkipEmptyEntityName() { when(configuration.exists(null)).thenReturn(false); final var validationResult = endpointValidator.entityExists(SecurityConfiguration.of(null, configuration)); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -110,7 +111,7 @@ public void entityHidden() { when(configuration.isHidden("some_entity")).thenReturn(true); final var validationResult = endpointValidator.entityHidden( SecurityConfiguration.of("some_entity", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.NOT_FOUND, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.NOT_FOUND)); } @Test @@ -118,7 +119,7 @@ public void entityNotHidden() { when(configuration.isHidden("some_entity")).thenReturn(false); final var validationResult = endpointValidator.entityHidden( SecurityConfiguration.of("some_entity", configuration)); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -126,7 +127,7 @@ public void entityReserved() { when(configuration.isReserved("some_entity")).thenReturn(true); final var validationResult = endpointValidator.entityReserved( SecurityConfiguration.of("some_entity", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -134,7 +135,7 @@ public void entityNotReserved() { when(configuration.isReserved("some_entity")).thenReturn(false); final var validationResult = endpointValidator.entityReserved( SecurityConfiguration.of("some_entity", configuration)); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -142,7 +143,7 @@ public void entityStatic() { when(configuration.isStatic("some_entity")).thenReturn(true); final var validationResult = endpointValidator.entityStatic( SecurityConfiguration.of("some_entity", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -150,7 +151,7 @@ public void entityNotStatic() { when(configuration.isStatic("some_entity")).thenReturn(false); final var validationResult = endpointValidator.entityStatic( SecurityConfiguration.of("some_entity", configuration)); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -159,7 +160,7 @@ public void hiddenEntityImmutable() throws Exception { var validationResult = endpointValidator.entityImmutable( SecurityConfiguration.of("some_entity", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.NOT_FOUND, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.NOT_FOUND)); } @Test @@ -168,7 +169,7 @@ public void staticEntityImmutable() throws Exception { when(configuration.isStatic("some_entity")).thenReturn(true); final var validationResult = endpointValidator.entityImmutable( SecurityConfiguration.of("some_entity", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -178,7 +179,7 @@ public void reservedEntityImmutable() throws Exception { when(configuration.isReserved("some_entity")).thenReturn(true); final var validationResult = endpointValidator.entityImmutable( SecurityConfiguration.of("some_entity", configuration)); assertFalse(validationResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -186,19 +187,19 @@ public void hasRightsToChangeImmutableEntity() throws Exception { configImmutableEntities(false); var result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("hidden_entity", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.NOT_FOUND, result.status()); + assertThat(result.status(), is(RestStatus.NOT_FOUND)); result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("static_entity", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("reserved_entity", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.FORBIDDEN, result.status()); + assertThat(result.status(), is(RestStatus.FORBIDDEN)); result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("just_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); } @Test @@ -207,19 +208,19 @@ public void hasRightsToChangeImmutableEntityForAdmin() throws Exception { var result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("hidden_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("static_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("reserved_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); result = endpointValidator.isAllowedToChangeImmutableEntity(SecurityConfiguration.of("just_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); } @Test @@ -228,11 +229,11 @@ public void hasRightsToLoadOrChangeHiddenEntityForRegularUser() throws Exception var result = endpointValidator.isAllowedToLoadOrChangeHiddenEntity(SecurityConfiguration.of("hidden_entity", configuration)); assertFalse(result.isValid()); - assertEquals(RestStatus.NOT_FOUND, result.status()); + assertThat(result.status(), is(RestStatus.NOT_FOUND)); result = endpointValidator.isAllowedToLoadOrChangeHiddenEntity(SecurityConfiguration.of("just_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); } @Test @@ -241,11 +242,11 @@ public void hasRightsToLoadOrChangeHiddenEntityForAdmin() throws Exception { var result = endpointValidator.isAllowedToLoadOrChangeHiddenEntity(SecurityConfiguration.of("hidden_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); result = endpointValidator.isAllowedToLoadOrChangeHiddenEntity(SecurityConfiguration.of("just_entity", configuration)); assertTrue(result.isValid()); - assertEquals(RestStatus.OK, result.status()); + assertThat(result.status(), is(RestStatus.OK)); } private void configImmutableEntities(final boolean isAdmin) { @@ -267,7 +268,7 @@ public void entityNotImmutable() throws Exception { var validationResult = endpointValidator.entityImmutable( SecurityConfiguration.of("some_entity", configuration)); assertTrue(validationResult.isValid()); - assertEquals(RestStatus.OK, validationResult.status()); + assertThat(validationResult.status(), is(RestStatus.OK)); } @Test @@ -283,8 +284,8 @@ public void validateRolesForAdmin() throws IOException { for (final var roleWithExpectedResults : expectedResultForRoles) { final var validationResult = endpointValidator.validateRoles(List.of(roleWithExpectedResults.getLeft()), configuration); - assertEquals(roleWithExpectedResults.getMiddle(), validationResult.isValid()); - assertEquals(roleWithExpectedResults.getRight(), validationResult.status()); + assertThat(validationResult.isValid(), is(roleWithExpectedResults.getMiddle())); + assertThat(validationResult.status(), is(roleWithExpectedResults.getRight())); } } @@ -302,8 +303,8 @@ public void validateRolesForRegularUser() throws IOException { for (final var roleWithExpectedResults : expectedResultForRoles) { final var validationResult = endpointValidator.validateRoles(List.of(roleWithExpectedResults.getLeft()), configuration); - assertEquals(roleWithExpectedResults.getMiddle(), validationResult.isValid()); - assertEquals(roleWithExpectedResults.getRight(), validationResult.status()); + assertThat(validationResult.isValid(), is(roleWithExpectedResults.getMiddle())); + assertThat(validationResult.status(), is(roleWithExpectedResults.getRight())); } } @@ -338,7 +339,7 @@ public void regularUserCanNotChangeObjectWithRestAdminPermissionsForExistingRole SecurityConfiguration.of("some_role", configuration) ); assertFalse(roleCheckResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, roleCheckResult.status()); + assertThat(roleCheckResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -359,7 +360,7 @@ public void regularUserCanNotChangeObjectWithRestAdminPermissionsForNewRoles() t SecurityConfiguration.of(objectMapper.createObjectNode().set("cluster_permissions", array), "some_role", configuration) ); assertFalse(roleCheckResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, roleCheckResult.status()); + assertThat(roleCheckResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -372,7 +373,7 @@ public void regularUserCanNotChangeObjectWithRestAdminPermissionsForExitingActio SecurityConfiguration.of("some_ag", configuration) ); assertFalse(agCheckResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, agCheckResult.status()); + assertThat(agCheckResult.status(), is(RestStatus.FORBIDDEN)); } @Test @@ -391,7 +392,7 @@ public void regularUserCanNotChangeObjectWithRestAdminPermissionsForMewActionGro SecurityConfiguration.of(objectMapper.createObjectNode().set("allowed_actions", array), "some_ag", configuration) ); assertFalse(agCheckResult.isValid()); - assertEquals(RestStatus.FORBIDDEN, agCheckResult.status()); + assertThat(agCheckResult.status(), is(RestStatus.FORBIDDEN)); } private List restAdminPermissions() { diff --git a/src/test/java/org/opensearch/security/dlic/rest/validation/PasswordValidatorTest.java b/src/test/java/org/opensearch/security/dlic/rest/validation/PasswordValidatorTest.java index c623140c3f..7f8b631edb 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/validation/PasswordValidatorTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/validation/PasswordValidatorTest.java @@ -18,10 +18,11 @@ import org.opensearch.common.settings.Settings; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_MIN_LENGTH; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_SCORE_BASED_VALIDATION_STRENGTH; import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_PASSWORD_VALIDATION_REGEX; -import static org.junit.Assert.assertEquals; public class PasswordValidatorTest { @@ -69,7 +70,7 @@ public void verifyWeakPasswords( final RequestContentValidator.ValidationError expectedValidationResult ) { for (final String password : WEAK_PASSWORDS) - assertEquals(password, expectedValidationResult, passwordValidator.validate("some_user_name", password)); + assertThat(password, passwordValidator.validate("some_user_name", password), is(expectedValidationResult)); } @@ -78,7 +79,7 @@ public void verifyFairPasswords( final RequestContentValidator.ValidationError expectedValidationResult ) { for (final String password : FAIR_PASSWORDS) - assertEquals(password, expectedValidationResult, passwordValidator.validate("some_user_name", password)); + assertThat(password, passwordValidator.validate("some_user_name", password), is(expectedValidationResult)); } @@ -87,7 +88,7 @@ public void verifyGoodPasswords( final RequestContentValidator.ValidationError expectedValidationResult ) { for (final String password : GOOD_PASSWORDS) - assertEquals(password, expectedValidationResult, passwordValidator.validate("some_user_name", password)); + assertThat(password, passwordValidator.validate("some_user_name", password), is(expectedValidationResult)); } @@ -96,7 +97,7 @@ public void verifyStrongPasswords( final RequestContentValidator.ValidationError expectedValidationResult ) { for (final String password : STRONG_PASSWORDS) - assertEquals(password, expectedValidationResult, passwordValidator.validate("some_user_name", password)); + assertThat(password, passwordValidator.validate("some_user_name", password), is(expectedValidationResult)); } @@ -105,16 +106,16 @@ public void verifyVeryStrongPasswords( final RequestContentValidator.ValidationError expectedValidationResult ) { for (final String password : VERY_STRONG_PASSWORDS) - assertEquals(password, expectedValidationResult, passwordValidator.validate("some_user_name", password)); + assertThat(password, passwordValidator.validate("some_user_name", password), is(expectedValidationResult)); } public void verifySimilarPasswords(final PasswordValidator passwordValidator) { for (final String password : SIMILAR_PASSWORDS) - assertEquals( + assertThat( password, - RequestContentValidator.ValidationError.SIMILAR_PASSWORD, - passwordValidator.validate("some_user_name", password) + passwordValidator.validate("some_user_name", password), + is(RequestContentValidator.ValidationError.SIMILAR_PASSWORD) ); } @@ -129,16 +130,16 @@ public void testRegExpBasedValidation() { verifyWeakPasswords(passwordValidator, RequestContentValidator.ValidationError.INVALID_PASSWORD_INVALID_REGEX); verifyFairPasswords(passwordValidator, RequestContentValidator.ValidationError.INVALID_PASSWORD_INVALID_REGEX); for (final String password : GOOD_PASSWORDS.subList(0, GOOD_PASSWORDS.size() - 2)) - assertEquals( + assertThat( password, - RequestContentValidator.ValidationError.INVALID_PASSWORD_INVALID_REGEX, - passwordValidator.validate("some_user_name", password) + passwordValidator.validate("some_user_name", password), + is(RequestContentValidator.ValidationError.INVALID_PASSWORD_INVALID_REGEX) ); for (final String password : GOOD_PASSWORDS.subList(GOOD_PASSWORDS.size() - 2, GOOD_PASSWORDS.size())) - assertEquals( + assertThat( password, - RequestContentValidator.ValidationError.WEAK_PASSWORD, - passwordValidator.validate("some_user_name", password) + passwordValidator.validate("some_user_name", password), + is(RequestContentValidator.ValidationError.WEAK_PASSWORD) ); verifyStrongPasswords(passwordValidator, RequestContentValidator.ValidationError.NONE); verifyVeryStrongPasswords(passwordValidator, RequestContentValidator.ValidationError.NONE); @@ -151,9 +152,9 @@ public void testMinLength() { Settings.builder().put(SECURITY_RESTAPI_PASSWORD_MIN_LENGTH, 15).build() ); for (final String password : STRONG_PASSWORDS) { - assertEquals( + assertThat( RequestContentValidator.ValidationError.INVALID_PASSWORD_TOO_SHORT, - passwordValidator.validate(password, "some_user_name") + is(passwordValidator.validate(password, "some_user_name")) ); } diff --git a/src/test/java/org/opensearch/security/dlic/rest/validation/RequestContentValidatorTest.java b/src/test/java/org/opensearch/security/dlic/rest/validation/RequestContentValidatorTest.java index 429bd67b3f..561695106d 100644 --- a/src/test/java/org/opensearch/security/dlic/rest/validation/RequestContentValidatorTest.java +++ b/src/test/java/org/opensearch/security/dlic/rest/validation/RequestContentValidatorTest.java @@ -38,7 +38,8 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -155,9 +156,9 @@ public Map allowedKeys() { assertFalse(validationResult.isValid()); assertErrorMessage(errorMessage, RequestContentValidator.ValidationError.WRONG_DATATYPE); - assertEquals("String expected", errorMessage.get("a").asText()); - assertEquals("Object expected", errorMessage.get("b").asText()); - assertEquals("Array expected", errorMessage.get("c").asText()); + assertThat(errorMessage.get("a").asText(), is("String expected")); + assertThat(errorMessage.get("b").asText(), is("Object expected")); + assertThat(errorMessage.get("c").asText(), is("Array expected")); } @Test @@ -190,8 +191,8 @@ public Map allowedKeys() { final JsonNode errorMessage = xContentToJsonNode(validationResult.errorMessage()); assertErrorMessage(errorMessage, RequestContentValidator.ValidationError.INVALID_CONFIGURATION); - assertEquals("{\"keys\":\"c,d\"}", errorMessage.get("invalid_keys").toString()); - assertEquals("{\"keys\":\"a\"}", errorMessage.get("missing_mandatory_keys").toString()); + assertThat(errorMessage.get("invalid_keys").toString(), is("{\"keys\":\"c,d\"}")); + assertThat(errorMessage.get("missing_mandatory_keys").toString(), is("{\"keys\":\"a\"}")); } @Test @@ -313,8 +314,8 @@ private void assertErrorMessage(final ToXContent toXContent, final RequestConten } private void assertErrorMessage(final JsonNode jsonNode, final RequestContentValidator.ValidationError expectedValidationError) { - assertEquals("error", jsonNode.get("status").asText()); - assertEquals(expectedValidationError.message(), jsonNode.get("reason").asText()); + assertThat(jsonNode.get("status").asText(), is("error")); + assertThat(jsonNode.get("reason").asText(), is(expectedValidationError.message())); } } diff --git a/src/test/java/org/opensearch/security/http/OnBehalfOfAuthenticatorTest.java b/src/test/java/org/opensearch/security/http/OnBehalfOfAuthenticatorTest.java index bae4fa7f28..310acc4772 100644 --- a/src/test/java/org/opensearch/security/http/OnBehalfOfAuthenticatorTest.java +++ b/src/test/java/org/opensearch/security/http/OnBehalfOfAuthenticatorTest.java @@ -49,14 +49,14 @@ import io.jsonwebtoken.security.Keys; import org.mockito.ArgumentCaptor; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.rest.RestRequest.Method.POST; import static org.opensearch.rest.RestRequest.Method.PUT; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -94,7 +94,7 @@ public void testReRequestAuthenticationReturnsEmptyOptional() { public void testGetTypeReturnsExpectedType() { OnBehalfOfAuthenticator authenticator = new OnBehalfOfAuthenticator(defaultSettings(), clusterName); String type = authenticator.getType(); - assertEquals("onbehalfof_jwt", type); + assertThat(type, is("onbehalfof_jwt")); } @Test @@ -286,9 +286,9 @@ public void testBearer() throws Exception { ); assertNotNull(credentials); - assertEquals("Leonard McCoy", credentials.getUsername()); - assertEquals(0, credentials.getSecurityRoles().size()); - assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getSecurityRoles().size(), is(0)); + assertThat(credentials.getBackendRoles().size(), is(0)); assertThat(credentials.getAttributes(), equalTo(expectedAttributes)); } @@ -414,9 +414,9 @@ public void testPlainTextedRolesFromDrClaim() { ); assertNotNull(credentials); - assertEquals("Leonard McCoy", credentials.getUsername()); - assertEquals(2, credentials.getSecurityRoles().size()); - assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getSecurityRoles().size(), is(2)); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -466,8 +466,8 @@ public void testNullClaim() throws Exception { ); assertNotNull(credentials); - assertEquals("Leonard McCoy", credentials.getUsername()); - assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -481,8 +481,8 @@ public void testNonStringClaim() throws Exception { ); assertNotNull(credentials); - assertEquals("Leonard McCoy", credentials.getUsername()); - assertEquals(1, credentials.getSecurityRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getSecurityRoles().size(), is(1)); assertTrue(credentials.getSecurityRoles().contains("123")); } @@ -497,9 +497,9 @@ public void testRolesMissing() throws Exception { ); assertNotNull(credentials); - assertEquals("Leonard McCoy", credentials.getUsername()); - assertEquals(0, credentials.getSecurityRoles().size()); - assertEquals(0, credentials.getBackendRoles().size()); + assertThat(credentials.getUsername(), is("Leonard McCoy")); + assertThat(credentials.getSecurityRoles().size(), is(0)); + assertThat(credentials.getBackendRoles().size(), is(0)); } @Test @@ -571,8 +571,8 @@ public void testRolesArray() throws Exception { final AuthCredentials credentials = extractCredentialsFromJwtHeader(signingKeyB64Encoded, claimsEncryptionKey, builder, true); assertNotNull(credentials); - assertEquals("Cluster_0", credentials.getUsername()); - assertEquals(3, credentials.getSecurityRoles().size()); + assertThat(credentials.getUsername(), is("Cluster_0")); + assertThat(credentials.getSecurityRoles().size(), is(3)); assertTrue(credentials.getSecurityRoles().contains("a")); assertTrue(credentials.getSecurityRoles().contains("b")); assertTrue(credentials.getSecurityRoles().contains("3rd")); diff --git a/src/test/java/org/opensearch/security/http/proxy/HTTPExtendedProxyAuthenticatorTest.java b/src/test/java/org/opensearch/security/http/proxy/HTTPExtendedProxyAuthenticatorTest.java index 6644f8ce73..44065f819e 100644 --- a/src/test/java/org/opensearch/security/http/proxy/HTTPExtendedProxyAuthenticatorTest.java +++ b/src/test/java/org/opensearch/security/http/proxy/HTTPExtendedProxyAuthenticatorTest.java @@ -52,7 +52,8 @@ import org.opensearch.security.support.ConfigConstants; import org.opensearch.security.user.AuthCredentials; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -73,7 +74,7 @@ public void setup() { @Test public void testGetType() { - assertEquals("extended-proxy", authenticator.getType()); + assertThat(authenticator.getType(), is("extended-proxy")); } @Test(expected = OpenSearchSecurityException.class) @@ -109,9 +110,9 @@ public void testReturnsCredentials() { authenticator = new HTTPExtendedProxyAuthenticator(settings, null); AuthCredentials creds = authenticator.extractCredentials(new TestRestRequest(headers).asSecurityRequest(), context); assertNotNull(creds); - assertEquals("aValidUser", creds.getUsername()); - assertEquals("123,456", creds.getAttributes().get("attr.proxy.uid")); - assertEquals("someothervalue", creds.getAttributes().get("attr.proxy.other")); + assertThat(creds.getUsername(), is("aValidUser")); + assertThat(creds.getAttributes().get("attr.proxy.uid"), is("123,456")); + assertThat(creds.getAttributes().get("attr.proxy.other"), is("someothervalue")); assertTrue(creds.isComplete()); } @@ -126,8 +127,8 @@ public void testTrimOnRoles() { authenticator = new HTTPExtendedProxyAuthenticator(settings, null); AuthCredentials creds = authenticator.extractCredentials(new TestRestRequest(headers).asSecurityRequest(), context); assertNotNull(creds); - assertEquals("aValidUser", creds.getUsername()); - assertEquals(ImmutableSet.of("role1", "role2"), creds.getBackendRoles()); + assertThat(creds.getUsername(), is("aValidUser")); + assertThat(creds.getBackendRoles(), is(ImmutableSet.of("role1", "role2"))); assertTrue(creds.isComplete()); } diff --git a/src/test/java/org/opensearch/security/multitenancy/test/MultitenancyTests.java b/src/test/java/org/opensearch/security/multitenancy/test/MultitenancyTests.java index 0a785d7b80..d1422e61eb 100644 --- a/src/test/java/org/opensearch/security/multitenancy/test/MultitenancyTests.java +++ b/src/test/java/org/opensearch/security/multitenancy/test/MultitenancyTests.java @@ -38,6 +38,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; public class MultitenancyTests extends SingleClusterTest { @@ -114,14 +115,14 @@ public void testNoDnfof() throws Exception { } HttpResponse resc; - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_b", "user_b"))).getStatusCode() + is((resc = rh.executeGetRequest("indexa,indexb/_search?pretty", encodeBasicHeader("user_b", "user_b"))).getStatusCode()) ); String msearchBody = "{\"index\":\"indexa\", \"ignore_unavailable\": true}" @@ -134,7 +135,7 @@ public void testNoDnfof() throws Exception { + System.lineSeparator(); // msearch a resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_a", "user_a")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); @@ -142,7 +143,7 @@ public void testNoDnfof() throws Exception { // msearch b resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexa")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); @@ -159,13 +160,13 @@ public void testNoDnfof() throws Exception { // msearch b2 resc = rh.executePostRequest("_msearch?pretty", msearchBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexc")); Assert.assertFalse(resc.getBody(), resc.getBody().contains("indexd")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("permission")); int count = resc.getBody().split("\"status\" : 403").length; - Assert.assertEquals(3, count); + assertThat(count, is(3)); String mgetBody = "{" + "\"docs\" : [" @@ -181,7 +182,7 @@ public void testNoDnfof() throws Exception { + "}"; resc = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertFalse(resc.getBody(), resc.getBody().contains("\"content\" : \"indexa\"")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("indexb")); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); @@ -201,59 +202,59 @@ public void testNoDnfof() throws Exception { + "}"; resc = rh.executePostRequest("_mget?pretty", mgetBody, encodeBasicHeader("user_b", "user_b")); - Assert.assertEquals(200, resc.getStatusCode()); + assertThat(resc.getStatusCode(), is(200)); Assert.assertTrue(resc.getBody(), resc.getBody().contains("exception")); count = resc.getBody().split("root_cause").length; - Assert.assertEquals(3, count); + assertThat(count, is(3)); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("index*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("index*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (resc = rh.executeGetRequest("indexa/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("indexa/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("indexb/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("indexb/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("_all/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("_all/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("notexists/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("notexists/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_NOT_FOUND, - (resc = rh.executeGetRequest("indexanbh,indexabb*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("indexanbh,indexabb*/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (resc = rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode() + is((resc = rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("user_a", "user_a"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (resc = rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode() + is((resc = rh.executeGetRequest("starfleet/_search?pretty", encodeBasicHeader("worf", "worf"))).getStatusCode()) ); } @@ -266,52 +267,63 @@ public void testMt() throws Exception { HttpResponse res; String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (res = rh.executePutRequest( - ".kibana/_doc/5.6.0?pretty", - body, - new BasicHeader("securitytenant", "blafasel"), - encodeBasicHeader("hr_employee", "hr_employee") - )).getStatusCode() + is( + (res = rh.executePutRequest( + ".kibana/_doc/5.6.0?pretty", + body, + new BasicHeader("securitytenant", "blafasel"), + encodeBasicHeader("hr_employee", "hr_employee") + )).getStatusCode() + ) ); body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_FORBIDDEN, - (res = rh.executePutRequest( - ".kibana/_doc/5.6.0?pretty", - body, - new BasicHeader("securitytenant", "business_intelligence"), - encodeBasicHeader("hr_employee", "hr_employee") - )).getStatusCode() + is( + (res = rh.executePutRequest( + ".kibana/_doc/5.6.0?pretty", + body, + new BasicHeader("securitytenant", "business_intelligence"), + encodeBasicHeader("hr_employee", "hr_employee") + )).getStatusCode() + ) ); body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - (res = rh.executePutRequest( - ".kibana/_doc/5.6.0?pretty", - body, - new BasicHeader("securitytenant", "human_resources"), - encodeBasicHeader("hr_employee", "hr_employee") - )).getStatusCode() + is( + (res = rh.executePutRequest( + ".kibana/_doc/5.6.0?pretty", + body, + new BasicHeader("securitytenant", "human_resources"), + encodeBasicHeader("hr_employee", "hr_employee") + )).getStatusCode() + ) ); - Assert.assertEquals(".kibana_1592542611_humanresources_1", DefaultObjectMapper.readTree(res.getBody()).get("_index").asText()); + assertThat(DefaultObjectMapper.readTree(res.getBody()).get("_index").asText(), is(".kibana_1592542611_humanresources_1")); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - ".kibana/_doc/5.6.0?pretty", - new BasicHeader("securitytenant", "human_resources"), - encodeBasicHeader("hr_employee", "hr_employee") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + ".kibana/_doc/5.6.0?pretty", + new BasicHeader("securitytenant", "human_resources"), + encodeBasicHeader("hr_employee", "hr_employee") + )).getStatusCode() + ) ); Assert.assertTrue(WildcardMatcher.from("*human_resources*").test(res.getBody())); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest(".kibana_1592542611_humanresources_1/_alias", encodeBasicHeader("admin", "admin"))).getStatusCode() + is( + (res = rh.executeGetRequest(".kibana_1592542611_humanresources_1/_alias", encodeBasicHeader("admin", "admin"))) + .getStatusCode() + ) ); Assert.assertNotNull( DefaultObjectMapper.readTree(res.getBody()) @@ -355,14 +367,16 @@ public void testMtMulti() throws Exception { // search HttpResponse res; String body = "{\"query\" : {\"term\" : { \"_id\" : \"index-pattern:9fbbd1a0-c3c5-11e8-a13f-71b8ea5a4f7b\"}}}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - ".kibana/_search/?pretty", - body, - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + ".kibana/_search/?pretty", + body, + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("exception")); Assert.assertTrue(res.getBody().contains("humanresources")); @@ -375,14 +389,16 @@ public void testMtMulti() throws Exception { + "{\"size\":10, \"query\":{\"bool\":{\"must\":{\"match_all\":{}}}}}" + System.lineSeparator(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "_msearch/?pretty", - body, - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "_msearch/?pretty", + body, + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("exception")); Assert.assertTrue(res.getBody().contains("humanresources")); @@ -390,13 +406,15 @@ public void testMtMulti() throws Exception { Assert.assertTrue(res.getBody().contains(dashboardsIndex)); // get - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - ".kibana/_doc/index-pattern:9fbbd1a0-c3c5-11e8-a13f-71b8ea5a4f7b?pretty", - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + ".kibana/_doc/index-pattern:9fbbd1a0-c3c5-11e8-a13f-71b8ea5a4f7b?pretty", + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("exception")); Assert.assertTrue(res.getBody().contains("humanresources")); @@ -405,14 +423,16 @@ public void testMtMulti() throws Exception { // mget body = "{\"docs\" : [{\"_index\" : \".kibana\",\"_id\" : \"index-pattern:9fbbd1a0-c3c5-11e8-a13f-71b8ea5a4f7b\"}]}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePostRequest( - "_mget/?pretty", - body, - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePostRequest( + "_mget/?pretty", + body, + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("exception")); Assert.assertTrue(res.getBody().contains("humanresources")); @@ -425,14 +445,16 @@ public void testMtMulti() throws Exception { + "\"index-pattern\" : {" + "\"title\" : \"xyz\"" + "}}"; - Assert.assertEquals( + assertThat( HttpStatus.SC_CREATED, - (res = rh.executePutRequest( - ".kibana/_doc/abc?pretty", - body, - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePutRequest( + ".kibana/_doc/abc?pretty", + body, + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("exception")); Assert.assertTrue(res.getBody().contains("\"result\" : \"created\"")); @@ -448,25 +470,24 @@ public void testMtMulti() throws Exception { + "{ \"field2\" : \"value2\" }" + System.lineSeparator(); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executePutRequest( - "_bulk?pretty", - body, - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("admin", "admin") - )).getStatusCode() + is( + (res = rh.executePutRequest( + "_bulk?pretty", + body, + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("admin", "admin") + )).getStatusCode() + ) ); Assert.assertFalse(res.getBody().contains("exception")); Assert.assertTrue(res.getBody().contains(dashboardsIndex)); Assert.assertTrue(res.getBody().contains("\"errors\" : false")); Assert.assertTrue(res.getBody().contains("\"result\" : \"created\"")); - Assert.assertEquals( - HttpStatus.SC_OK, - (res = rh.executeGetRequest("_cat/indices", encodeBasicHeader("admin", "admin"))).getStatusCode() - ); - Assert.assertEquals(2, res.getBody().split(".kibana").length); + assertThat(HttpStatus.SC_OK, is((res = rh.executeGetRequest("_cat/indices", encodeBasicHeader("admin", "admin"))).getStatusCode())); + assertThat(res.getBody().split(".kibana").length, is(2)); Assert.assertTrue(res.getBody().contains(dashboardsIndex)); } @@ -493,13 +514,13 @@ public void testDashboardsAlias() throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest(".kibana-6/_doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode() + is((res = rh.executeGetRequest(".kibana-6/_doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode()) ); - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest(".kibana/_doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode() + is((res = rh.executeGetRequest(".kibana/_doc/6.2.2?pretty", encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode()) ); } @@ -532,13 +553,15 @@ public void testDashboardsAlias65() throws Exception { final RestHelper rh = nonSslRestHelper(); HttpResponse res; - Assert.assertEquals( + assertThat( HttpStatus.SC_OK, - (res = rh.executeGetRequest( - ".kibana/_doc/6.2.2?pretty", - new BasicHeader("securitytenant", "__user__"), - encodeBasicHeader("kibanaro", "kibanaro") - )).getStatusCode() + is( + (res = rh.executeGetRequest( + ".kibana/_doc/6.2.2?pretty", + new BasicHeader("securitytenant", "__user__"), + encodeBasicHeader("kibanaro", "kibanaro") + )).getStatusCode() + ) ); Assert.assertTrue(res.getBody().contains(".kibana_-900636979_kibanaro")); } @@ -615,12 +638,12 @@ public void testMultitenancyAnonymousUser() throws Exception { /* The anonymous user has access to its tenant */ res = rh.executeGetRequest(url, new BasicHeader("securitytenant", anonymousTenant)); - Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode()); - Assert.assertEquals(anonymousTenant, res.findValueInJson("_source.tenant")); + assertThat(res.getStatusCode(), is(HttpStatus.SC_OK)); + assertThat(res.findValueInJson("_source.tenant"), is(anonymousTenant)); /* No access to other tenants */ res = rh.executeGetRequest(url, new BasicHeader("securitytenant", "human_resources")); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); } @Test diff --git a/src/test/java/org/opensearch/security/privileges/PrivilegesEvaluatorTest.java b/src/test/java/org/opensearch/security/privileges/PrivilegesEvaluatorTest.java index d5a26024a9..fba61d00ec 100644 --- a/src/test/java/org/opensearch/security/privileges/PrivilegesEvaluatorTest.java +++ b/src/test/java/org/opensearch/security/privileges/PrivilegesEvaluatorTest.java @@ -13,7 +13,6 @@ import org.apache.hc.core5.http.Header; import org.apache.http.HttpStatus; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -22,6 +21,9 @@ import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class PrivilegesEvaluatorTest extends SingleClusterTest { private static final Header NegativeLookaheadUserHeader = encodeBasicHeader("negative_lookahead_user", "negative_lookahead_user"); private static final Header NegatedRegexUserHeader = encodeBasicHeader("negated_regex_user", "negated_regex_user"); @@ -44,17 +46,17 @@ public void testNegativeLookaheadPattern() throws Exception { RestHelper rh = nonSslRestHelper(); RestHelper.HttpResponse response = rh.executeGetRequest("*/_search", NegativeLookaheadUserHeader); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("r*/_search", NegativeLookaheadUserHeader); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } @Test public void testRegexPattern() throws Exception { RestHelper rh = nonSslRestHelper(); RestHelper.HttpResponse response = rh.executeGetRequest("*/_search", NegatedRegexUserHeader); - Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_FORBIDDEN)); response = rh.executeGetRequest("r*/_search", NegatedRegexUserHeader); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); + assertThat(response.getStatusCode(), is(HttpStatus.SC_OK)); } } diff --git a/src/test/java/org/opensearch/security/protected_indices/ProtectedIndicesTests.java b/src/test/java/org/opensearch/security/protected_indices/ProtectedIndicesTests.java index c1198269b1..f881e2e91e 100644 --- a/src/test/java/org/opensearch/security/protected_indices/ProtectedIndicesTests.java +++ b/src/test/java/org/opensearch/security/protected_indices/ProtectedIndicesTests.java @@ -54,8 +54,9 @@ import org.opensearch.security.test.SingleClusterTest; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static junit.framework.TestCase.assertTrue; -import static org.junit.Assert.assertEquals; public class ProtectedIndicesTests extends SingleClusterTest { @@ -887,41 +888,49 @@ public void testAccessSnapshot() throws Exception { RestHelper rh = nonSslRestHelper(); for (String index : listOfIndexesToTest) { - assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executeGetRequest("_snapshot/" + index + "/" + index + "_1", protectedIndexUserHeader).getStatusCode() + is(rh.executeGetRequest("_snapshot/" + index + "/" + index + "_1", protectedIndexUserHeader).getStatusCode()) ); - assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", - "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", - protectedIndexUserHeader - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", + "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", + protectedIndexUserHeader + ).getStatusCode() + ) ); - assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", - "", - protectedIndexUserHeader - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", + "", + protectedIndexUserHeader + ).getStatusCode() + ) ); - assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePostRequest( - "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", - "{ \"indices\": \"" + index + "\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"" + index + "_1\" }", - protectedIndexUserHeader - ).getStatusCode() + is( + rh.executePostRequest( + "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", + "{ \"indices\": \"" + index + "\", \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"" + index + "_1\" }", + protectedIndexUserHeader + ).getStatusCode() + ) ); - assertEquals( + assertThat( HttpStatus.SC_OK, - rh.executePutRequest( - "_snapshot/" + index + "/" + index + "_2?wait_for_completion=true", - String.format(putSnapshot, index), - protectedIndexUserHeader - ).getStatusCode() + is( + rh.executePutRequest( + "_snapshot/" + index + "/" + index + "_2?wait_for_completion=true", + String.format(putSnapshot, index), + protectedIndexUserHeader + ).getStatusCode() + ) ); } } diff --git a/src/test/java/org/opensearch/security/securityconf/FlattenedActionGroupsTest.java b/src/test/java/org/opensearch/security/securityconf/FlattenedActionGroupsTest.java index 9e2bbd390b..7cea117d25 100644 --- a/src/test/java/org/opensearch/security/securityconf/FlattenedActionGroupsTest.java +++ b/src/test/java/org/opensearch/security/securityconf/FlattenedActionGroupsTest.java @@ -18,13 +18,15 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import org.junit.Assert; import org.junit.Test; import org.opensearch.security.securityconf.impl.CType; import org.opensearch.security.securityconf.impl.SecurityDynamicConfiguration; import org.opensearch.security.securityconf.impl.v7.ActionGroupsV7; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class FlattenedActionGroupsTest { @Test public void basicTest() throws Exception { @@ -42,11 +44,11 @@ public void basicTest() throws Exception { FlattenedActionGroups actionGroups = new FlattenedActionGroups(config); - Assert.assertEquals( + assertThat( ImmutableSet.of("C", "A", "A1", "A2", "A3", "C1", "B", "B1", "B2", "B3", "Z"), - actionGroups.resolve(ImmutableSet.of("Z")) + is(actionGroups.resolve(ImmutableSet.of("Z"))) ); - Assert.assertEquals(ImmutableSet.of("A", "A1", "A2", "A3"), actionGroups.resolve(ImmutableSet.of("A"))); + assertThat(actionGroups.resolve(ImmutableSet.of("A")), is(ImmutableSet.of("A", "A1", "A2", "A3"))); } /** @@ -70,9 +72,9 @@ public void cycleTest() throws Exception { FlattenedActionGroups actionGroups = new FlattenedActionGroups(config); - Assert.assertEquals(ImmutableSet.of("A", "A1", "B", "B1", "C", "C1", "D", "D1"), actionGroups.resolve(ImmutableSet.of("A"))); - Assert.assertEquals(ImmutableSet.of("A", "A1", "B", "B1", "C", "C1", "D", "D1"), actionGroups.resolve(ImmutableSet.of("C"))); - Assert.assertEquals(ImmutableSet.of("D", "D1"), actionGroups.resolve(ImmutableSet.of("D"))); + assertThat(actionGroups.resolve(ImmutableSet.of("A")), is(ImmutableSet.of("A", "A1", "B", "B1", "C", "C1", "D", "D1"))); + assertThat(actionGroups.resolve(ImmutableSet.of("C")), is(ImmutableSet.of("A", "A1", "B", "B1", "C", "C1", "D", "D1"))); + assertThat(actionGroups.resolve(ImmutableSet.of("D")), is(ImmutableSet.of("D", "D1"))); } private static class TestActionGroups { diff --git a/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java b/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java index a780b0066f..f2e5351019 100644 --- a/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java +++ b/src/test/java/org/opensearch/security/securityconf/impl/v6/ConfigV6Test.java @@ -34,52 +34,52 @@ public static Iterable omitDefaults() { } public void assertEquals(ConfigV6.Kibana expected, JsonNode node) { - Assert.assertEquals(expected.multitenancy_enabled, node.get("multitenancy_enabled").asBoolean()); + assertThat(node.get("multitenancy_enabled").asBoolean(), is(expected.multitenancy_enabled)); assertThat(node.get("sign_in_options").isArray(), is(true)); assertThat(node.get("sign_in_options").toString(), containsString(expected.sign_in_options.get(0).toString())); if (expected.server_username == null) { Assert.assertNull(node.get("server_username")); } else { - Assert.assertEquals(expected.server_username, node.get("server_username").asText()); + assertThat(node.get("server_username").asText(), is(expected.server_username)); } if (expected.index == null) { // null is not persisted Assert.assertNull(node.get("index")); } else { - Assert.assertEquals(expected.index, node.get("index").asText()); + assertThat(node.get("index").asText(), is(expected.index)); } if (expected.opendistro_role == null) { Assert.assertNull(node.get("opendistro_role")); } else { - Assert.assertEquals(expected.opendistro_role, node.get("opendistro_role").asText()); + assertThat(node.get("opendistro_role").asText(), is(expected.opendistro_role)); } if (omitDefaults && !expected.do_not_fail_on_forbidden) { // false (default) is not persisted Assert.assertNull(node.get("do_not_fail_on_forbidden")); } else { - Assert.assertEquals(expected.do_not_fail_on_forbidden, node.get("do_not_fail_on_forbidden").asBoolean()); + assertThat(node.get("do_not_fail_on_forbidden").asBoolean(), is(expected.do_not_fail_on_forbidden)); } } private void assertEquals(ConfigV6.Kibana expected, ConfigV6.Kibana actual) { - Assert.assertEquals(expected.multitenancy_enabled, actual.multitenancy_enabled); + assertThat(actual.multitenancy_enabled, is(expected.multitenancy_enabled)); assertThat(expected.sign_in_options, is(actual.sign_in_options)); if (expected.server_username == null) { // null is restored to default instead of null - Assert.assertEquals(new ConfigV6.Kibana().server_username, actual.server_username); + assertThat(actual.server_username, is(new ConfigV6.Kibana().server_username)); } else { - Assert.assertEquals(expected.server_username, actual.server_username); + assertThat(actual.server_username, is(expected.server_username)); } // null is restored to default (which is null). - Assert.assertEquals(expected.opendistro_role, actual.opendistro_role); + assertThat(actual.opendistro_role, is(expected.opendistro_role)); if (expected.index == null) { // null is restored to default instead of null - Assert.assertEquals(new ConfigV6.Kibana().index, actual.index); + assertThat(actual.index, is(new ConfigV6.Kibana().index)); } else { - Assert.assertEquals(expected.index, actual.index); + assertThat(actual.index, is(expected.index)); } - Assert.assertEquals(expected.do_not_fail_on_forbidden, actual.do_not_fail_on_forbidden); + assertThat(actual.do_not_fail_on_forbidden, is(expected.do_not_fail_on_forbidden)); } public ConfigV6Test(boolean omitDefaults) { @@ -120,7 +120,7 @@ public void testOnBehalfOfSettings() { ConfigV6.OnBehalfOfSettings oboSettings; oboSettings = new ConfigV6.OnBehalfOfSettings(); - Assert.assertEquals(oboSettings.getOboEnabled(), Boolean.FALSE); + assertThat(Boolean.FALSE, is(oboSettings.getOboEnabled())); Assert.assertNull(oboSettings.getSigningKey()); Assert.assertNull(oboSettings.getEncryptionKey()); } diff --git a/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java b/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java index 246247c6d9..df1835adff 100644 --- a/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java +++ b/src/test/java/org/opensearch/security/securityconf/impl/v7/ConfigV7Test.java @@ -34,44 +34,44 @@ public static Iterable omitDefaults() { } public void assertEquals(ConfigV7.Kibana expected, JsonNode node) { - Assert.assertEquals(expected.multitenancy_enabled, node.get("multitenancy_enabled").asBoolean()); + assertThat(node.get("multitenancy_enabled").asBoolean(), is(expected.multitenancy_enabled)); assertThat(node.get("sign_in_options").isArray(), is(true)); assertThat(node.get("sign_in_options").toString(), containsString(expected.sign_in_options.get(0).toString())); if (expected.server_username == null) { Assert.assertNull(node.get("server_username")); } else { - Assert.assertEquals(expected.server_username, node.get("server_username").asText()); + assertThat(node.get("server_username").asText(), is(expected.server_username)); } if (expected.index == null) { // null is not persisted Assert.assertNull(node.get("index")); } else { - Assert.assertEquals(expected.index, node.get("index").asText()); + assertThat(node.get("index").asText(), is(expected.index)); } if (expected.opendistro_role == null) { Assert.assertNull(node.get("opendistro_role")); } else { - Assert.assertEquals(expected.opendistro_role, node.get("opendistro_role").asText()); + assertThat(node.get("opendistro_role").asText(), is(expected.opendistro_role)); } } private void assertEquals(ConfigV7.Kibana expected, ConfigV7.Kibana actual) { - Assert.assertEquals(expected.multitenancy_enabled, actual.multitenancy_enabled); + assertThat(actual.multitenancy_enabled, is(expected.multitenancy_enabled)); assertThat(expected.sign_in_options, is(actual.sign_in_options)); if (expected.server_username == null) { // null is restored to default instead of null - Assert.assertEquals(new ConfigV7.Kibana().server_username, actual.server_username); + assertThat(actual.server_username, is(new ConfigV7.Kibana().server_username)); } else { - Assert.assertEquals(expected.server_username, actual.server_username); + assertThat(actual.server_username, is(expected.server_username)); } // null is restored to default (which is null). - Assert.assertEquals(expected.opendistro_role, actual.opendistro_role); + assertThat(actual.opendistro_role, is(expected.opendistro_role)); if (expected.index == null) { // null is restored to default instead of null - Assert.assertEquals(new ConfigV7.Kibana().index, actual.index); + assertThat(actual.index, is(new ConfigV7.Kibana().index)); } else { - Assert.assertEquals(expected.index, actual.index); + assertThat(actual.index, is(expected.index)); } } @@ -111,7 +111,7 @@ public void testOnBehalfOfSettings() { ConfigV7.OnBehalfOfSettings oboSettings; oboSettings = new ConfigV7.OnBehalfOfSettings(); - Assert.assertEquals(oboSettings.getOboEnabled(), Boolean.FALSE); + assertThat(Boolean.FALSE, is(oboSettings.getOboEnabled())); Assert.assertNull(oboSettings.getSigningKey()); Assert.assertNull(oboSettings.getEncryptionKey()); } diff --git a/src/test/java/org/opensearch/security/ssl/CertificateValidatorTest.java b/src/test/java/org/opensearch/security/ssl/CertificateValidatorTest.java index ce614a17ca..9a764cca24 100644 --- a/src/test/java/org/opensearch/security/ssl/CertificateValidatorTest.java +++ b/src/test/java/org/opensearch/security/ssl/CertificateValidatorTest.java @@ -40,6 +40,9 @@ import org.opensearch.security.ssl.util.ExceptionUtils; import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class CertificateValidatorTest { public static final Date CRL_DATE = new Date(1525546426000L); @@ -54,7 +57,7 @@ public void testStaticCRL() throws Exception { crls = CertificateFactory.getInstance("X.509").generateCRLs(crlin); } - Assert.assertEquals(crls.size(), 1); + assertThat(1, is(crls.size())); // trust chain incl intermediate certificates (root + intermediates) Collection rootCas; @@ -63,7 +66,7 @@ public void testStaticCRL() throws Exception { rootCas = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(rootCas.size(), 2); + assertThat(2, is(rootCas.size())); // certificate chain to validate (client cert + intermediates but without root) Collection certsToValidate; @@ -72,7 +75,7 @@ public void testStaticCRL() throws Exception { certsToValidate = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(certsToValidate.size(), 2); + assertThat(2, is(certsToValidate.size())); CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), crls); validator.setDate(CRL_DATE); @@ -93,7 +96,7 @@ public void testStaticCRLOk() throws Exception { crls = CertificateFactory.getInstance("X.509").generateCRLs(crlin); } - Assert.assertEquals(crls.size(), 1); + assertThat(1, is(crls.size())); // trust chain incl intermediate certificates (root + intermediates) Collection rootCas; @@ -102,7 +105,7 @@ public void testStaticCRLOk() throws Exception { rootCas = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(rootCas.size(), 2); + assertThat(2, is(rootCas.size())); // certificate chain to validate (client cert + intermediates but without root) Collection certsToValidate; @@ -111,7 +114,7 @@ public void testStaticCRLOk() throws Exception { certsToValidate = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(certsToValidate.size(), 3); + assertThat(3, is(certsToValidate.size())); CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), crls); validator.setDate(CRL_DATE); @@ -132,7 +135,7 @@ public void testNoValidationPossible() throws Exception { rootCas = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(rootCas.size(), 2); + assertThat(2, is(rootCas.size())); // certificate chain to validate (client cert + intermediates but without root) Collection certsToValidate; @@ -141,7 +144,7 @@ public void testNoValidationPossible() throws Exception { certsToValidate = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(certsToValidate.size(), 2); + assertThat(2, is(certsToValidate.size())); CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), Collections.emptyList()); validator.setDate(CRL_DATE); @@ -164,7 +167,7 @@ public void testCRLDP() throws Exception { rootCas = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(rootCas.size(), 1); + assertThat(1, is(rootCas.size())); // certificate chain to validate (client cert + intermediates but without root) Collection certsToValidate; @@ -174,7 +177,7 @@ public void testCRLDP() throws Exception { certsToValidate = (Collection) CertificateFactory.getInstance("X.509").generateCertificates(trin); } - Assert.assertEquals(certsToValidate.size(), 2); + assertThat(2, is(certsToValidate.size())); CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), Collections.emptyList()); validator.setEnableCRLDP(true); diff --git a/src/test/java/org/opensearch/security/ssl/OpenSSLTest.java b/src/test/java/org/opensearch/security/ssl/OpenSSLTest.java index 1758d7dc9c..170d6cc410 100644 --- a/src/test/java/org/opensearch/security/ssl/OpenSSLTest.java +++ b/src/test/java/org/opensearch/security/ssl/OpenSSLTest.java @@ -47,6 +47,9 @@ import io.netty.handler.ssl.OpenSsl; import io.netty.util.internal.PlatformDependent; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class OpenSSLTest extends SSLTest { private static final String USE_NETTY_DEFAULT_ALLOCATOR_PROPERTY = "opensearch.unsafe.use_netty_default_allocator"; private static String USE_NETTY_DEFAULT_ALLOCATOR; @@ -218,8 +221,8 @@ public void testNodeClientSSLwithOpenSslTLSv13() throws Exception { .health(new ClusterHealthRequest().waitForNodes("4").timeout(TimeValue.timeValueSeconds(5))) .actionGet(); Assert.assertFalse(res.isTimedOut()); - Assert.assertEquals(4, res.getNumberOfNodes()); - Assert.assertEquals(4, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(res.getNumberOfNodes(), is(4)); + assertThat(node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(4)); } Assert.assertFalse(rh.executeSimpleRequest("_nodes/stats?pretty").contains("\"tx_size_in_bytes\" : 0")); diff --git a/src/test/java/org/opensearch/security/ssl/SSLTest.java b/src/test/java/org/opensearch/security/ssl/SSLTest.java index b5135ebdb0..4e497be468 100644 --- a/src/test/java/org/opensearch/security/ssl/SSLTest.java +++ b/src/test/java/org/opensearch/security/ssl/SSLTest.java @@ -64,6 +64,8 @@ import io.netty.util.internal.PlatformDependent; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.ssl.SecureSSLSettings.SSLSetting.SECURITY_SSL_HTTP_KEYSTORE_KEYPASSWORD; import static org.opensearch.security.ssl.SecureSSLSettings.SSLSetting.SECURITY_SSL_HTTP_PEMKEY_PASSWORD; import static org.opensearch.security.ssl.SecureSSLSettings.SSLSetting.SECURITY_SSL_TRANSPORT_KEYSTORE_KEYPASSWORD; @@ -161,15 +163,15 @@ public void testCipherAndProtocols() throws Exception { String[] enabledProtocols = new DefaultSecurityKeyStore(settings, Paths.get(".")).createHTTPSSLEngine().getEnabledProtocols(); if (allowOpenSSL) { - Assert.assertEquals(2, enabledProtocols.length); // SSLv2Hello is always enabled when using openssl + assertThat(enabledProtocols.length, is(2)); // SSLv2Hello is always enabled when using openssl Assert.assertTrue("Check SSLv3", "SSLv3".equals(enabledProtocols[0]) || "SSLv3".equals(enabledProtocols[1])); - Assert.assertEquals(1, enabledCiphers.length); - Assert.assertEquals("TLS_RSA_EXPORT_WITH_RC4_40_MD5", enabledCiphers[0]); + assertThat(enabledCiphers.length, is(1)); + assertThat(enabledCiphers[0], is("TLS_RSA_EXPORT_WITH_RC4_40_MD5")); } else { - Assert.assertEquals(1, enabledProtocols.length); - Assert.assertEquals("SSLv3", enabledProtocols[0]); - Assert.assertEquals(1, enabledCiphers.length); - Assert.assertEquals("SSL_RSA_EXPORT_WITH_RC4_40_MD5", enabledCiphers[0]); + assertThat(enabledProtocols.length, is(1)); + assertThat(enabledProtocols[0], is("SSLv3")); + assertThat(enabledCiphers.length, is(1)); + assertThat(enabledCiphers[0], is("SSL_RSA_EXPORT_WITH_RC4_40_MD5")); } settings = Settings.builder() @@ -198,15 +200,15 @@ public void testCipherAndProtocols() throws Exception { enabledProtocols = new DefaultSecurityKeyStore(settings, Paths.get(".")).createServerTransportSSLEngine().getEnabledProtocols(); if (allowOpenSSL) { - Assert.assertEquals(2, enabledProtocols.length); // SSLv2Hello is always enabled when using openssl + assertThat(enabledProtocols.length, is(2)); // SSLv2Hello is always enabled when using openssl Assert.assertTrue("Check SSLv3", "SSLv3".equals(enabledProtocols[0]) || "SSLv3".equals(enabledProtocols[1])); - Assert.assertEquals(1, enabledCiphers.length); - Assert.assertEquals("TLS_RSA_EXPORT_WITH_RC4_40_MD5", enabledCiphers[0]); + assertThat(enabledCiphers.length, is(1)); + assertThat(enabledCiphers[0], is("TLS_RSA_EXPORT_WITH_RC4_40_MD5")); } else { - Assert.assertEquals(1, enabledProtocols.length); - Assert.assertEquals("SSLv3", enabledProtocols[0]); - Assert.assertEquals(1, enabledCiphers.length); - Assert.assertEquals("SSL_RSA_EXPORT_WITH_RC4_40_MD5", enabledCiphers[0]); + assertThat(enabledProtocols.length, is(1)); + assertThat(enabledProtocols[0], is("SSLv3")); + assertThat(enabledCiphers.length, is(1)); + assertThat(enabledCiphers[0], is("SSL_RSA_EXPORT_WITH_RC4_40_MD5")); } enabledCiphers = new DefaultSecurityKeyStore(settings, Paths.get(".")).createClientTransportSSLEngine(null, -1) .getEnabledCipherSuites(); @@ -214,15 +216,15 @@ public void testCipherAndProtocols() throws Exception { .getEnabledProtocols(); if (allowOpenSSL) { - Assert.assertEquals(2, enabledProtocols.length); // SSLv2Hello is always enabled when using openssl + assertThat(enabledProtocols.length, is(2)); // SSLv2Hello is always enabled when using openssl Assert.assertTrue("Check SSLv3", "SSLv3".equals(enabledProtocols[0]) || "SSLv3".equals(enabledProtocols[1])); - Assert.assertEquals(1, enabledCiphers.length); - Assert.assertEquals("TLS_RSA_EXPORT_WITH_RC4_40_MD5", enabledCiphers[0]); + assertThat(enabledCiphers.length, is(1)); + assertThat(enabledCiphers[0], is("TLS_RSA_EXPORT_WITH_RC4_40_MD5")); } else { - Assert.assertEquals(1, enabledProtocols.length); - Assert.assertEquals("SSLv3", enabledProtocols[0]); - Assert.assertEquals(1, enabledCiphers.length); - Assert.assertEquals("SSL_RSA_EXPORT_WITH_RC4_40_MD5", enabledCiphers[0]); + assertThat(enabledProtocols.length, is(1)); + assertThat(enabledProtocols[0], is("SSLv3")); + assertThat(enabledCiphers.length, is(1)); + assertThat(enabledCiphers[0], is("SSL_RSA_EXPORT_WITH_RC4_40_MD5")); } } catch (OpenSearchSecurityException e) { Assert.assertTrue( @@ -757,8 +759,8 @@ public void testNodeClientSSL() throws Exception { .health(new ClusterHealthRequest().waitForNodes("4").timeout(TimeValue.timeValueSeconds(15))) .actionGet(); Assert.assertFalse(res.isTimedOut()); - Assert.assertEquals(4, res.getNumberOfNodes()); - Assert.assertEquals(4, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(res.getNumberOfNodes(), is(4)); + assertThat(node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(4)); } String res = rh.executeSimpleRequest("_nodes/stats?pretty"); @@ -788,7 +790,7 @@ public void testAvailCiphers() throws Exception { @Test public void testUnmodifieableCipherProtocolConfig() throws Exception { SSLConfigConstants.getSecureSSLProtocols(Settings.EMPTY, false)[0] = "bogus"; - Assert.assertEquals("TLSv1.3", SSLConfigConstants.getSecureSSLProtocols(Settings.EMPTY, false)[0]); + assertThat(SSLConfigConstants.getSecureSSLProtocols(Settings.EMPTY, false)[0], is("TLSv1.3")); try { SSLConfigConstants.getSecureSSLCiphers(Settings.EMPTY, false).set(0, "bogus"); @@ -849,21 +851,23 @@ public void testCustomPrincipalExtractor() throws Exception { log.debug("Client built, connect now to {}:{}", clusterInfo.nodeHost, clusterInfo.httpPort); - Assert.assertEquals(3, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(3)); log.debug("Client connected"); TestPrincipalExtractor.reset(); - Assert.assertEquals( + assertThat( "test", - tc.index(new IndexRequest("test").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"a\":5}", XContentType.JSON)) - .actionGet() - .getIndex() + is( + tc.index(new IndexRequest("test").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"a\":5}", XContentType.JSON)) + .actionGet() + .getIndex() + ) ); log.debug("Index created"); - Assert.assertEquals(1L, tc.search(new SearchRequest("test")).actionGet().getHits().getTotalHits().value); + assertThat(tc.search(new SearchRequest("test")).actionGet().getHits().getTotalHits().value, is(1L)); log.debug("Search done"); - Assert.assertEquals(3, tc.admin().cluster().health(new ClusterHealthRequest("test")).actionGet().getNumberOfNodes()); + assertThat(tc.admin().cluster().health(new ClusterHealthRequest("test")).actionGet().getNumberOfNodes(), is(3)); log.debug("ClusterHealth done"); - Assert.assertEquals(3, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(3)); log.debug("NodesInfoRequest asserted"); } @@ -1005,8 +1009,8 @@ public void testNodeClientSSLwithJavaTLSv13() throws Exception { .health(new ClusterHealthRequest().waitForNodes("4").timeout(TimeValue.timeValueSeconds(5))) .actionGet(); Assert.assertFalse(res.isTimedOut()); - Assert.assertEquals(4, res.getNumberOfNodes()); - Assert.assertEquals(4, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(res.getNumberOfNodes(), is(4)); + assertThat(node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(4)); } String res = rh.executeSimpleRequest("_nodes/stats?pretty"); diff --git a/src/test/java/org/opensearch/security/ssl/SecureSSLSettingsTest.java b/src/test/java/org/opensearch/security/ssl/SecureSSLSettingsTest.java index beb170a31a..f68f28db27 100644 --- a/src/test/java/org/opensearch/security/ssl/SecureSSLSettingsTest.java +++ b/src/test/java/org/opensearch/security/ssl/SecureSSLSettingsTest.java @@ -10,6 +10,8 @@ import org.opensearch.common.settings.MockSecureSettings; import org.opensearch.common.settings.Settings; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.ssl.SecureSSLSettings.SSLSetting.SECURITY_SSL_HTTP_PEMKEY_PASSWORD; public class SecureSSLSettingsTest { @@ -26,14 +28,14 @@ public void testGetSecureSetting() { mockSecureSettings.setString(SECURITY_SSL_HTTP_PEMKEY_PASSWORD.propertyName, "test-password"); final var settings = Settings.builder().setSecureSettings(mockSecureSettings).build(); final var password = SECURITY_SSL_HTTP_PEMKEY_PASSWORD.getSetting(settings); - Assert.assertEquals("test-password", password); + assertThat(password, is("test-password")); } @Test public void testGetInsecureSetting() { final var settings = Settings.builder().put(SECURITY_SSL_HTTP_PEMKEY_PASSWORD.insecurePropertyName, "test-password").build(); final var password = SECURITY_SSL_HTTP_PEMKEY_PASSWORD.getSetting(settings); - Assert.assertEquals("test-password", password); + assertThat(password, is("test-password")); } @Test @@ -45,6 +47,6 @@ public void testShouldFavorSecureOverInsecureSetting() { .put(SECURITY_SSL_HTTP_PEMKEY_PASSWORD.insecurePropertyName, "insecure-password") .build(); final var password = SECURITY_SSL_HTTP_PEMKEY_PASSWORD.getSetting(settings); - Assert.assertEquals("secure-password", password); + assertThat(password, is("secure-password")); } } diff --git a/src/test/java/org/opensearch/security/ssl/SecuritySSLReloadCertsActionTests.java b/src/test/java/org/opensearch/security/ssl/SecuritySSLReloadCertsActionTests.java index fe201fc2e8..9669f17c7f 100644 --- a/src/test/java/org/opensearch/security/ssl/SecuritySSLReloadCertsActionTests.java +++ b/src/test/java/org/opensearch/security/ssl/SecuritySSLReloadCertsActionTests.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.databind.JsonNode; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -34,6 +33,9 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SecuritySSLReloadCertsActionTests extends SingleClusterTest { private final ClusterConfiguration clusterConfiguration = ClusterConfiguration.DEFAULT; @@ -94,11 +96,11 @@ public void checkClusterHealth() throws Exception { String clusterHealthResponse = rh.executeSimpleRequest("_cluster/health"); final var clusterHealthResponseJson = DefaultObjectMapper.readTree(clusterHealthResponse); - Assert.assertEquals("green", clusterHealthResponseJson.get("status").asText()); + assertThat(clusterHealthResponseJson.get("status").asText(), is("green")); String catNodesResponse = rh.executeSimpleRequest("_cat/nodes?format=json"); final var catNodesResponseJson = DefaultObjectMapper.readTree(catNodesResponse);// (JSONArray) parser.parse(catNodesResponse); - Assert.assertEquals(clusterConfiguration.getNodes(), catNodesResponseJson.size()); + assertThat(catNodesResponseJson.size(), is(clusterConfiguration.getNodes())); } @Test @@ -108,7 +110,7 @@ public void testReloadTransportSSLCertsPass() throws Exception { String certDetailsResponse = rh.executeSimpleRequest(GET_CERT_DETAILS_ENDPOINT); final var expectedJsonResponse = getInitCertDetailsExpectedResponse(); - Assert.assertEquals(expectedJsonResponse, DefaultObjectMapper.readTree(certDetailsResponse)); + assertThat(DefaultObjectMapper.readTree(certDetailsResponse), is(expectedJsonResponse)); // Test Valid Case: Change transport file details to "ssl/pem/node-new.crt.pem" and "ssl/pem/node-new.key.pem" updateFiles(newCertFilePath, pemCertFilePath); @@ -125,7 +127,7 @@ public void testReloadHttpSSLCertsPass() throws Exception { String certDetailsResponse = rh.executeSimpleRequest(GET_CERT_DETAILS_ENDPOINT); final var expectedJsonResponse = getInitCertDetailsExpectedResponse(); - Assert.assertEquals(expectedJsonResponse, DefaultObjectMapper.readTree(certDetailsResponse)); + assertThat(DefaultObjectMapper.readTree(certDetailsResponse), is(expectedJsonResponse)); // Test Valid Case: Change rest file details to "ssl/pem/node-new.crt.pem" and "ssl/pem/node-new.key.pem" updateFiles(newCertFilePath, pemCertFilePath); @@ -143,11 +145,11 @@ public void testSSLReloadFail_InvalidDNAndDate() throws Exception { updateFiles("ssl/reload/node-wrong.key.pem", pemKeyFilePath); RestHelper.HttpResponse reloadCertsResponse = rh.executePutRequest(RELOAD_TRANSPORT_CERTS_ENDPOINT, null); - Assert.assertEquals(500, reloadCertsResponse.getStatusCode()); - Assert.assertEquals( + assertThat(reloadCertsResponse.getStatusCode(), is(500)); + assertThat( "OpenSearchSecurityException[Error while initializing transport SSL layer from PEM: java.lang.Exception: " + "New Certs do not have valid Issuer DN, Subject DN or SAN.]; nested: Exception[New Certs do not have valid Issuer DN, Subject DN or SAN.];", - DefaultObjectMapper.readTree(reloadCertsResponse.getBody()).get("error").get("root_cause").get(0).get("reason").asText() + is(DefaultObjectMapper.readTree(reloadCertsResponse.getBody()).get("error").get("root_cause").get(0).get("reason").asText()) ); } @@ -159,7 +161,7 @@ public void testReloadTransportSSLSameCertsPass() throws Exception { String certDetailsResponse = rh.executeSimpleRequest(GET_CERT_DETAILS_ENDPOINT); final var expectedJsonResponse = getInitCertDetailsExpectedResponse(); - Assert.assertEquals(expectedJsonResponse, DefaultObjectMapper.readTree(certDetailsResponse)); + assertThat(DefaultObjectMapper.readTree(certDetailsResponse), is(expectedJsonResponse)); // Test Valid Case: Reload same certificate updateFiles(defaultCertFilePath, pemCertFilePath); @@ -175,7 +177,7 @@ public void testReloadHttpSSLSameCertsPass() throws Exception { String certDetailsResponse = rh.executeSimpleRequest(GET_CERT_DETAILS_ENDPOINT); final var expectedJsonResponse = getInitCertDetailsExpectedResponse(); - Assert.assertEquals(expectedJsonResponse, DefaultObjectMapper.readTree(certDetailsResponse)); + assertThat(DefaultObjectMapper.readTree(certDetailsResponse), is(expectedJsonResponse)); // Test Valid Case: Reload same certificate updateFiles(defaultCertFilePath, pemCertFilePath); @@ -196,13 +198,13 @@ private void assertReloadCertificateSuccess(RestHelper rh, String updateChannel, String reloadEndpoint = updateChannel.equals("http") ? RELOAD_HTTP_CERTS_ENDPOINT : RELOAD_TRANSPORT_CERTS_ENDPOINT; RestHelper.HttpResponse reloadCertsResponse = rh.executePutRequest(reloadEndpoint, null); - Assert.assertEquals(200, reloadCertsResponse.getStatusCode()); + assertThat(reloadCertsResponse.getStatusCode(), is(200)); final var expectedJsonResponse = DefaultObjectMapper.objectMapper.createObjectNode(); expectedJsonResponse.put("message", String.format("updated %s certs", updateChannel)); - Assert.assertEquals(expectedJsonResponse.toString(), reloadCertsResponse.getBody()); + assertThat(reloadCertsResponse.getBody(), is(expectedJsonResponse.toString())); String certDetailsResponse = rh.executeSimpleRequest(GET_CERT_DETAILS_ENDPOINT); - Assert.assertEquals(expectedCertResponse, DefaultObjectMapper.readTree(certDetailsResponse)); + assertThat(DefaultObjectMapper.readTree(certDetailsResponse), is(expectedCertResponse)); } private void updateFiles(String srcFile, String dstFile) { diff --git a/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java b/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java index 097d65472c..c62de20cd5 100644 --- a/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/CertFromFileTests.java @@ -18,6 +18,9 @@ import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class CertFromFileTests { @Test @@ -31,7 +34,7 @@ public void testLoadSameCertForClientServerUsage() throws Exception { CertFromFile cert = new CertFromFile(certProps); - Assert.assertEquals(1, cert.getCerts().length); + assertThat(cert.getCerts().length, is(1)); Assert.assertNotNull(cert.getClientPemCert()); Assert.assertNotNull(cert.getClientPemKey()); Assert.assertNotNull(cert.getClientTrustedCas()); @@ -80,7 +83,7 @@ public void testLoadDifferentCertsForClientServerUsage() throws Exception { CertFromFile cert = new CertFromFile(clientCertProps, servertCertProps); - Assert.assertEquals(2, cert.getCerts().length); + assertThat(cert.getCerts().length, is(2)); } } diff --git a/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java b/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java index fb97fdcfd1..62befc9893 100644 --- a/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/CertFromKeystoreTests.java @@ -22,6 +22,9 @@ import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class CertFromKeystoreTests { @Test @@ -36,7 +39,7 @@ public void testLoadSameCertForClientServerUsage() throws UnrecoverableKeyExcept CertFromKeystore cert = new CertFromKeystore(props, "node-0", "changeit"); // second cert is Signing cert - Assert.assertEquals(2, cert.getCerts().length); + assertThat(cert.getCerts().length, is(2)); Assert.assertTrue(cert.getCerts()[0].getSubjectDN().getName().contains("node-0")); Assert.assertNotNull(cert.getServerKey()); @@ -55,7 +58,7 @@ public void testLoadSameCertWithoutAlias() throws UnrecoverableKeyException, Cer CertFromKeystore cert = new CertFromKeystore(props, null, "changeit"); // second cert is Signing cert - Assert.assertEquals(2, cert.getCerts().length); + assertThat(cert.getCerts().length, is(2)); Assert.assertTrue(cert.getCerts()[0].getSubjectDN().getName().contains("node-0")); } @@ -70,7 +73,7 @@ public void testLoadDifferentCertsForClientServerUsage() throws UnrecoverableKey CertFromKeystore cert = new CertFromKeystore(props, "node-0-server", "node-0-client", "changeit", "changeit"); - Assert.assertEquals(4, cert.getCerts().length); + assertThat(cert.getCerts().length, is(4)); Assert.assertTrue(cert.getClientCert()[0].getSubjectDN().getName().contains("node-client")); Assert.assertTrue(cert.getServerCert()[0].getSubjectDN().getName().contains("node-server")); diff --git a/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java b/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java index e4ab860759..c7d2b85fc1 100644 --- a/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/CertFromTruststoreTests.java @@ -21,6 +21,9 @@ import org.opensearch.security.test.helper.file.FileHelper; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class CertFromTruststoreTests { @Test @@ -34,7 +37,7 @@ public void testLoadSameCertForClientServerUsage() throws CertificateException, CertFromTruststore cert = new CertFromTruststore(props, "root-ca"); - Assert.assertEquals(1, cert.getClientTrustedCerts().length); + assertThat(cert.getClientTrustedCerts().length, is(1)); Assert.assertTrue(cert.getClientTrustedCerts().equals(cert.getServerTrustedCerts())); } @@ -48,7 +51,7 @@ public void testLoadSameCertWithoutAlias() throws CertificateException, NoSuchAl CertFromTruststore cert = new CertFromTruststore(props, null); - Assert.assertEquals(1, cert.getClientTrustedCerts().length); + assertThat(cert.getClientTrustedCerts().length, is(1)); } public void testLoadDifferentCertsForClientServerUsage() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, @@ -61,8 +64,8 @@ public void testLoadDifferentCertsForClientServerUsage() throws CertificateExcep CertFromTruststore cert = new CertFromTruststore(props, "root-ca", "root-ca"); - Assert.assertEquals(1, cert.getClientTrustedCerts().length); - Assert.assertEquals(1, cert.getServerTrustedCerts().length); + assertThat(cert.getClientTrustedCerts().length, is(1)); + assertThat(cert.getServerTrustedCerts().length, is(1)); // we are loading same cert twice Assert.assertFalse(cert.getClientTrustedCerts().equals(cert.getServerTrustedCerts())); } diff --git a/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java b/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java index be9617b868..2baf819509 100644 --- a/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java +++ b/src/test/java/org/opensearch/security/ssl/util/SSLConnectionTestUtilTests.java @@ -17,13 +17,15 @@ import java.io.OutputStreamWriter; import java.net.Socket; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class SSLConnectionTestUtilTests { private Socket socket; private OutputStream outputStream; @@ -64,7 +66,7 @@ public void testConnectionSSLAvailable() throws Exception { verifyClientHelloSend(); Mockito.verify(socket, Mockito.times(1)).close(); - Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.SSL_AVAILABLE, result); + assertThat("Unexpected result for testConnection invocation", result, is(SSLConnectionTestResult.SSL_AVAILABLE)); } @Test @@ -85,7 +87,7 @@ public void testConnectionSSLNotAvailable() throws Exception { verifyClientHelloSend(); verifyOpenSearchPingSend(); Mockito.verify(socket, Mockito.times(2)).close(); - Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.SSL_NOT_AVAILABLE, result); + assertThat("Unexpected result for testConnection invocation", result, is(SSLConnectionTestResult.SSL_NOT_AVAILABLE)); } @Test @@ -107,7 +109,7 @@ public void testConnectionSSLNotAvailableIOException() throws Exception { Mockito.verifyNoInteractions(inputStreamReader); verifyOpenSearchPingSend(); Mockito.verify(socket, Mockito.times(2)).close(); - Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.SSL_NOT_AVAILABLE, result); + assertThat("Unexpected result for testConnection invocation", result, is(SSLConnectionTestResult.SSL_NOT_AVAILABLE)); } @Test @@ -131,7 +133,7 @@ public void testConnectionOpenSearchPingFailed() throws Exception { verifyClientHelloSend(); verifyOpenSearchPingSend(); Mockito.verify(socket, Mockito.times(2)).close(); - Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.OPENSEARCH_PING_FAILED, result); + assertThat("Unexpected result for testConnection invocation", result, is(SSLConnectionTestResult.OPENSEARCH_PING_FAILED)); } @Test @@ -161,7 +163,7 @@ public void testConnectionOpenSearchPingFailedInvalidReply() throws Exception { verifyClientHelloSend(); verifyOpenSearchPingSend(); Mockito.verify(socket, Mockito.times(2)).close(); - Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.OPENSEARCH_PING_FAILED, result); + assertThat("Unexpected result for testConnection invocation", result, is(SSLConnectionTestResult.OPENSEARCH_PING_FAILED)); } @Test @@ -185,7 +187,7 @@ public void testConnectionOpenSearchPingFailedIOException() throws Exception { verifyOpenSearchPingSend(); Mockito.verifyNoInteractions(inputStream); Mockito.verify(socket, Mockito.times(2)).close(); - Assert.assertEquals("Unexpected result for testConnection invocation", SSLConnectionTestResult.OPENSEARCH_PING_FAILED, result); + assertThat("Unexpected result for testConnection invocation", result, is(SSLConnectionTestResult.OPENSEARCH_PING_FAILED)); } private void verifyClientHelloSend() throws IOException { @@ -193,7 +195,7 @@ private void verifyClientHelloSend() throws IOException { Mockito.verify(outputStreamWriter, Mockito.times(1)).write(clientHelloMsgArgCaptor.capture()); String msgWritten = clientHelloMsgArgCaptor.getValue(); String expectedMsg = "DUALCM"; - Assert.assertEquals("Unexpected Dual SSL Client Hello message written to socket", expectedMsg, msgWritten); + assertThat("Unexpected Dual SSL Client Hello message written to socket", msgWritten, is(expectedMsg)); } private void verifyOpenSearchPingSend() throws IOException { @@ -202,7 +204,7 @@ private void verifyOpenSearchPingSend() throws IOException { byte[] bytesWritten = argumentCaptor.getValue(); byte[] expectedBytes = new byte[] { 'E', 'S', (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; for (int i = 0; i < bytesWritten.length; i++) { - Assert.assertEquals("Unexpected OpenSearch Ping bytes written to socket", expectedBytes[i], bytesWritten[i]); + assertThat("Unexpected OpenSearch Ping bytes written to socket", bytesWritten[i], is(expectedBytes[i])); } } diff --git a/src/test/java/org/opensearch/security/state/SecurityMetadataSerializationTestCase.java b/src/test/java/org/opensearch/security/state/SecurityMetadataSerializationTestCase.java index c52f37cf54..43cde36a15 100644 --- a/src/test/java/org/opensearch/security/state/SecurityMetadataSerializationTestCase.java +++ b/src/test/java/org/opensearch/security/state/SecurityMetadataSerializationTestCase.java @@ -35,7 +35,8 @@ import org.opensearch.security.securityconf.impl.CType; import org.opensearch.test.DiffableTestUtils; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotSame; @RunWith(RandomizedRunner.class) @@ -102,8 +103,8 @@ void assertSerialization(ClusterState.Custom testInstance, Version version) thro void assertEqualInstances(ClusterState.Custom expectedInstance, ClusterState.Custom newInstance) { assertNotSame(newInstance, expectedInstance); - assertEquals(expectedInstance, newInstance); - assertEquals(expectedInstance.hashCode(), newInstance.hashCode()); + assertThat(newInstance, is(expectedInstance)); + assertThat(newInstance.hashCode(), is(expectedInstance.hashCode())); } @Test diff --git a/src/test/java/org/opensearch/security/support/Base64CustomHelperTest.java b/src/test/java/org/opensearch/security/support/Base64CustomHelperTest.java index afba688af7..a5151be9fb 100644 --- a/src/test/java/org/opensearch/security/support/Base64CustomHelperTest.java +++ b/src/test/java/org/opensearch/security/support/Base64CustomHelperTest.java @@ -31,6 +31,8 @@ import com.amazon.dlic.auth.ldap.LdapUser; import org.ldaptive.LdapEntry; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.support.Base64CustomHelper.deserializeObject; import static org.opensearch.security.support.Base64CustomHelper.serializeObject; @@ -54,37 +56,37 @@ private static Serializable ds(Serializable s) { @Test public void testString() { String string = "string"; - Assert.assertEquals(string, ds(string)); + assertThat(ds(string), is(string)); } @Test public void testInteger() { Integer integer = 0; - Assert.assertEquals(integer, ds(integer)); + assertThat(ds(integer), is(integer)); } @Test public void testDouble() { Double number = 0.; - Assert.assertEquals(number, ds(number)); + assertThat(ds(number), is(number)); } @Test public void testInetSocketAddress() { InetSocketAddress inetSocketAddress = new InetSocketAddress(0); - Assert.assertEquals(inetSocketAddress, ds(inetSocketAddress)); + assertThat(ds(inetSocketAddress), is(inetSocketAddress)); } @Test public void testUser() { User user = new User("user"); - Assert.assertEquals(user, ds(user)); + assertThat(ds(user), is(user)); } @Test public void testSourceFieldsContext() { SourceFieldsContext sourceFieldsContext = new SourceFieldsContext(new SearchRequest("")); - Assert.assertEquals(sourceFieldsContext.toString(), ds(sourceFieldsContext).toString()); + assertThat(ds(sourceFieldsContext).toString(), is(sourceFieldsContext.toString())); } @Test @@ -94,7 +96,7 @@ public void testHashMap() { put("key", "value"); } }; - Assert.assertEquals(map, ds(map)); + assertThat(ds(map), is(map)); } @Test @@ -104,7 +106,7 @@ public void testArrayList() { add("value"); } }; - Assert.assertEquals(list, ds(list)); + assertThat(ds(list), is(list)); } @Test @@ -117,17 +119,17 @@ public void testLdapUser() { 34, WildcardMatcher.ANY ); - Assert.assertEquals(ldapUser, ds(ldapUser)); + assertThat(ds(ldapUser), is(ldapUser)); } @Test public void testGetWriteableClassID() { // a need to make a change in this test signifies a breaking change in security plugin's custom serialization // format - Assert.assertEquals(Integer.valueOf(1), Base64CustomHelper.getWriteableClassID(User.class)); - Assert.assertEquals(Integer.valueOf(2), Base64CustomHelper.getWriteableClassID(LdapUser.class)); - Assert.assertEquals(Integer.valueOf(3), Base64CustomHelper.getWriteableClassID(UserInjector.InjectedUser.class)); - Assert.assertEquals(Integer.valueOf(4), Base64CustomHelper.getWriteableClassID(SourceFieldsContext.class)); + assertThat(Base64CustomHelper.getWriteableClassID(User.class), is(Integer.valueOf(1))); + assertThat(Base64CustomHelper.getWriteableClassID(LdapUser.class), is(Integer.valueOf(2))); + assertThat(Base64CustomHelper.getWriteableClassID(UserInjector.InjectedUser.class), is(Integer.valueOf(3))); + assertThat(Base64CustomHelper.getWriteableClassID(SourceFieldsContext.class), is(Integer.valueOf(4))); } @Test @@ -136,7 +138,7 @@ public void testInjectedUser() { // for custom serialization, we expect InjectedUser to be returned on deserialization UserInjector.InjectedUser deserializedInjecteduser = (UserInjector.InjectedUser) ds(injectedUser); - Assert.assertEquals(injectedUser, deserializedInjecteduser); + assertThat(deserializedInjecteduser, is(injectedUser)); Assert.assertTrue(deserializedInjecteduser.isInjected()); } diff --git a/src/test/java/org/opensearch/security/support/Base64HelperTest.java b/src/test/java/org/opensearch/security/support/Base64HelperTest.java index 32d96767d8..de21c67d52 100644 --- a/src/test/java/org/opensearch/security/support/Base64HelperTest.java +++ b/src/test/java/org/opensearch/security/support/Base64HelperTest.java @@ -14,14 +14,13 @@ import java.util.HashMap; import java.util.stream.IntStream; -import org.junit.Assert; import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.closeTo; -import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.support.Base64Helper.deserializeObject; import static org.opensearch.security.support.Base64Helper.serializeObject; -import static org.junit.Assert.assertThat; public class Base64HelperTest { @@ -41,8 +40,8 @@ private static Serializable ds(Serializable s) { @Test public void testSerde() { String test = "string"; - Assert.assertEquals(test, ds(test)); - Assert.assertEquals(test, dsJDK(test)); + assertThat(ds(test), is(test)); + assertThat(dsJDK(test), is(test)); } @Test @@ -50,8 +49,8 @@ public void testEnsureJDKSerialized() { String test = "string"; String jdkSerialized = Base64Helper.serializeObject(test, true); String customSerialized = Base64Helper.serializeObject(test, false); - Assert.assertEquals(jdkSerialized, Base64Helper.ensureJDKSerialized(jdkSerialized)); - Assert.assertEquals(jdkSerialized, Base64Helper.ensureJDKSerialized(customSerialized)); + assertThat(Base64Helper.ensureJDKSerialized(jdkSerialized), is(jdkSerialized)); + assertThat(Base64Helper.ensureJDKSerialized(customSerialized), is(jdkSerialized)); } @Test @@ -65,9 +64,9 @@ public void testDuplicatedItemSizes() { final var customSerialized = Base64Helper.serializeObject(largeObject, false); final var customSerializedOnlyHashMap = Base64Helper.serializeObject(hm, false); - assertThat(jdkSerialized.length(), equalTo(3832)); + assertThat(jdkSerialized.length(), is(3832)); // The custom serializer is ~50x larger than the jdk serialized version - assertThat(customSerialized.length(), equalTo(184792)); + assertThat(customSerialized.length(), is(184792)); // Show that the majority of the size of the custom serialized large object is the map duplicated ~100 times assertThat((double) customSerializedOnlyHashMap.length(), closeTo(customSerialized.length() / 100, 70d)); } diff --git a/src/test/java/org/opensearch/security/support/Base64JDKHelperTest.java b/src/test/java/org/opensearch/security/support/Base64JDKHelperTest.java index 4aab76bbae..8737f5b6ac 100644 --- a/src/test/java/org/opensearch/security/support/Base64JDKHelperTest.java +++ b/src/test/java/org/opensearch/security/support/Base64JDKHelperTest.java @@ -33,6 +33,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThrows; public class Base64JDKHelperTest { @@ -47,51 +48,51 @@ private static Serializable ds(Serializable s) { @Test public void testString() { String string = "string"; - Assert.assertEquals(string, ds(string)); + assertThat(ds(string), is(string)); } @Test public void testInteger() { Integer integer = 0; - Assert.assertEquals(integer, ds(integer)); + assertThat(ds(integer), is(integer)); } @Test public void testDouble() { Double number = 0.0; - Assert.assertEquals(number, ds(number)); + assertThat(ds(number), is(number)); } @Test public void testInetSocketAddress() { InetSocketAddress inetSocketAddress = new InetSocketAddress(0); - Assert.assertEquals(inetSocketAddress, ds(inetSocketAddress)); + assertThat(ds(inetSocketAddress), is(inetSocketAddress)); } @Test public void testUser() { User user = new User("user"); - Assert.assertEquals(user, ds(user)); + assertThat(ds(user), is(user)); } @Test public void testSourceFieldsContext() { SourceFieldsContext sourceFieldsContext = new SourceFieldsContext(new SearchRequest("")); - Assert.assertEquals(sourceFieldsContext.toString(), ds(sourceFieldsContext).toString()); + assertThat(ds(sourceFieldsContext).toString(), is(sourceFieldsContext.toString())); } @Test public void testHashMap() { HashMap map = new HashMap<>(); map.put("key", "value"); - Assert.assertEquals(map, ds(map)); + assertThat(ds(map), is(map)); } @Test public void testArrayList() { ArrayList list = new ArrayList<>(); list.add("value"); - Assert.assertEquals(list, ds(list)); + assertThat(ds(list), is(list)); } @Test @@ -126,7 +127,7 @@ public void testLdapUser() { 34, WildcardMatcher.ANY ); - Assert.assertEquals(ldapUser, ds(ldapUser)); + assertThat(ds(ldapUser), is(ldapUser)); } @Test @@ -136,7 +137,7 @@ public void testInjectedUser() { // we expect to get User object when deserializing InjectedUser via JDK serialization User user = new User("username"); User deserializedUser = (User) ds(injectedUser); - Assert.assertEquals(user, deserializedUser); + assertThat(deserializedUser, is(user)); Assert.assertTrue(deserializedUser.isInjected()); } } diff --git a/src/test/java/org/opensearch/security/support/ConfigReaderTest.java b/src/test/java/org/opensearch/security/support/ConfigReaderTest.java index 189b92ff68..b75d5a6e35 100644 --- a/src/test/java/org/opensearch/security/support/ConfigReaderTest.java +++ b/src/test/java/org/opensearch/security/support/ConfigReaderTest.java @@ -21,8 +21,9 @@ import org.opensearch.security.DefaultObjectMapper; import org.opensearch.security.securityconf.impl.CType; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.configuration.ConfigurationRepository.DEFAULT_CONFIG_VERSION; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -54,8 +55,8 @@ public void testCreateReaderForNonMandatoryCTypes() throws IOException { assertTrue(emptyYaml.has("_meta")); final var meta = emptyYaml.get("_meta"); - assertEquals(cType.toLCString(), meta.get("type").asText()); - assertEquals(DEFAULT_CONFIG_VERSION, meta.get("config_version").asInt()); + assertThat(meta.get("type").asText(), is(cType.toLCString())); + assertThat(meta.get("config_version").asInt(), is(DEFAULT_CONFIG_VERSION)); } } } diff --git a/src/test/java/org/opensearch/security/support/SecurityIndexHandlerTest.java b/src/test/java/org/opensearch/security/support/SecurityIndexHandlerTest.java index 170f0a9853..e121218af4 100644 --- a/src/test/java/org/opensearch/security/support/SecurityIndexHandlerTest.java +++ b/src/test/java/org/opensearch/security/support/SecurityIndexHandlerTest.java @@ -58,9 +58,9 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; import static org.opensearch.security.configuration.ConfigurationRepository.DEFAULT_CONFIG_VERSION; import static org.opensearch.security.support.YamlConfigReader.emptyYamlConfigFor; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -172,19 +172,19 @@ public void testCreateIndex_shouldCreateIndex() { verify(indicesAdminClient).create(requestCaptor.capture(), any()); final var createRequest = requestCaptor.getValue(); - assertEquals(INDEX_NAME, createRequest.index()); + assertThat(createRequest.index(), is(INDEX_NAME)); for (final var setting : SecurityIndexHandler.INDEX_SETTINGS.entrySet()) - assertEquals(setting.getValue().toString(), createRequest.settings().get(setting.getKey())); + assertThat(createRequest.settings().get(setting.getKey()), is(setting.getValue().toString())); - assertEquals(ActiveShardCount.ONE, createRequest.waitForActiveShards()); + assertThat(createRequest.waitForActiveShards(), is(ActiveShardCount.ONE)); } @Test public void testCreateIndex_shouldReturnSecurityExceptionIfItCanNotCreateIndex() { final var listener = spy(ActionListener.wrap(r -> fail("Unexpected behave"), e -> { - assertEquals(SecurityException.class, e.getClass()); - assertEquals("Couldn't create security index " + INDEX_NAME, e.getMessage()); + assertThat(e.getClass(), is(SecurityException.class)); + assertThat(e.getMessage(), is("Couldn't create security index " + INDEX_NAME)); })); doAnswer(invocation -> { @@ -202,7 +202,7 @@ public void testCreateIndex_shouldReturnSecurityExceptionIfItCanNotCreateIndex() @Test public void testUploadDefaultConfiguration_shouldFailIfRequiredConfigFilesAreMissing() { final var listener = spy(ActionListener.>wrap(r -> fail("Unexpected behave"), e -> { - assertEquals(SecurityException.class, e.getClass()); + assertThat(e.getClass(), is(SecurityException.class)); assertThat(e.getMessage(), containsString("Couldn't find configuration file")); })); securityIndexHandler.uploadDefaultConfiguration(configFolder, listener); @@ -218,8 +218,8 @@ public void testUploadDefaultConfiguration_shouldFailIfBulkHasFailures() throws 100L ); final var listener = spy(ActionListener.>wrap(r -> fail("Unexpected behave"), e -> { - assertEquals(SecurityException.class, e.getClass()); - assertEquals(e.getMessage(), failedBulkResponse.buildFailureMessage()); + assertThat(e.getClass(), is(SecurityException.class)); + assertThat(failedBulkResponse.buildFailureMessage(), is(e.getMessage())); })); doAnswer(invocation -> { ActionListener actionListener = invocation.getArgument(1); @@ -268,8 +268,8 @@ public void testUploadDefaultConfiguration_shouldCreateSetOfSecurityConfigs() th final var bulkRequest = bulkRequestCaptor.getValue(); for (final var r : bulkRequest.requests()) { final var indexRequest = (IndexRequest) r; - assertEquals(INDEX_NAME, r.index()); - assertEquals(DocWriteRequest.OpType.INDEX, indexRequest.opType()); + assertThat(r.index(), is(INDEX_NAME)); + assertThat(indexRequest.opType(), is(DocWriteRequest.OpType.INDEX)); } verify(listener).onResponse(any()); } @@ -337,7 +337,7 @@ public void testLoadConfiguration_shouldFailIfResponseHasFailures() { final var listener = spy( ActionListener.>>wrap( r -> fail("Unexpected behave"), - e -> assertEquals(SecurityException.class, e.getClass()) + e -> assertThat(e.getClass(), is(SecurityException.class)) ) ); @@ -361,7 +361,7 @@ public void testLoadConfiguration_shouldFailIfNoRequiredConfigInResponse() { final var listener = spy( ActionListener.>>wrap( r -> fail("Unexpected behave"), - e -> assertEquals("Missing required configuration for type: CONFIG", e.getMessage()) + e -> assertThat(e.getMessage(), is("Missing required configuration for type: CONFIG")) ) ); doAnswer(invocation -> { @@ -384,7 +384,7 @@ public void testLoadConfiguration_shouldFailForUnsupportedVersion() { final var listener = spy( ActionListener.>>wrap( r -> fail("Unexpected behave"), - e -> assertEquals("Version 1 is not supported for CONFIG", e.getMessage()) + e -> assertThat(e.getMessage(), is("Version 1 is not supported for CONFIG")) ) ); doAnswer(invocation -> { @@ -417,7 +417,7 @@ public void testLoadConfiguration_shouldFailForUnparseableConfig() { final var listener = spy( ActionListener.>>wrap( r -> fail("Unexpected behave"), - e -> assertEquals("Couldn't parse content for CONFIG", e.getMessage()) + e -> assertThat(e.getMessage(), is("Couldn't parse content for CONFIG")) ) ); doAnswer(invocation -> { @@ -451,7 +451,7 @@ public void testLoadConfiguration_shouldFailForUnparseableConfig() { @Test public void testLoadConfiguration_shouldBuildSecurityConfig() { final var listener = spy(ActionListener.>>wrap(config -> { - assertEquals(CType.values().length, config.keySet().size()); + assertThat(config.keySet().size(), is(CType.values().length)); for (final var c : CType.values()) { assertTrue(c.toLCString(), config.containsKey(c)); } diff --git a/src/test/java/org/opensearch/security/support/StreamableRegistryTest.java b/src/test/java/org/opensearch/security/support/StreamableRegistryTest.java index e1959d3e19..9d5da3930a 100644 --- a/src/test/java/org/opensearch/security/support/StreamableRegistryTest.java +++ b/src/test/java/org/opensearch/security/support/StreamableRegistryTest.java @@ -18,13 +18,16 @@ import org.opensearch.OpenSearchException; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class StreamableRegistryTest { StreamableRegistry streamableRegistry = StreamableRegistry.getInstance(); @Test public void testStreamableTypeIDs() { - Assert.assertEquals(1, streamableRegistry.getStreamableID(InetSocketAddress.class)); + assertThat(streamableRegistry.getStreamableID(InetSocketAddress.class), is(1)); Assert.assertThrows(OpenSearchException.class, () -> streamableRegistry.getStreamableID(String.class)); } } diff --git a/src/test/java/org/opensearch/security/system_indices/AbstractSystemIndicesTests.java b/src/test/java/org/opensearch/security/system_indices/AbstractSystemIndicesTests.java index f5af73265e..deb6f6f5e3 100644 --- a/src/test/java/org/opensearch/security/system_indices/AbstractSystemIndicesTests.java +++ b/src/test/java/org/opensearch/security/system_indices/AbstractSystemIndicesTests.java @@ -37,7 +37,8 @@ import org.opensearch.security.test.helper.file.FileHelper; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; /** * Test for opendistro system indices, to restrict configured indices access to adminDn @@ -165,15 +166,15 @@ RestHelper sslRestHelper() { } void validateSearchResponse(RestHelper.HttpResponse response, int expectedHits) throws IOException { - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); XContentParser xcp = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, response.getBody()); SearchResponse searchResponse = SearchResponse.fromXContent(xcp); - assertEquals(RestStatus.OK, searchResponse.status()); - assertEquals(expectedHits, searchResponse.getHits().getHits().length); - assertEquals(0, searchResponse.getFailedShards()); - assertEquals(5, searchResponse.getSuccessfulShards()); + assertThat(searchResponse.status(), is(RestStatus.OK)); + assertThat(searchResponse.getHits().getHits().length, is(expectedHits)); + assertThat(searchResponse.getFailedShards(), is(0)); + assertThat(searchResponse.getSuccessfulShards(), is(5)); } String permissionExceptionMessage(String action, String username) { @@ -185,7 +186,7 @@ String permissionExceptionMessage(String action, String username) { } void validateForbiddenResponse(RestHelper.HttpResponse response, String action, String user) { - assertEquals(RestStatus.FORBIDDEN.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.FORBIDDEN.getStatus())); MatcherAssert.assertThat(response.getBody(), Matchers.containsStringIgnoringCase(permissionExceptionMessage(action, user))); } @@ -196,7 +197,7 @@ void shouldBeAllowedOnlyForAuthorizedIndices(String index, RestHelper.HttpRespon if (isSecurityIndexRequest || isRequestingAccessToNonAuthorizedSystemIndex) { validateForbiddenResponse(response, isSecurityIndexRequest ? "" : action, user); } else { - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } diff --git a/src/test/java/org/opensearch/security/system_indices/SystemIndexDisabledTests.java b/src/test/java/org/opensearch/security/system_indices/SystemIndexDisabledTests.java index e14574873e..b387070195 100644 --- a/src/test/java/org/opensearch/security/system_indices/SystemIndexDisabledTests.java +++ b/src/test/java/org/opensearch/security/system_indices/SystemIndexDisabledTests.java @@ -23,7 +23,8 @@ import org.opensearch.core.rest.RestStatus; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -53,7 +54,7 @@ public void testSearchAsSuperAdmin() throws Exception { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", matchAllQuery); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } @Test @@ -69,7 +70,7 @@ public void testSearchAsAdmin() throws Exception { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", matchAllQuery, allAccessUserHeader); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); assertTrue(response.getBody().contains(SYSTEM_INDICES.get(0))); assertFalse(response.getBody().contains(ACCESSIBLE_ONLY_BY_SUPER_ADMIN)); } @@ -100,7 +101,7 @@ private void testSearchWithUser(String user, Header header) throws IOException { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", "", header); - assertEquals(RestStatus.FORBIDDEN.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.FORBIDDEN.getStatus())); validateForbiddenResponse(response, "indices:data/read/search", user); } @@ -113,10 +114,10 @@ public void testDeleteAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse responseDoc = restHelper.executeDeleteRequest(index + "/_doc/document1"); - assertEquals(RestStatus.OK.getStatus(), responseDoc.getStatusCode()); + assertThat(responseDoc.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse responseIndex = restHelper.executeDeleteRequest(index); - assertEquals(RestStatus.OK.getStatus(), responseIndex.getStatusCode()); + assertThat(responseIndex.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -161,10 +162,10 @@ public void testCloseOpenAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse responseClose = restHelper.executePostRequest(index + "/_close", ""); - assertEquals(RestStatus.OK.getStatus(), responseClose.getStatusCode()); + assertThat(responseClose.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse responseOpen = restHelper.executePostRequest(index + "/_open", ""); - assertEquals(RestStatus.OK.getStatus(), responseOpen.getStatusCode()); + assertThat(responseOpen.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -178,7 +179,7 @@ public void testCloseOpenAsAdmin() { // User can open the index but cannot close it response = restHelper.executePostRequest(index + "/_open", "", allAccessUserHeader); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -204,7 +205,7 @@ private void testCloseOpenWithUser(String user, Header header) { if (index.equals(ACCESSIBLE_ONLY_BY_SUPER_ADMIN) || index.equals(SYSTEM_INDEX_WITH_NO_ASSOCIATED_ROLE_PERMISSIONS)) { validateForbiddenResponse(response, "indices:admin/open", user); } else { - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } } @@ -218,10 +219,10 @@ public void testCreateIndexAsSuperAdmin() { for (String index : INDICES_FOR_CREATE_REQUEST) { RestHelper.HttpResponse responseIndex = restHelper.executePutRequest(index, createIndexSettings); - assertEquals(RestStatus.OK.getStatus(), responseIndex.getStatusCode()); + assertThat(responseIndex.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse response = restHelper.executePostRequest(index + "/_doc", "{\"foo\": \"bar\"}"); - assertEquals(RestStatus.CREATED.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.CREATED.getStatus())); } } @@ -245,10 +246,10 @@ private void testCreateIndexWithUser(Header header) { for (String index : INDICES_FOR_CREATE_REQUEST) { RestHelper.HttpResponse response = restHelper.executePutRequest(index, createIndexSettings, header); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); response = restHelper.executePostRequest(index + "/_doc", "{\"foo\": \"bar\"}", header); - assertEquals(RestStatus.CREATED.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.CREATED.getStatus())); } } @@ -261,10 +262,10 @@ public void testUpdateAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse response = restHelper.executePutRequest(index + "/_settings", updateIndexSettings); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); response = restHelper.executePutRequest(index + "/_mapping", newMappings); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -310,22 +311,22 @@ public void testSnapshotSystemIndicesAsSuperAdmin() { } for (String index : SYSTEM_INDICES) { - assertEquals(HttpStatus.SC_OK, restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1").getStatusCode()); - assertEquals( - HttpStatus.SC_OK, + assertThat(restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1").getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "", allAccessUserHeader - ).getStatusCode() + ).getStatusCode(), + is(HttpStatus.SC_OK) ); - assertEquals( - HttpStatus.SC_OK, + assertThat( restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", allAccessUserHeader - ).getStatusCode() + ).getStatusCode(), + is(HttpStatus.SC_OK) ); } } @@ -344,7 +345,7 @@ public void testSnapshotSystemIndicesAsAdmin() { for (String index : SYSTEM_INDICES) { String snapshotRequest = "_snapshot/" + index + "/" + index + "_1"; RestHelper.HttpResponse res = restHelper.executeGetRequest(snapshotRequest); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); res = restHelper.executePostRequest(snapshotRequest + "/_restore?wait_for_completion=true", "", allAccessUserHeader); shouldBeAllowedOnlyForAuthorizedIndices(index, res, "", allAccessUser); @@ -381,7 +382,7 @@ private void testSnapshotWithUser(String user, Header header) { for (String index : SYSTEM_INDICES) { String snapshotRequest = "_snapshot/" + index + "/" + index + "_1"; RestHelper.HttpResponse res = restHelper.executeGetRequest(snapshotRequest); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); String action = index.equals(ACCESSIBLE_ONLY_BY_SUPER_ADMIN) ? "" : "indices:data/write/index, indices:admin/create"; diff --git a/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionDisabledTests.java b/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionDisabledTests.java index 37b4f1bc0f..fcb1f9265c 100644 --- a/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionDisabledTests.java +++ b/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionDisabledTests.java @@ -23,7 +23,8 @@ import org.opensearch.core.rest.RestStatus; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; /** @@ -52,7 +53,7 @@ public void testSearchAsSuperAdmin() throws Exception { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", matchAllQuery); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } @Test @@ -67,7 +68,7 @@ public void testSearchAsAdmin() throws Exception { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", matchAllQuery, allAccessUserHeader); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); assertFalse(response.getBody().contains(SYSTEM_INDICES.get(0))); assertFalse(response.getBody().contains(ACCESSIBLE_ONLY_BY_SUPER_ADMIN)); } @@ -99,7 +100,7 @@ private void testSearchWithUser(String user, Header header) throws IOException { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", "", header); - assertEquals(RestStatus.FORBIDDEN.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.FORBIDDEN.getStatus())); validateForbiddenResponse(response, "indices:data/read/search", user); } @@ -112,10 +113,10 @@ public void testDeleteAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse responseDoc = restHelper.executeDeleteRequest(index + "/_doc/document1"); - assertEquals(RestStatus.OK.getStatus(), responseDoc.getStatusCode()); + assertThat(responseDoc.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse responseIndex = restHelper.executeDeleteRequest(index); - assertEquals(RestStatus.OK.getStatus(), responseIndex.getStatusCode()); + assertThat(responseIndex.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -155,10 +156,10 @@ public void testCloseOpenAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse responseClose = restHelper.executePostRequest(index + "/_close", ""); - assertEquals(RestStatus.OK.getStatus(), responseClose.getStatusCode()); + assertThat(responseClose.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse responseOpen = restHelper.executePostRequest(index + "/_open", ""); - assertEquals(RestStatus.OK.getStatus(), responseOpen.getStatusCode()); + assertThat(responseOpen.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -172,7 +173,7 @@ public void testCloseOpenAsAdmin() { // admin cannot close any system index but can open them response = restHelper.executePostRequest(index + "/_open", "", allAccessUserHeader); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -196,7 +197,7 @@ private void testCloseOpenWithUser(String user, Header header) { // normal user cannot open or close security index response = restHelper.executePostRequest(index + "/_open", "", header); if (index.startsWith(".system")) { - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } else { validateForbiddenResponse(response, "indices:admin/open", user); } @@ -213,10 +214,10 @@ public void testCreateIndexAsSuperAdmin() { for (String index : INDICES_FOR_CREATE_REQUEST) { RestHelper.HttpResponse responseIndex = restHelper.executePutRequest(index, createIndexSettings); - assertEquals(RestStatus.OK.getStatus(), responseIndex.getStatusCode()); + assertThat(responseIndex.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse response = restHelper.executePostRequest(index + "/_doc", "{\"foo\": \"bar\"}"); - assertEquals(RestStatus.CREATED.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.CREATED.getStatus())); } } @@ -240,10 +241,10 @@ private void testCreateIndexWithUser(Header header) { for (String index : INDICES_FOR_CREATE_REQUEST) { RestHelper.HttpResponse response = restHelper.executePutRequest(index, createIndexSettings, header); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); response = restHelper.executePostRequest(index + "/_doc", "{\"foo\": \"bar\"}", header); - assertEquals(RestStatus.CREATED.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.CREATED.getStatus())); } } @@ -256,10 +257,10 @@ public void testUpdateAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse response = restHelper.executePutRequest(index + "/_settings", updateIndexSettings); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); response = restHelper.executePutRequest(index + "/_mapping", newMappings); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -305,22 +306,22 @@ public void testSnapshotSystemIndicesAsSuperAdmin() { } for (String index : SYSTEM_INDICES) { - assertEquals(HttpStatus.SC_OK, restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1").getStatusCode()); - assertEquals( - HttpStatus.SC_OK, + assertThat(restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1").getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "", allAccessUserHeader - ).getStatusCode() + ).getStatusCode(), + is(HttpStatus.SC_OK) ); - assertEquals( - HttpStatus.SC_OK, + assertThat( restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", allAccessUserHeader - ).getStatusCode() + ).getStatusCode(), + is(HttpStatus.SC_OK) ); } } @@ -338,7 +339,7 @@ public void testSnapshotSystemIndicesAsAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse res = restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1"); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); res = restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", @@ -378,7 +379,7 @@ private void testSnapshotSystemIndexWithUser(String user, Header header) { RestHelper restHelper = sslRestHelper(); for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse res = restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1"); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); res = restHelper.executePostRequest("_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "", header); validateForbiddenResponse(res, "", user); diff --git a/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionEnabledTests.java b/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionEnabledTests.java index f8e29b2bbd..397b8c2286 100644 --- a/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionEnabledTests.java +++ b/src/test/java/org/opensearch/security/system_indices/SystemIndexPermissionEnabledTests.java @@ -21,7 +21,8 @@ import org.opensearch.core.rest.RestStatus; import org.opensearch.security.test.helper.rest.RestHelper; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; public class SystemIndexPermissionEnabledTests extends AbstractSystemIndicesTests { @@ -47,7 +48,7 @@ public void testSearchAsSuperAdmin() throws Exception { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", matchAllQuery); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } @Test @@ -63,7 +64,7 @@ public void testSearchAsAdmin() { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", matchAllQuery, allAccessUserHeader); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); assertFalse(response.getBody().contains(SYSTEM_INDICES.get(0))); assertFalse(response.getBody().contains(ACCESSIBLE_ONLY_BY_SUPER_ADMIN)); } @@ -86,7 +87,7 @@ public void testSearchAsNormalUser() throws Exception { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", "", normalUserHeader); - assertEquals(RestStatus.FORBIDDEN.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.FORBIDDEN.getStatus())); validateForbiddenResponse(response, "indices:data/read/search", normalUser); } @@ -102,7 +103,7 @@ public void testSearchAsNormalUserWithoutSystemIndexAccess() { // search all indices RestHelper.HttpResponse response = restHelper.executePostRequest("/_search", "", normalUserWithoutSystemIndexHeader); - assertEquals(RestStatus.FORBIDDEN.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.FORBIDDEN.getStatus())); validateForbiddenResponse(response, "indices:data/read/search", normalUserWithoutSystemIndex); } @@ -137,10 +138,10 @@ public void testDeleteAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse responseDoc = restHelper.executeDeleteRequest(index + "/_doc/document1"); - assertEquals(RestStatus.OK.getStatus(), responseDoc.getStatusCode()); + assertThat(responseDoc.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse responseIndex = restHelper.executeDeleteRequest(index); - assertEquals(RestStatus.OK.getStatus(), responseIndex.getStatusCode()); + assertThat(responseIndex.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -198,10 +199,10 @@ public void testCloseOpenAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse responseClose = restHelper.executePostRequest(index + "/_close", ""); - assertEquals(RestStatus.OK.getStatus(), responseClose.getStatusCode()); + assertThat(responseClose.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse responseOpen = restHelper.executePostRequest(index + "/_open", ""); - assertEquals(RestStatus.OK.getStatus(), responseOpen.getStatusCode()); + assertThat(responseOpen.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -252,10 +253,10 @@ public void testCreateIndexAsSuperAdmin() { for (String index : INDICES_FOR_CREATE_REQUEST) { RestHelper.HttpResponse responseIndex = restHelper.executePutRequest(index, createIndexSettings); - assertEquals(RestStatus.OK.getStatus(), responseIndex.getStatusCode()); + assertThat(responseIndex.getStatusCode(), is(RestStatus.OK.getStatus())); RestHelper.HttpResponse response = restHelper.executePostRequest(index + "/_doc", "{\"foo\": \"bar\"}"); - assertEquals(RestStatus.CREATED.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.CREATED.getStatus())); } } @@ -279,10 +280,10 @@ private void testCreateIndexWithUser(Header header) { for (String index : INDICES_FOR_CREATE_REQUEST) { RestHelper.HttpResponse response = restHelper.executePutRequest(index, createIndexSettings, header); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); response = restHelper.executePostRequest(index + "/_doc", "{\"foo\": \"bar\"}", header); - assertEquals(RestStatus.CREATED.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.CREATED.getStatus())); } } @@ -295,10 +296,10 @@ public void testUpdateAsSuperAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse response = restHelper.executePutRequest(index + "/_settings", updateIndexSettings); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); response = restHelper.executePutRequest(index + "/_mapping", newMappings); - assertEquals(RestStatus.OK.getStatus(), response.getStatusCode()); + assertThat(response.getStatusCode(), is(RestStatus.OK.getStatus())); } } @@ -352,22 +353,22 @@ public void testSnapshotSystemIndicesAsSuperAdmin() { } for (String index : SYSTEM_INDICES) { - assertEquals(HttpStatus.SC_OK, restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1").getStatusCode()); - assertEquals( - HttpStatus.SC_OK, + assertThat(restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1").getStatusCode(), is(HttpStatus.SC_OK)); + assertThat( restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "", allAccessUserHeader - ).getStatusCode() + ).getStatusCode(), + is(HttpStatus.SC_OK) ); - assertEquals( - HttpStatus.SC_OK, + assertThat( restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", "{ \"rename_pattern\": \"(.+)\", \"rename_replacement\": \"restored_index_with_global_state_$1\" }", allAccessUserHeader - ).getStatusCode() + ).getStatusCode(), + is(HttpStatus.SC_OK) ); } } @@ -385,7 +386,7 @@ public void testSnapshotSystemIndicesAsAdmin() { for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse res = restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1"); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); res = restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", @@ -416,7 +417,7 @@ public void testSnapshotSystemIndicesAsNormalUser() { RestHelper restHelper = sslRestHelper(); for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse res = restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1"); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); res = restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", @@ -449,7 +450,7 @@ public void testSnapshotSystemIndicesAsNormalUserWithoutSystemIndexAccess() { RestHelper restHelper = sslRestHelper(); for (String index : SYSTEM_INDICES) { RestHelper.HttpResponse res = restHelper.executeGetRequest("_snapshot/" + index + "/" + index + "_1"); - assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode()); + assertThat(res.getStatusCode(), is(HttpStatus.SC_UNAUTHORIZED)); res = restHelper.executePostRequest( "_snapshot/" + index + "/" + index + "_1/_restore?wait_for_completion=true", diff --git a/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java b/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java index e05d1ffe8a..ec4525eb30 100644 --- a/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java +++ b/src/test/java/org/opensearch/security/test/AbstractSecurityUnitTest.java @@ -94,6 +94,9 @@ import io.netty.handler.ssl.OpenSsl; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + /* * There are real thread leaks during test execution, not all threads are * properly waited on or interrupted. While this normally doesn't create test @@ -265,7 +268,7 @@ public static Settings.Builder mergeNodeRolesAndSettings(final Settings.Builder protected void initialize(ClusterHelper clusterHelper, ClusterInfo clusterInfo, DynamicSecurityConfig securityConfig) throws IOException { try (Client tc = clusterHelper.nodeClient()) { - Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size()); + assertThat(tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size(), is(clusterInfo.numNodes)); try { tc.admin().indices().create(new CreateIndexRequest(".opendistro_security")).actionGet(); @@ -283,7 +286,7 @@ protected void initialize(ClusterHelper clusterHelper, ClusterInfo clusterInfo, new ConfigUpdateRequest(CType.lcStringValues().toArray(new String[0])) ).actionGet(); Assert.assertFalse(cur.failures().toString(), cur.hasFailures()); - Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size()); + assertThat(cur.getNodes().size(), is(clusterInfo.numNodes)); SearchResponse sr = tc.search(new SearchRequest(".opendistro_security")).actionGet(); sr = tc.search(new SearchRequest(".opendistro_security")).actionGet(); diff --git a/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java b/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java index 27668d2657..c9c5820482 100644 --- a/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java +++ b/src/test/java/org/opensearch/security/test/helper/cluster/ClusterHelper.java @@ -71,6 +71,9 @@ import org.opensearch.security.test.helper.cluster.ClusterConfiguration.NodeSettings; import org.opensearch.security.test.helper.network.SocketUtils; import org.opensearch.transport.TransportInfo; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; // CS-ENFORCE-SINGLE public final class ClusterHelper { @@ -380,7 +383,7 @@ public ClusterInfo waitForCluster(final ClusterHealthStatus status, final TimeVa log.debug("... cluster state ok {} with {} nodes", healthResponse.getStatus().name(), healthResponse.getNumberOfNodes()); } - org.junit.Assert.assertEquals(expectedNodeCount, healthResponse.getNumberOfNodes()); + assertThat(healthResponse.getNumberOfNodes(), is(expectedNodeCount)); final NodesInfoResponse res = client.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet(); diff --git a/src/test/java/org/opensearch/security/transport/SecurityInterceptorTests.java b/src/test/java/org/opensearch/security/transport/SecurityInterceptorTests.java index 8d902ed498..42884862a2 100644 --- a/src/test/java/org/opensearch/security/transport/SecurityInterceptorTests.java +++ b/src/test/java/org/opensearch/security/transport/SecurityInterceptorTests.java @@ -54,7 +54,8 @@ import org.mockito.MockitoAnnotations; import static java.util.Collections.emptySet; -import static org.junit.Assert.assertEquals; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; @@ -208,7 +209,7 @@ public void sendRequest( TransportResponseHandler handler ) { String serializedUserHeader = threadPool.getThreadContext().getHeader(ConfigConstants.OPENDISTRO_SECURITY_USER_HEADER); - assertEquals(serializedUserHeader, Base64Helper.serializeObject(user, true)); + assertThat(serializedUserHeader, is(Base64Helper.serializeObject(user, true))); senderLatch.get().countDown(); } }; @@ -223,7 +224,7 @@ public void sendRequest( TransportResponseHandler handler ) { User transientUser = threadPool.getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - assertEquals(transientUser, user); + assertThat(user, is(transientUser)); senderLatch.get().countDown(); } }; @@ -238,7 +239,7 @@ public void sendRequest( final void verifyOriginalContext(User user) { User transientUser = threadPool.getThreadContext().getTransient(ConfigConstants.OPENDISTRO_SECURITY_USER); - assertEquals(transientUser, user); + assertThat(user, is(transientUser)); assertNull(threadPool.getThreadContext().getHeader(ConfigConstants.OPENDISTRO_SECURITY_USER_HEADER)); }