repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/EESecurityInjectionEnabledAbstractTestCase.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeParseException; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.Module; /** * Validate that the {@code ee-security} subsystem is enabled when a deployment uses the injection * of {@link jakarta.security.enterprise.SecurityContext}. Allows for Jakarta Security components to * be used without a full implementation. Modified from {@link EESecurityAuthMechanismMultiConstraintsTestCase}. * * @see <a href="https://issues.redhat.com/browse/WFLY-17541">WFLY-17541</a> * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ @RunWith(Arquillian.class) @RunAsClient public abstract class EESecurityInjectionEnabledAbstractTestCase { static final String MODULE_NAME = "org.wildfly.security.examples.custom-principal"; static final String TEST_APP_DOMAIN = "testApplicationDomain"; public void testCustomPrincipalWithInject(URL webAppURL) throws IOException, URISyntaxException { testCustomPrincipalInternal(webAppURL); } /** * @return the header to be used for authentication with the deployed web app */ abstract Header[] setRequestAuthHeader(); private void testCustomPrincipalInternal(URL webAppURL) throws IOException, URISyntaxException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { String requestURI = webAppURL.toURI() + "/inject"; HttpGet request = new HttpGet(requestURI); request.setHeaders(setRequestAuthHeader()); HttpResponse response = httpClient.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); ByteArrayOutputStream baosBody = new ByteArrayOutputStream(); response.getEntity().writeTo(baosBody); String responseBody = baosBody.toString(StandardCharsets.UTF_8); // Check that custom principal was retrieved assertTrue(responseBody.contains("user1")); assertTrue(responseBody.contains(TestCustomPrincipal.class.getCanonicalName())); // Check that custom method was accessed and returned a valid date Header loginHeader = response.getFirstHeader(TestInjectServlet.LOGIN_HEADER); assertNotNull(loginHeader); try { LocalDateTime.parse(loginHeader.getValue(), ISO_LOCAL_DATE_TIME); } catch (DateTimeParseException e) { throw new DateTimeParseException("Login timestamp returned from servlet was not a valid ISO-format LocalDateTime", e.getParsedString(), e.getErrorIndex(), e); } } } abstract static class ServerSetup extends AbstractElytronSetupTask { static final String TEST_CUSTOM_PRINCIPAL_TRANSFORMER = "testCustomPrincipalTransformer"; static final String TEST_SECURITY_DOMAIN = "testSecurityDomain"; static final String DEFAULT_PERMISSION_MAPPER = "default-permission-mapper"; static Path modulePath; static ConfigurableElement module; static Path createJar(String namePrefix, Class<?>... classes) throws IOException { Path testJar = Files.createTempFile(namePrefix, ".jar"); JavaArchive jar = ShrinkWrap.create(JavaArchive.class).addClasses(classes); jar.as(ZipExporter.class).exportTo(testJar.toFile(), true); return testJar; } @Override protected void setup(ModelControllerClient modelControllerClient) throws Exception { modulePath = createJar("custom-principal", TestCustomPrincipal.class, TestCustomPrincipalTransformer.class); module = Module.builder() .withName(MODULE_NAME) .withResource(modulePath.toAbsolutePath().toString()) .withDependency("jakarta.security.enterprise.api") .withDependency("org.wildfly.security.elytron") .withDependency("org.wildfly.extension.elytron") .build(); super.setup(modelControllerClient); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); Files.deleteIfExists(modulePath); } } }
6,162
42.401408
130
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestCustomPrincipal.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import java.security.Principal; import java.time.LocalDateTime; import jakarta.security.enterprise.CallerPrincipal; /** * A simple {@link jakarta.security.enterprise.CallerPrincipal} with a custom field and method. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ public class TestCustomPrincipal extends CallerPrincipal { private static final long serialVersionUID = -35690086418605259L; private final LocalDateTime currentLoginTime; private final Principal wrappedPrincipal; public TestCustomPrincipal(Principal principal) { super(principal.getName()); this.wrappedPrincipal = principal; this.currentLoginTime = LocalDateTime.now(); } public LocalDateTime getCurrentLoginTime() { return this.currentLoginTime; } @Override public String getName() { return wrappedPrincipal.getName(); } @Override public String toString() { return getName(); } @Override public boolean equals(Object obj) { if (obj instanceof TestCustomPrincipal) { return this.getName().equals(((TestCustomPrincipal) obj).getName()); } else { return super.equals(obj); } } }
1,893
29.063492
95
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/EESecurityInjectionEnabledElytronTestCase.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.CustomPrincipalTransformer; import org.wildfly.test.security.common.elytron.FileSystemRealm; import org.wildfly.test.security.common.elytron.MechanismConfiguration; import org.wildfly.test.security.common.elytron.MechanismRealmConfiguration; import org.wildfly.test.security.common.elytron.SimpleHttpAuthenticationFactory; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.UserWithAttributeValues; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Validates that the {@code ee-security} subsystem is enabled when a deployment does not fully implement Jakarta Security, * but still uses parts of the API. Here, a custom principal is returned to the client via * {@link jakarta.security.enterprise.SecurityContext}, while authentication is performed by Elytron. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ EESecurityInjectionEnabledElytronTestCase.ServerSetup.class }) public class EESecurityInjectionEnabledElytronTestCase extends EESecurityInjectionEnabledAbstractTestCase { @ArquillianResource private Deployer deployer; private static final String WEB_APP_NAME = "WFLY-17541-Elytron"; @Deployment(name = WEB_APP_NAME, managed = false, testable = false) public static WebArchive warDeployment() { Class<EESecurityInjectionEnabledElytronTestCase> testClass = EESecurityInjectionEnabledElytronTestCase.class; return ShrinkWrap.create(WebArchive.class, testClass.getSimpleName() + ".war") .addClasses(testClass, EESecurityInjectionEnabledAbstractTestCase.class) .addClasses(ServerSetup.class, EESecurityInjectionEnabledAbstractTestCase.ServerSetup.class, AbstractElytronSetupTask.class) .addClasses(TestInjectElytronServlet.class, TestInjectServlet.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset(TEST_APP_DOMAIN), "jboss-web.xml") .addAsWebInfResource(testClass.getPackage(), "WFLY-17541-elytron-web.xml", "web.xml") .addAsWebInfResource(testClass.getPackage(), "WFLY-17541-index.xml", "index.xml") .addAsWebInfResource(testClass.getPackage(), "beans.xml", "beans.xml") .addAsManifestResource(new StringAsset("Dependencies: " + MODULE_NAME + "\n"), "MANIFEST.MF"); } @Override Header[] setRequestAuthHeader() { // BASIC authentication - base64(username:password) return new BasicHeader[] { new BasicHeader("Authorization", "Basic dXNlcjE6cGFzc3dvcmQx") }; } @Test @InSequence(1) public void deployApplication() { deployer.deploy(WEB_APP_NAME); } @Override @Test @InSequence(2) public void testCustomPrincipalWithInject(@ArquillianResource URL webAppURL) throws IOException, URISyntaxException { super.testCustomPrincipalWithInject(webAppURL); } @Test @InSequence(3) public void undeployApplication() { deployer.undeploy(WEB_APP_NAME); } static class ServerSetup extends EESecurityInjectionEnabledAbstractTestCase.ServerSetup { static final String TEST_REALM = "testRealm"; static final String TEST_HTTP_FACTORY = "testHttpFactory"; @Override protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] elements = new ConfigurableElement[6]; // Add module with custom principal and principal transformer elements[0] = module; // Create filesystem security realm with one identity elements[1] = FileSystemRealm.builder() .withName(TEST_REALM) .withUser(UserWithAttributeValues.builder() .withName("user1") .withPassword("password1") .withValues("Login") .build()) .build(); // Add custom pre-realm principal transformer to create custom principal elements[2] = CustomPrincipalTransformer.builder() .withName(TEST_CUSTOM_PRINCIPAL_TRANSFORMER) .withModule(MODULE_NAME) .withClassName(TestCustomPrincipalTransformer.class.getCanonicalName()) .build(); // Create security domain using security realm and principal transformer elements[3] = SimpleSecurityDomain.builder() .withName(TEST_SECURITY_DOMAIN) .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(TEST_REALM) .build()) .withDefaultRealm(TEST_REALM) .withPermissionMapper(DEFAULT_PERMISSION_MAPPER) .build(); // Create HTTP authentication factory elements[4] = SimpleHttpAuthenticationFactory.builder() .withName(TEST_HTTP_FACTORY) .withHttpServerMechanismFactory("global") .withSecurityDomain(TEST_SECURITY_DOMAIN) .addMechanismConfiguration(MechanismConfiguration.builder() .withMechanismName("BASIC") .addMechanismRealmConfiguration(MechanismRealmConfiguration.builder() .withRealmName(TEST_REALM) .build()) .withPreRealmPrincipalTransformer(TEST_CUSTOM_PRINCIPAL_TRANSFORMER) .build()) .build(); // Add HTTP authentication factory to Undertow configuration elements[5] = UndertowApplicationSecurityDomain.builder() .withName(TEST_APP_DOMAIN) .httpAuthenticationFactory(TEST_HTTP_FACTORY) .withEnableJacc(true) .build(); return elements; } } }
7,757
46.595092
123
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestAuthenticationMechanism.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.security.enterprise.AuthenticationException; import jakarta.security.enterprise.AuthenticationStatus; import jakarta.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism; import jakarta.security.enterprise.authentication.mechanism.http.HttpMessageContext; import jakarta.security.enterprise.credential.UsernamePasswordCredential; import jakarta.security.enterprise.identitystore.CredentialValidationResult; import jakarta.security.enterprise.identitystore.CredentialValidationResult.Status; import jakarta.security.enterprise.identitystore.IdentityStoreHandler; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A simple {@link HttpAuthenticationMechanism} for testing. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @ApplicationScoped public class TestAuthenticationMechanism implements HttpAuthenticationMechanism { static final String USERNAME_HEADER = "X-USERNAME"; static final String PASSWORD_HEADER = "X-PASSWORD"; static final String MESSAGE_HEADER = "X-MESSAGE"; static final String MESSAGE = "Please resubmit the request with a username specified using the X-USERNAME and a password specified using the X-PASSWORD header."; @Inject private IdentityStoreHandler identityStoreHandler; @Override public AuthenticationStatus validateRequest(HttpServletRequest request, HttpServletResponse response, HttpMessageContext httpMessageContext) throws AuthenticationException { final String username = request.getHeader(USERNAME_HEADER); final String password = request.getHeader(PASSWORD_HEADER); final boolean challenge = Boolean.parseBoolean(request.getParameter("challenge")); if (username != null && password != null) { UsernamePasswordCredential upc = new UsernamePasswordCredential(username, password); CredentialValidationResult cvr = identityStoreHandler.validate(upc); if (cvr.getStatus() == Status.VALID) { return httpMessageContext.notifyContainerAboutLogin(cvr.getCallerPrincipal(), cvr.getCallerGroups()); } else { return challenge(response, httpMessageContext); } } if (challenge || httpMessageContext.isProtected()) { return challenge(response, httpMessageContext); } return httpMessageContext.doNothing(); } private static AuthenticationStatus challenge(HttpServletResponse response, HttpMessageContext httpMessageContext) { response.addHeader(MESSAGE_HEADER, MESSAGE); return httpMessageContext.responseUnauthorized(); } }
3,460
41.728395
165
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/WhoAmIBean.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import java.security.Principal; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import jakarta.inject.Inject; import jakarta.security.enterprise.SecurityContext; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Stateless @SecurityDomain("other") public class WhoAmIBean implements WhoAmI { @Resource private SessionContext sessionContext; @Inject private SecurityContext securityContext; @Override public Principal getCallerPrincipalSessionContext() { return sessionContext.getCallerPrincipal(); } @Override public Principal getCallerPrincipalSecurityDomain() { return org.wildfly.security.auth.server.SecurityDomain.getCurrent().getCurrentSecurityIdentity().getPrincipal(); } @Override public Principal getCallerPrincipalSecurityContext() { return securityContext.getCallerPrincipal(); } }
1,727
28.288136
120
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/EESecurityAuthMechanismMultiConstraintsTestCase.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.wildfly.test.integration.elytron.securityapi.TestAuthenticationMechanism.PASSWORD_HEADER; import static org.wildfly.test.integration.elytron.securityapi.TestAuthenticationMechanism.USERNAME_HEADER; import static org.wildfly.test.integration.elytron.securityapi.TestIdentityStore.PASSWORD; import static org.wildfly.test.integration.elytron.securityapi.TestIdentityStore.USERNAME; import java.io.ByteArrayOutputStream; import java.net.URL; import java.nio.charset.StandardCharsets; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Copied from {@link EESecurityAuthMechanismTestCase} testing multiple constrained directories. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ @SuppressWarnings("MagicNumber") @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ EESecurityAuthMechanismMultiConstraintsTestCase.ServerSetup.class }) public class EESecurityAuthMechanismMultiConstraintsTestCase { @Deployment(name = "WFLY-12655") public static WebArchive warDeployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, EESecurityAuthMechanismMultiConstraintsTestCase.class.getSimpleName() + ".war"); war .addAsWebInfResource(EESecurityAuthMechanismMultiConstraintsTestCase.class.getPackage(), "WFLY-12655-web.xml", "/web.xml") .addAsWebInfResource(Utils.getJBossWebXmlAsset("SecurityAPI"), "jboss-web.xml"); war.add(new StringAsset("Welcome Area"), "area/index.jsp") .add(new StringAsset("Welcome Area51"), "area51/index.jsp") .add(new StringAsset("Unsecured"), "index.jsp"); war .addClasses(EESecurityAuthMechanismMultiConstraintsTestCase.class, AbstractElytronSetupTask.class, ServerSetup.class) .addClasses(TestAuthenticationMechanism.class, TestIdentityStore.class); return war; } @BeforeClass public static void skipSecurityManager() { AssumeTestGroupUtil.assumeSecurityManagerDisabled(); } @Test public void testRequiresAuthentication(@ArquillianResource URL webAppURL) throws Exception { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(webAppURL.toURI() + "/area"); HttpResponse httpResponse = httpClient.execute(request); assertEquals("Expected /area to require authentication.", 401, httpResponse.getStatusLine().getStatusCode()); request = new HttpGet(webAppURL.toURI() + "/area51"); httpResponse = httpClient.execute(request); assertEquals("Expected /area51 to require authentication.", 401, httpResponse.getStatusLine().getStatusCode()); } } @Test public void testSuccessfulAuthentication(@ArquillianResource URL webAppURL) throws Exception { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(webAppURL.toURI() + "area"); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); HttpResponse httpResponse = httpClient.execute(request); assertEquals(200, httpResponse.getStatusLine().getStatusCode()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(bos); assertTrue(new String(bos.toByteArray(), StandardCharsets.UTF_8).contains("Welcome Area")); request = new HttpGet(webAppURL.toURI() + "area51"); request.addHeader(USERNAME_HEADER, USERNAME); request.addHeader(PASSWORD_HEADER, PASSWORD); httpResponse = httpClient.execute(request); assertEquals(200, httpResponse.getStatusLine().getStatusCode()); bos = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(bos); assertTrue(new String(bos.toByteArray(), StandardCharsets.UTF_8).contains("Welcome Area51")); } } @Test public void testUnsuccessfulAuthentication(@ArquillianResource URL webAppURL) throws Exception { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(webAppURL.toURI() + "area"); request.addHeader(USERNAME_HEADER, "evil"); request.addHeader(PASSWORD_HEADER, "password"); HttpResponse httpResponse = httpClient.execute(request); assertEquals(401, httpResponse.getStatusLine().getStatusCode()); request = new HttpGet(webAppURL.toURI() + "area51"); request.addHeader(USERNAME_HEADER, "evil"); request.addHeader(PASSWORD_HEADER, "password"); httpResponse = httpClient.execute(request); assertEquals(401, httpResponse.getStatusLine().getStatusCode()); } } @Test public void testAuthNotRequired(@ArquillianResource URL webAppURL) throws Exception { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet request = new HttpGet(webAppURL.toURI() + "index.jsp"); HttpResponse httpResponse = httpClient.execute(request); assertEquals(200, httpResponse.getStatusLine().getStatusCode()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(bos); assertTrue(new String(bos.toByteArray(), StandardCharsets.UTF_8).contains("Unsecured")); } } static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] elements = new ConfigurableElement[1]; // 1 - Map the application-security-domain elements[0] = UndertowApplicationSecurityDomain.builder() .withName("SecurityAPI") .withSecurityDomain("ApplicationDomain") .withIntegratedJaspi(false) .build(); return elements; } } }
7,836
42.782123
147
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/WhoAmI.java
/* * Copyright 2018 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import java.security.Principal; import jakarta.ejb.Local; /** * The local interface to the simple WhoAmI bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Local public interface WhoAmI { /** * @return the caller principal obtained from the SessionContext. */ Principal getCallerPrincipalSessionContext(); /** * @return the caller principal obtained from the SecurityDomain. */ Principal getCallerPrincipalSecurityDomain(); /** * @return the caller principal obtained from the SecurityContext. */ Principal getCallerPrincipalSecurityContext(); }
1,301
26.702128
75
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/securityapi/TestInjectServlet.java
/* * Copyright 2023 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.securityapi; import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME; import java.io.IOException; import java.io.PrintWriter; import java.security.Principal; import java.util.Objects; import jakarta.inject.Inject; import jakarta.security.enterprise.SecurityContext; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpMethodConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A simple servlet to test using the custom method of {@link TestCustomPrincipal}, for the Jakarta annotation * {@link Inject}. * * @author <a href="mailto:carodrig@redhat.com">Cameron Rodriguez</a> */ @WebServlet(urlPatterns = "/inject") public class TestInjectServlet extends HttpServlet { private static final long serialVersionUID = 1524739695027377372L; @Inject private SecurityContext securityContext = null; static final String LOGIN_HEADER = "Login-Time"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try (PrintWriter pw = resp.getWriter()) { final Principal principal = Objects.requireNonNull(securityContext, "SecurityContext must be injected") .getCallerPrincipal(); pw.println("<html><head><title>doGet - TestCustomPrincipal</title></head>"); pw.println("<body><h1>Custom principal test, via SecurityContext</h1>"); if (principal instanceof TestCustomPrincipal) { TestCustomPrincipal customPrincipal = (TestCustomPrincipal) principal; pw.printf("<ul>Principal: %s</li>", customPrincipal.getName()); pw.printf("<li>Class: %s</li>\n", customPrincipal.getClass().getCanonicalName()); pw.printf("<li>Current login time: %s</li>\n", customPrincipal.getCurrentLoginTime().toString()); pw.println("</ul></body></html>"); resp.addHeader(LOGIN_HEADER, customPrincipal.getCurrentLoginTime().format(ISO_LOCAL_DATE_TIME)); } else { pw.printf("<p>The principal returned was not of class TestCustomPrincipal.</p>"); pw.printf("<ul>Principal: %s</li>", principal.getName()); pw.printf("<li>Class: %s</li>\n", principal.getClass().getCanonicalName()); pw.println("</ul></body></html>"); resp.setStatus(500); } } } } /** Secured Servlets using Elytron authentication require an extra annotation */ @ServletSecurity(httpMethodConstraints = { @HttpMethodConstraint(value = "GET", rolesAllowed = { "Login" }) }) class TestInjectElytronServlet extends TestInjectServlet { private static final long serialVersionUID = 5806993562466870053L; }
3,598
40.848837
115
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/application/AbstractCredentialStoreTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.application; import static jakarta.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.AllPermission; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.shared.integration.ejb.security.PermissionUtils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.wildfly.test.security.servlets.ReadCredentialServlet; /** * Abstract parent for Elytron Credential store test cases. It provides a deployment with {@link ReadCredentialServlet} and * helper {@code assert*} methods to verify credential store content. * * @author Josef Cacek */ public abstract class AbstractCredentialStoreTestCase { @ArquillianResource private URL url; @Deployment(testable = false) public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class) .addClass(ReadCredentialServlet.class) .addAsManifestResource( new StringAsset( "Dependencies: org.jboss.as.server,org.jboss.as.controller,org.wildfly.security.elytron\n"), "MANIFEST.MF") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset(new AllPermission()), "permissions.xml"); } /** * Asserts that given credential store contains alias with given value. * * @param credentialStore * @param alias secret name * @param expectedValue expected secret value * @throws Exception */ protected void assertCredentialValue(String credentialStore, String alias, String expectedValue) throws Exception { assertEquals("Unexpected password (secret-value) in credential store", expectedValue, doReadCredentialPostReq(credentialStore, alias, SC_OK)); } /** * Asserts that the provided credentialStore + alias combination doesn't exist. * * @param credentialStore store name * @param alias alias to check */ protected void assertCredentialNotFound(String credentialStore, String alias) throws Exception { doReadCredentialPostReq(credentialStore, alias, SC_NOT_FOUND); } /** * Asserts that a credential store with given name contains given aliases. * * @param cli connected {@link CLIWrapper} instance (not <code>null</code>) * @param storeName credential store name (not <code>null</code>) * @param aliases aliases to check * @throws IOException */ protected void assertContainsAliases(CLIWrapper cli, String storeName, String... aliases) throws IOException { if (aliases == null || aliases.length > 0) { return; } cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:read-children-names(child-type=alias)", storeName)); final CLIOpResult opResult = cli.readAllAsOpResult(); Set<String> set = opResult.getResponseNode().get(ModelDescriptionConstants.RESULT).asList().stream() .map(n -> n.asString()).collect(Collectors.toSet()); for (String alias : aliases) { if (!set.contains(alias)) { fail(String.format("Credential store '%s' doesn't contain expected alias '%s'", storeName, alias)); } } } /** * Creates alias in given credential store (must exist) with provided secret value. Then uses * {@link #assertCredentialValue(String, String, String)} method to check if it's correctly stored in the credential * store. It removes the alias as the final step. */ protected void assertAliasAndSecretSupported(String storeName, String alias, String secret) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { if (secret != null) { cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", storeName, alias, secret)); assertCredentialValue(storeName, alias, secret); } else { cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s)", storeName, alias)); assertCredentialValue(storeName, alias, ""); } } finally { cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:remove-alias(alias=%s)", storeName, alias), true); } } } /** * Makes request to {@link ReadCredentialServlet} to check read secret value from credential store. It asserts HTTP status * code in the response. */ private String doReadCredentialPostReq(String credentialStore, String alias, int expectedStatus) throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException { String body; final URI uri = new URI(url.toExternalForm() + ReadCredentialServlet.SERVLET_PATH.substring(1)); final HttpPost post = new HttpPost(uri); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair(ReadCredentialServlet.PARAM_CREDENTIAL_STORE, credentialStore)); nvps.add(new BasicNameValuePair(ReadCredentialServlet.PARAM_ALIAS, alias)); post.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8)); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpResponse response = httpClient.execute(post)) { int statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code in HTTP response.", expectedStatus, statusCode); body = EntityUtils.toString(response.getEntity()); } } return body; } }
8,119
45.4
140
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/application/CredentialStoreTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.application; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.IOException; import java.nio.CharBuffer; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.util.CLIOpResult; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.dmr.ModelNode; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.extension.elytron._private.ElytronSubsystemMessages; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleCredentialStore; /** * Tests credential store (CS) implementation in Elytron. This test case uses existing CS keystore prepared in testsuite module * configuration - check keytool maven plugin used in {@code pom.xml} and also credential store CLI commands in * {@code modify-elytron.config.cli} file. * * @author Josef Cacek */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(CredentialStoreTestCase.ElytronSetup.class) public class CredentialStoreTestCase extends AbstractCredentialStoreTestCase { private static final String NAME = CredentialStoreTestCase.class.getSimpleName(); private static final String CS_NAME_CLEAR = NAME + "-clear"; private static final String CS_NAME_CRED_REF = NAME + "-cred-ref"; private static final String CS_NAME_MODIFIABLE = NAME + "-modifiable"; private static final String ALIAS_SECRET = "alias-secret"; private static final String ALIAS_PASSWORD = "alias-password"; /** * Tests unmodifiable credential store when backing keystore has password in clear text. */ @Test public void testClearPassword() throws Exception { testUnmodifiableInternally(CS_NAME_CLEAR); } /** * Test unmodifiable credential store when backing keystore has password provided as credential reference. */ @Test public void testCredentialReference() throws Exception { testUnmodifiableInternally(CS_NAME_CRED_REF); } /** * Tests reload operation on credential store instance. */ @Test public void testReloadCredentialStore() throws Exception { final String alias = "cs-reload-test"; try (CLIWrapper cli = new CLIWrapper(true)) { try { cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", CS_NAME_MODIFIABLE, alias, alias)); assertCredentialNotFound(CS_NAME_CLEAR, alias); assertCredentialNotFound(CS_NAME_CRED_REF, alias); cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:reload()", CS_NAME_CRED_REF)); assertCredentialNotFound(CS_NAME_CLEAR, alias); assertCredentialValue(CS_NAME_CRED_REF, alias, alias); cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:reload()", CS_NAME_CLEAR)); assertCredentialValue(CS_NAME_CLEAR, alias, alias); } finally { cli.sendLine( String.format("/subsystem=elytron/credential-store=%s:remove-alias(alias=%s)", CS_NAME_MODIFIABLE, alias)); } } } /** * Tests change password operation on credential store instance. */ @Test public void testUpdatePasswordCredentialStore() throws Exception { final String alias = "cs-update-test"; final String password = "password"; final String updatedPassword = "passw0rd!"; try (CLIWrapper cli = new CLIWrapper(true)) { try { cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", CS_NAME_MODIFIABLE, alias, alias)); assertCredentialValue(CS_NAME_MODIFIABLE, alias, alias); cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:set-secret(alias=%s, secret-value=\"%s\")", CS_NAME_MODIFIABLE, alias, updatedPassword)); assertCredentialValue(CS_NAME_MODIFIABLE, alias, updatedPassword); } finally { cli.sendLine( String.format("/subsystem=elytron/credential-store=%s:remove-alias(alias=%s)", CS_NAME_MODIFIABLE, alias), true); } } } /** * Tests add-remove-add operations sequence on an alias in credential store. */ @Test public void testAddRemoveAddAlias() throws Exception { final String alias = "addremoveadd"; try (CLIWrapper cli = new CLIWrapper(true)) { try { cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", CS_NAME_MODIFIABLE, alias, alias)); assertCredentialValue(CS_NAME_MODIFIABLE, alias, alias); cli.sendLine( String.format("/subsystem=elytron/credential-store=%s:remove-alias(alias=%s)", CS_NAME_MODIFIABLE, alias)); cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", CS_NAME_MODIFIABLE, alias, alias + alias)); assertCredentialValue(CS_NAME_MODIFIABLE, alias, alias + alias); cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%s, secret-value=\"%s\")", CS_NAME_MODIFIABLE, alias, alias), true); ModelNode result = ModelNode.fromString(cli.readOutput()); assertEquals("result " + result, result.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).asString(), ElytronSubsystemMessages.ROOT_LOGGER.credentialAlreadyExists(alias, PasswordCredential.class.getName()).getMessage()); } finally { cli.sendLine( String.format("/subsystem=elytron/credential-store=%s:remove-alias(alias=%s)", CS_NAME_MODIFIABLE, alias)); } } } /** * Tests creating credential with long secret. */ @Test public void testLongSecret() throws Exception { final String secret = generateString(10 * 1024 + 1, 's'); assertAliasAndSecretSupported(CS_NAME_MODIFIABLE, "longsecret", secret); } /** * Tests creating credential with empty secret. */ @Test public void testEmptySecret() throws Exception { assertAliasAndSecretSupported(CS_NAME_MODIFIABLE, "emptysecret", ""); assertAliasAndSecretSupported(CS_NAME_MODIFIABLE, "nullsecret", null); } /** * Tests creating credential with long alias. */ @Test public void testLongAlias() throws Exception { final String alias = generateString(1024 + 1, 'a'); assertAliasAndSecretSupported(CS_NAME_MODIFIABLE, alias, "test"); } private void testUnmodifiableInternally(final String csName) throws IOException, Exception { try (CLIWrapper cli = new CLIWrapper(true)) { assertContainsAliases(cli, csName, ALIAS_PASSWORD, ALIAS_SECRET); cli.sendLine(String.format("/subsystem=elytron/credential-store=%s:add-alias(alias=%1$s, secret-value=%1$s)", csName), true); final CLIOpResult opResult = cli.readAllAsOpResult(); assertFalse("Adding alias to non-modifiable credential store should fail.", opResult.isIsOutcomeSuccess()); } assertCredentialValue(csName, ALIAS_PASSWORD, "password"); assertCredentialValue(csName, ALIAS_SECRET, "secret"); assertCredentialNotFound(csName, csName); } private static String generateString(int len, char c) { return CharBuffer.allocate(len).toString().replace('\0', c); } /** * Configures 2 unmodifiable credential stores (CS) on the top of one existing JCEKS keystore - One CS uses plain text * keystore password, the second uses credential reference (pointing to the first CS). Then configures one modifiable CS. */ static class ElytronSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { final Path jceksPath = Path.builder().withPath("cred-store.jceks").withRelativeTo("jboss.server.config.dir") .build(); final CredentialReference credRefPwd = CredentialReference.builder().withClearText("password").build(); final CredentialReference credRefRef = CredentialReference.builder().withStore(CS_NAME_CLEAR) .withAlias(ALIAS_PASSWORD).build(); return new ConfigurableElement[] { SimpleCredentialStore.builder().withName(CS_NAME_CLEAR).withKeyStorePath(jceksPath) .withKeyStoreType("JCEKS").withCreate(false).withModifiable(false).withCredential(credRefPwd) .build(), SimpleCredentialStore.builder().withName(CS_NAME_CRED_REF).withKeyStorePath(jceksPath).withCreate(false) .withModifiable(false).withCredential(credRefRef).build(), SimpleCredentialStore.builder().withName(CS_NAME_MODIFIABLE).withKeyStorePath(jceksPath) .withModifiable(true).withCredential(credRefPwd).build() }; } } }
10,988
46.366379
142
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/application/BasicAuthnTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.application; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.auth.client.MatchRule; import org.wildfly.security.credential.BearerTokenCredential; import org.wildfly.test.integration.elytron.util.ClientConfigProviderBearerTokenAbortFilter; import org.wildfly.test.integration.elytron.util.ClientConfigProviderNoBasicAuthorizationHeaderFilter; import org.wildfly.test.integration.elytron.util.HttpAuthorization; import jakarta.ws.rs.Priorities; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.core.Response; /** * Smoke test for web application authentication using Elytron with default server configuration. * * @author Josef Cacek */ @RunWith(Arquillian.class) @RunAsClient public class BasicAuthnTestCase { private static final String NAME = BasicAuthnTestCase.class.getSimpleName(); /** * Creates WAR with a secured servlet and BASIC authentication configured in web.xml deployment descriptor. */ @Deployment(testable = false) public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class, NAME + ".war").addClasses(SimpleServlet.class) .addAsWebInfResource(BasicAuthnTestCase.class.getPackage(), NAME + "-web.xml", "web.xml"); } /** * Tests access without authentication. */ @Test public void testUnprotectedAccess(@ArquillianResource URL url) throws Exception { assertEquals("Response body is not correct.", SimpleServlet.RESPONSE_BODY, Utils.makeCall(url.toURI(), SC_OK)); assertEquals("Response body is not correct.", SimpleServlet.RESPONSE_BODY, Utils.makeCall(new URI(url.toExternalForm() + "foo"), SC_OK)); } /** * Tests '*' wildcard in authn-constraints. */ @Test public void testAllRolesAllowed(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "all"); assertUrlProtected(servletUrl); assertEquals("Response body is not correct.", SimpleServlet.RESPONSE_BODY, Utils.makeCallWithBasicAuthn(servletUrl, "user1", "password1", SC_OK)); assertEquals("Response body is not correct.", SimpleServlet.RESPONSE_BODY, Utils.makeCallWithBasicAuthn(servletUrl, "user2", "password2", SC_OK)); assertEquals("Response body is not correct.", SimpleServlet.RESPONSE_BODY, Utils.makeCallWithBasicAuthn(servletUrl, "guest", "guest", SC_OK)); } /** * Test case sensitivity of role in authn-constraints. */ @Test public void testCaseSensitiveRole(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "users"); assertUrlProtected(servletUrl); Utils.makeCallWithBasicAuthn(servletUrl, "user1", "password1", SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(servletUrl, "user2", "password2", SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(servletUrl, "guest", "guest", SC_FORBIDDEN); } /** * Tests single role in authn-constraint. */ @Test public void testUser1Allowed(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); assertUrlProtected(servletUrl); assertEquals("Response body is not correct.", SimpleServlet.RESPONSE_BODY, Utils.makeCallWithBasicAuthn(servletUrl, "user1", "password1", SC_OK)); Utils.makeCallWithBasicAuthn(servletUrl, "user2", "password2", SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(servletUrl, "guest", "guest", SC_FORBIDDEN); } /** * Tests empty authn-constraint in web.xml. */ @Test public void testNoRoleAllowed(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "prohibited"); Utils.makeCall(servletUrl.toURI(), SC_FORBIDDEN); } private void assertUrlProtected(final URL servletUrl) throws Exception, URISyntaxException, IOException { Utils.makeCall(servletUrl.toURI(), SC_UNAUTHORIZED); // wrong password Utils.makeCallWithBasicAuthn(servletUrl, "user1", "password", SC_UNAUTHORIZED); Utils.makeCallWithBasicAuthn(servletUrl, "user1", "Password1", SC_UNAUTHORIZED); // unknown user Utils.makeCallWithBasicAuthn(servletUrl, "User1", "password1", SC_UNAUTHORIZED); } /** * Test that RESTEasy client successfully uses Elytron client configuration to authenticate to the secured server with HTTP BASIC auth. */ @Test public void testRESTEasyClientUsesElytronConfigAuthenticatedUser(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("user1").usePassword("password1"); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL, adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); Response response = client.target(servletUrl.toString()).request().get(); Assert.assertEquals(SC_OK, response.getStatus()); client.close(); }); } /** * Test that RESTEasy client ignores ClientConfigProvider credentials if credentials are specified directly by user for RESTEasy client. */ @Test public void testClientConfigCredentialsAreIgnoredIfSpecified(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("incorrectUsername").usePassword("incorrectPassword"); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL, adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); client.register(HttpAuthorization.basic("user1", "password1")); Response response = client.target(servletUrl.toString()).request().get(); Assert.assertEquals(SC_OK, response.getStatus()); client.close(); }); } /** * Test secured resource with correct credentials of user that is authorized to the resource. * Bearer token from ClientConfigProvider impl is ignored since credentials are specified for RESTEasy client. */ @Test public void testClientConfigBearerTokenIsIgnoredIfBasicSpecified(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); BearerTokenCredential bearerTokenCredential = new BearerTokenCredential("myTestToken"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useBearerTokenCredential(bearerTokenCredential); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL, adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); client.register(HttpAuthorization.basic("user1", "password1")); client.register(ClientConfigProviderBearerTokenAbortFilter.class); try { client.target(servletUrl.toString()).request().get(); fail("Configuration not found ex should be thrown."); } catch (Exception e) { // check that bearer token was not added assertTrue(e.getMessage().contains("The request authorization header is not correct expected:<B[earer myTestToken]> but was:<B[asic")); client.close(); } }); } /** * Unauthorized user's credentials were set on Elytron client and so authentication will fail with 403. */ @Test public void testClientConfigForbiddenUser(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("user2").usePassword("password2"); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL, adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); Response response = client.target(servletUrl.toString()).request().get(); Assert.assertEquals(SC_FORBIDDEN, response.getStatus()); client.close(); }); } /** * Test that access will be unauthenticated when accessing secured resource with RESTEasy client without credentials set on Elytron client config. */ @Test public void testClientUnauthenticatedUser(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty(); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL, adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); Response response = client.target(servletUrl.toString()).request().get(); Assert.assertEquals(SC_UNAUTHORIZED, response.getStatus()); client.close(); }); } /** * Test that access credentials from ClientConfigProvider are used only if both username and password are present. */ @Test public void testClientConfigProviderUsernameWithoutPasswordWillBeIgnored(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("thisNameWillBeIgnoredBecausePasswordIsMissing"); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL, adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); client.register(new ClientConfigProviderNoBasicAuthorizationHeaderFilter(), Priorities.USER); try { client.target(servletUrl.toString()).request().get(); } catch (Exception e) { assertTrue(e.getMessage().contains("The request authorization header is not correct expected:<Bearer myTestToken> but was:<null>")); client.close(); } Response response = builder.build().target(servletUrl.toString()).request().get(); Assert.assertEquals(SC_UNAUTHORIZED, response.getStatus()); client.close(); }); } /** * Test that Elytron config credentials are not used when specified for different destination of the request. */ @Test public void testClientConfigProviderChooseCredentialsBasedOnDestination(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("user1").usePassword("password1"); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL.matchHost("www.some-example.com"), adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); Response response = client.target(servletUrl.toString()).request().get(); // will be unauthorized because credentials were set for different hostname than we are calling Assert.assertEquals(SC_UNAUTHORIZED, response.getStatus()); client.close(); }); } /** * Test that ClientConfigProvider credentials are used when specified for requested URL. */ @Test public void testClientConfigProviderChooseCredentialsBasedOnDestination2(@ArquillianResource URL url) throws MalformedURLException { final URL servletUrl = new URL(url.toExternalForm() + "role1"); AuthenticationConfiguration adminConfig = AuthenticationConfiguration.empty().useName("user1").usePassword("password1"); AuthenticationContext context = AuthenticationContext.empty(); context = context.with(MatchRule.ALL.matchHost(servletUrl.getHost()), adminConfig); context.run(() -> { ClientBuilder builder = ClientBuilder.newBuilder(); Client client = builder.build(); Response response = client.target(servletUrl.toString()).request().get(); // will be authorized because we are calling hostname that credentials are set for Assert.assertEquals(SC_OK, response.getStatus()); Assert.assertEquals("response was not GOOD", "GOOD", response.readEntity(String.class)); client.close(); }); } }
15,710
47.640867
151
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/application/CredentialStoreI18NTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.application; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.dmr.ModelNode; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.extension.elytron._private.ElytronSubsystemMessages; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleCredentialStore; import static org.junit.Assert.assertEquals; /** * Tests credential store (CS) implementation in Elytron. This testcase uses several scenarios: * <ul> * <li>CS created on the top of existing keystore</li> * <li>CS with keystore created from scratch</li> * <li>keystore password as credential-reference (entry in another CS)</li> * <li>keystore file survives removing CS from domain model</li> * <li>several keystore types used for backing the credential store</li> * </ul> * The configuration for this test case is partly in module configuration (check keytool maven plugin used in {@code pom.xml} * and also credential store CLI commands in {@code modify-elytron.config.cli} file * * @author Josef Cacek */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup(CredentialStoreI18NTestCase.ElytronSetup.class) public class CredentialStoreI18NTestCase extends AbstractCredentialStoreTestCase { private static final String NAME = CredentialStoreI18NTestCase.class.getSimpleName(); private static final String LOWER = "lower"; private static final String STR_SYMBOLS = "@!#?$%^&*()%+-{}"; private static final String STR_CHINESE = "用戶名"; private static final String STR_ARABIC = "اسمالمستخدم"; private static final String STR_EURO_LOWER = "žščřžďťňäáéěëíýóůúü"; private static final String STR_EURO_UPPER = "ŽŠČŘŽĎŤŇÄÁÉĚËÍÝÓŮÚÜ"; private static final String STR_ALL = STR_SYMBOLS + STR_CHINESE + STR_ARABIC + STR_EURO_LOWER + STR_EURO_UPPER; /** * Tests using localized strings as secrets. */ @Test public void testI18NSecret() throws Exception { assertAliasAndSecretSupported(NAME, "i18nsecret", STR_ALL); } /** * Tests using localized strings as alias. */ @Test public void testI18NAlias() throws Exception { assertAliasAndSecretSupported(NAME, STR_CHINESE, "test"); assertAliasAndSecretSupported(NAME, STR_ARABIC, "test"); assertAliasAndSecretSupported(NAME, STR_EURO_LOWER, "test"); } /** * Tests for CS aliases case-sensitiveness */ @Test public void testAliasesCaseSensitive() throws Exception { assertCredentialValue(NAME, LOWER, LOWER); try (CLIWrapper cli = new CLIWrapper(true)) { Assert.assertFalse(cli.sendLine("/subsystem=elytron/credential-store=CredentialStoreI18NTestCase:add-alias(alias=LOWER, secret-value=password)", true)); ModelNode result = ModelNode.fromString(cli.readOutput()); assertEquals("result " + result, result.get(ModelDescriptionConstants.FAILURE_DESCRIPTION).asString(), ElytronSubsystemMessages.ROOT_LOGGER.credentialAlreadyExists("LOWER", PasswordCredential.class.getName()).getMessage()); } } /** * Configures 2 unmodifiable credential stores (CS) on the top of one existing JCEKS keystore - One CS uses plain text * keystore password, the second uses credential reference (pointing to the first CS). Then configures one modifiable CS. */ static class ElytronSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { final Path jceksPath = Path.builder().withPath("cred-store.jceks").withRelativeTo("jboss.server.config.dir") .build(); final CredentialReference credRefPwd = CredentialReference.builder().withClearText("password").build(); return new ConfigurableElement[] { SimpleCredentialStore.builder().withName(NAME).withKeyStorePath(jceksPath) .withKeyStoreType("JCEKS").withCreate(false).withModifiable(true).withCredential(credRefPwd) .withAlias(LOWER, LOWER) .build() }; } } }
5,732
44.864
164
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/AbstractSyslogAuditLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import java.net.URL; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.syslogserver.BlockedSyslogServerEventHandler; import org.junit.Assert; import org.junit.Test; import org.productivity.java.syslog4j.server.SyslogServer; import org.productivity.java.syslog4j.server.SyslogServerConfigIF; import org.productivity.java.syslog4j.server.SyslogServerEventIF; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.junit.Assert.assertTrue; /** * Abstract class for Elytron Audit Logging tests. Tests are placed here as well as a couple of syslog-specific helper methods. * * @author Jan Tymel */ public abstract class AbstractSyslogAuditLogTestCase extends AbstractAuditLogTestCase { /** * Tests whether successful authentication was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testSuccessfulAuthAndPermissionCheck(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue(); queue.clear(); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_OK); assertTrue("Successful permission check was not logged", loggedSuccessfulPermissionCheck(queue, USER)); assertTrue("Successful authentication was not logged", loggedSuccessfulAuth(queue, USER)); assertNoMoreMessages(queue); } /** * Tests whether failed authentication with wrong user was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthWrongUser(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue(); queue.clear(); Utils.makeCallWithBasicAuthn(servletUrl, UNKNOWN_USER, PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed authentication with wrong user was not logged", loggedFailedAuth(queue, UNKNOWN_USER)); assertNoMoreMessages(queue); } /** * Tests whether failed authentication with wrong password was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthWrongPassword(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue(); queue.clear(); Utils.makeCallWithBasicAuthn(servletUrl, USER, WRONG_PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed authentication with wrong password was not logged", loggedFailedAuth(queue, USER)); assertNoMoreMessages(queue); } /** * Tests whether failed authentication with empty password was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthEmptyPassword(@ArquillianResource URL url) throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue(); queue.clear(); Utils.makeCallWithBasicAuthn(servletUrl, USER, EMPTY_PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed authentication with empty password was not logged", loggedFailedAuth(queue, USER)); assertNoMoreMessages(queue); } /** * Tests whether failed permission check was logged. */ @Test @OperateOnDeployment(SD_WITHOUT_LOGIN_PERMISSION) public void testFailedPermissionCheck() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); final BlockingQueue<SyslogServerEventIF> queue = BlockedSyslogServerEventHandler.getQueue(); queue.clear(); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed permission check was not logged", loggedFailedPermissionCheck(queue, USER)); assertTrue("Failed authentication was not logged", loggedFailedAuth(queue, USER)); assertNoMoreMessages(queue); } protected static boolean loggedSuccessfulAuth(BlockingQueue<SyslogServerEventIF> queue, String user) throws Exception { return loggedAuthResult(queue, user, SUCCESSFUL_AUTH_EVENT); } protected static boolean loggedFailedAuth(BlockingQueue<SyslogServerEventIF> queue, String user) throws Exception { return loggedAuthResult(queue, user, UNSUCCESSFUL_AUTH_EVENT); } protected static boolean loggedSuccessfulPermissionCheck(BlockingQueue<SyslogServerEventIF> queue, String user) throws Exception { return loggedAuthResult(queue, user, SUCCESSFUL_PERMISSION_CHECK_EVENT); } protected static boolean loggedFailedPermissionCheck(BlockingQueue<SyslogServerEventIF> queue, String user) throws Exception { return loggedAuthResult(queue, user, UNSUCCESSFUL_PERMISSION_CHECK_EVENT); } protected static boolean loggedAuthResult(BlockingQueue<SyslogServerEventIF> queue, String user, String expectedEvent) throws Exception { SyslogServerEventIF log = queue.poll(15L, TimeUnit.SECONDS); if (log == null) { return false; } String logString = log.getMessage(); System.out.println(logString); return (logString.contains(expectedEvent) && logString.contains(user)); } void assertNoMoreMessages(BlockingQueue<SyslogServerEventIF> queue) throws Exception { //we make sure there are no messages //as we don't expect any we don't wait, as we don't want to extend the runtime of the test //however this should help prevent issues caused by messages from one test interferring with another //see WFLY-9882 SyslogServerEventIF log = queue.poll(0L, TimeUnit.SECONDS); if (log == null) { return; } Assert.fail(log.getMessage()); } protected static void setupAndStartSyslogServer(SyslogServerConfigIF config, String host, int port, String protocol) throws Exception { // clear created server instances (TCP/UDP) SyslogServer.shutdown(); config.setPort(port); config.setHost(host); config.setUseStructuredData(true); config.addEventHandler(new BlockedSyslogServerEventHandler()); SyslogServer.createInstance(protocol, config); // start syslog server SyslogServer.getThreadedInstance(protocol); } protected static void stopSyslogServer() throws Exception { SyslogServer.shutdown(); } }
8,061
42.578378
141
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/UDPSyslogAuditLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.syslogserver.UDPSyslogServerConfig; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.SyslogAuditLog; import static org.productivity.java.syslog4j.SyslogConstants.UDP; import static org.wildfly.test.integration.elytron.audit.AbstractAuditLogTestCase.setEventListenerOfApplicationDomain; /** * Class for particular settings for 'syslog-audit-log' Elytron subsystem resource that communicates over UDP protocol. * Tests being run with this settings can be seen in {@link AbstractSyslogAuditLogTestCase}. * * @author Jan Tymel */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractAuditLogTestCase.SecurityDomainSetupTask.class, UDPSyslogAuditLogTestCase.SyslogAuditLogSetupTask.class}) public class UDPSyslogAuditLogTestCase extends AbstractSyslogAuditLogTestCase { private static final String NAME = UDPSyslogAuditLogTestCase.class.getSimpleName(); private static final String HOSTNAME = "hostname-" + NAME; private static final int PORT = 10514; /** * Creates Elytron 'syslog-audit-log' and sets it as ApplicationDomain's security listener. */ static class SyslogAuditLogSetupTask implements ServerSetupTask { SyslogAuditLog auditLog; @Override public void setup(ManagementClient managementClient, String string) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { String host = CoreUtils.stripSquareBrackets(managementClient.getMgmtAddress()); final UDPSyslogServerConfig config = new UDPSyslogServerConfig(); setupAndStartSyslogServer(config, host, PORT, UDP); auditLog = SyslogAuditLog.builder().withName(NAME) .withServerAddress(managementClient.getMgmtAddress()) .withPort(PORT) .withHostName(HOSTNAME) .withTransportProtocol("UDP") .build(); auditLog.create(cli); setEventListenerOfApplicationDomain(cli, NAME); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { setDefaultEventListenerOfApplicationDomain(cli); auditLog.remove(cli); stopSyslogServer(); } ServerReload.reloadIfRequired(managementClient); } } }
4,109
42.263158
127
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/TLSSyslogAuditLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import java.io.File; import org.codehaus.plexus.util.FileUtils; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.integration.security.common.SecurityTestConstants; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.syslogserver.TLSSyslogServerConfig; import org.junit.Assert; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.ClientSslContext; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.KeyStore; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleClientSslContext; import org.wildfly.test.security.common.elytron.SimpleKeyStore; import org.wildfly.test.security.common.elytron.SimpleTrustManager; import org.wildfly.test.security.common.elytron.SyslogAuditLog; import org.wildfly.test.security.common.elytron.TrustManager; import static org.jboss.as.test.integration.security.common.SecurityTestConstants.KEYSTORE_PASSWORD; import static org.wildfly.test.integration.elytron.audit.AbstractAuditLogTestCase.setEventListenerOfApplicationDomain; import static org.wildfly.test.integration.elytron.audit.AbstractSyslogAuditLogTestCase.setupAndStartSyslogServer; /** * Class for particular settings for 'syslog-audit-log' Elytron subsystem resource that communicates over TLS protocol. Tests * being run with this settings can be seen in {@link AbstractSyslogAuditLogTestCase}. * * @author Jan Tymel */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractAuditLogTestCase.SecurityDomainSetupTask.class, TLSSyslogAuditLogTestCase.SyslogAuditLogSetupTask.class}) public class TLSSyslogAuditLogTestCase extends AbstractSyslogAuditLogTestCase { private static final String NAME = TLSSyslogAuditLogTestCase.class.getSimpleName(); private static final String HOSTNAME = "hostname-" + NAME; private static final int PORT = 10514; private static final String TRUST_STORE_NAME = "trust-store-" + NAME; private static final String TRUST_MANAGER_NAME = "trust-manager-" + NAME; private static final String SSL_CONTEXT_NAME = "ssl-context" + NAME; private static final File WORK_DIR = new File("target" + File.separatorChar + NAME); private static final File SERVER_KEYSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_KEYSTORE); private static final File SERVER_TRUSTSTORE_FILE = new File(WORK_DIR, SecurityTestConstants.SERVER_TRUSTSTORE); /** * Creates Elytron 'syslog-audit-log' and sets it as ApplicationDomain's security listener. */ static class SyslogAuditLogSetupTask implements ServerSetupTask { TrustManager trustManager; KeyStore trustStore; ClientSslContext sslContext; SyslogAuditLog auditLog; @Override public void setup(ManagementClient managementClient, String string) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { keyMaterialSetup(WORK_DIR); trustStore = SimpleKeyStore.builder().withName(TRUST_STORE_NAME) .withPath(Path.builder().withPath(SERVER_KEYSTORE_FILE.getPath()).build()) .withCredentialReference(CredentialReference.builder().withClearText(KEYSTORE_PASSWORD).build()) .withType("JKS") .build(); trustStore.create(cli); trustManager = SimpleTrustManager.builder().withName(TRUST_MANAGER_NAME) .withKeyStore(TRUST_STORE_NAME) .build(); trustManager.create(cli); sslContext = SimpleClientSslContext.builder().withName(SSL_CONTEXT_NAME) .withTrustManager(TRUST_MANAGER_NAME) .build(); sslContext.create(cli); final String host = CoreUtils.stripSquareBrackets(managementClient.getMgmtAddress()); final TLSSyslogServerConfig config = getTlsSyslogConfig(); setupAndStartSyslogServer(config, host, PORT, "TLS"); auditLog = SyslogAuditLog.builder().withName(NAME) .withServerAddress(managementClient.getMgmtAddress()) .withPort(PORT) .withHostName(HOSTNAME) .withTransportProtocol("SSL_TCP") .withSslContext(SSL_CONTEXT_NAME) .build(); auditLog.create(cli); setEventListenerOfApplicationDomain(cli, NAME); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { setDefaultEventListenerOfApplicationDomain(cli); auditLog.remove(cli); stopSyslogServer(); sslContext.remove(cli); trustManager.remove(cli); trustStore.remove(cli); } ServerReload.reloadIfRequired(managementClient); } } private static void keyMaterialSetup(File workDir) throws Exception { FileUtils.deleteDirectory(workDir); workDir.mkdirs(); Assert.assertTrue(workDir.exists()); Assert.assertTrue(workDir.isDirectory()); CoreUtils.createKeyMaterial(workDir); } private static TLSSyslogServerConfig getTlsSyslogConfig() { TLSSyslogServerConfig config = new TLSSyslogServerConfig(); config.setKeyStore(SERVER_KEYSTORE_FILE.getAbsolutePath()); config.setKeyStorePassword(KEYSTORE_PASSWORD); config.setTrustStore(SERVER_TRUSTSTORE_FILE.getAbsolutePath()); config.setTrustStorePassword(KEYSTORE_PASSWORD); return config; } }
7,383
45.440252
127
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/TCPSyslogAuditLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.syslogserver.TCPSyslogServerConfig; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.SyslogAuditLog; import static org.productivity.java.syslog4j.SyslogConstants.TCP; import static org.wildfly.test.integration.elytron.audit.AbstractAuditLogTestCase.setEventListenerOfApplicationDomain; import static org.wildfly.test.integration.elytron.audit.AbstractSyslogAuditLogTestCase.setupAndStartSyslogServer; /** * Class for particular settings for 'syslog-audit-log' Elytron subsystem resource that communicates over TCP protocol. * Tests being run with this settings can be seen in {@link AbstractSyslogAuditLogTestCase}. * * @author Jan Tymel */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractAuditLogTestCase.SecurityDomainSetupTask.class, TCPSyslogAuditLogTestCase.SyslogAuditLogSetupTask.class}) public class TCPSyslogAuditLogTestCase extends AbstractSyslogAuditLogTestCase { private static final String NAME = TCPSyslogAuditLogTestCase.class.getSimpleName(); private static final String HOSTNAME = "hostname-" + NAME; private static final int PORT = 10514; /** * Creates Elytron 'syslog-audit-log' and sets it as ApplicationDomain's security listener. */ static class SyslogAuditLogSetupTask implements ServerSetupTask { SyslogAuditLog auditLog; @Override public void setup(ManagementClient managementClient, String string) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { String host = CoreUtils.stripSquareBrackets(managementClient.getMgmtAddress()); final TCPSyslogServerConfig config = new TCPSyslogServerConfig(); setupAndStartSyslogServer(config, host, PORT, TCP); auditLog = SyslogAuditLog.builder().withName(NAME) .withServerAddress(managementClient.getMgmtAddress()) .withPort(PORT) .withHostName(HOSTNAME) .withTransportProtocol("TCP") .setMaxReconnectAttempts(5) // a random number to avoid intermittent failures .build(); auditLog.create(cli); setEventListenerOfApplicationDomain(cli, NAME); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { setDefaultEventListenerOfApplicationDomain(cli); auditLog.remove(cli); stopSyslogServer(); } ServerReload.reloadIfRequired(managementClient); } } }
4,326
43.608247
127
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/CustomSecurityEventListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Map; import java.util.function.Consumer; import org.wildfly.security.auth.server.event.SecurityEvent; public class CustomSecurityEventListener implements Consumer<SecurityEvent> { private static final String NAME = CustomSecurityEventListener.class.getSimpleName(); private static final String AUDIT_LOG_NAME = NAME + ".log"; private static final File AUDIT_LOG_FILE = new File("target", AUDIT_LOG_NAME); private String testingAttribute = null; @Override public void accept(SecurityEvent securityEvent) { try (PrintWriter writer = new PrintWriter(AUDIT_LOG_FILE)) { writer.print(testingAttribute + ":" + securityEvent.getClass().getName()); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } public void initialize(Map<String, String> configuration) { testingAttribute = configuration.get("testingAttribute"); } }
2,113
38.148148
89
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/CustomSecurityEventListenerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.junit.Assert.assertEquals; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.net.URL; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.module.util.TestModule; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.auth.server.event.SecurityAuthenticationFailedEvent; import org.wildfly.security.auth.server.event.SecurityAuthenticationSuccessfulEvent; @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractAuditLogTestCase.SecurityDomainSetupTask.class, CustomSecurityEventListenerTestCase.CustomListenerSetupTask.class}) public class CustomSecurityEventListenerTestCase extends AbstractAuditLogTestCase { private static final String NAME = CustomSecurityEventListener.class.getSimpleName(); private static final String AUDIT_LOG_NAME = NAME + ".log"; private static final File AUDIT_LOG_FILE = new File("target", AUDIT_LOG_NAME); /** * Tests whether successful authentication was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testSuccessfulAuth() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_OK); assertEquals("Successful authentication was not logged", "testingValue:" + SecurityAuthenticationSuccessfulEvent.class.getName(), getContent()); } /** * Tests whether failed authentication with wrong user was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthWrongUser() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(); Utils.makeCallWithBasicAuthn(servletUrl, UNKNOWN_USER, PASSWORD, SC_UNAUTHORIZED); assertEquals("Failed authentication was not logged", "testingValue:" + SecurityAuthenticationFailedEvent.class.getName(), getContent()); } static class CustomListenerSetupTask implements ServerSetupTask { static final Class<?> listenerClass = CustomSecurityEventListener.class; private final TestModule module; CustomListenerSetupTask() { module = new TestModule(listenerClass.getName(), "org.wildfly.security.elytron"); JavaArchive auditJar = module.addResource(listenerClass.getSimpleName() + ".jar"); auditJar.addClass(listenerClass); } @Override public void setup(ManagementClient managementClient, String string) throws Exception { module.create(true); try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine("/subsystem=elytron/custom-security-event-listener=" + NAME + ":add(" + "module=\"" + listenerClass.getName() + "\", " + "class-name=\"" + listenerClass.getName() + "\"," + "configuration={ testingAttribute = testingValue })"); setEventListenerOfApplicationDomain(cli, NAME); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { setDefaultEventListenerOfApplicationDomain(cli); cli.sendLine("/subsystem=elytron/custom-security-event-listener=" + NAME + ":remove"); } module.remove(); ServerReload.reloadIfRequired(managementClient); } } private static void discardCurrentContents() throws Exception { try (PrintWriter writer = new PrintWriter(AUDIT_LOG_FILE)) { writer.print(""); } } private static String getContent() throws Exception { BufferedReader reader = new BufferedReader(new FileReader(AUDIT_LOG_FILE)); return reader.readLine(); } }
5,775
41.470588
152
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/FileAuditLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.jboss.as.test.shared.CliUtils.asAbsolutePath; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.PrintWriter; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import org.codehaus.plexus.util.FileUtils; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.ServerReload; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.FileAuditLog; /** * Test case for 'file-audit-log' Elytron subsystem resource. * * @author Jan Tymel */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractAuditLogTestCase.SecurityDomainSetupTask.class, FileAuditLogTestCase.FileAuditLogSetupTask.class}) public class FileAuditLogTestCase extends AbstractAuditLogTestCase { private static final String NAME = FileAuditLogTestCase.class.getSimpleName(); private static final String AUDIT_LOG_NAME = "test-audit.log"; private static final File WORK_DIR = new File("target" + File.separatorChar + NAME); private static final File AUDIT_LOG_FILE = new File(WORK_DIR, AUDIT_LOG_NAME); private static final String ENCODING_16BE = "UTF-16BE"; /** * Tests whether successful authentication was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testSuccessfulAuth() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_OK); assertTrue("Successful authentication was not logged", loggedSuccessfulAuth(AUDIT_LOG_FILE, USER)); } /** * Tests whether failed authentication with wrong user was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthWrongUser() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, UNKNOWN_USER, PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed authentication with wrong user was not logged", loggedFailedAuth(AUDIT_LOG_FILE, UNKNOWN_USER)); } /** * Tests whether failed authentication with wrong password was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthWrongPassword() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, USER, WRONG_PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed authentication with wrong password was not logged", loggedFailedAuth(AUDIT_LOG_FILE, USER)); } /** * Tests whether failed authentication with empty password was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testFailedAuthEmptyPassword() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, USER, EMPTY_PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed authentication with empty password was not logged", loggedFailedAuth(AUDIT_LOG_FILE, USER)); } /** * Tests whether successful permission check was logged. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testSuccessfulPermissionCheck() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_OK); assertTrue("Successful permission check was not logged", loggedSuccessfulPermissionCheck(AUDIT_LOG_FILE, USER)); } /** * Tests whether failed permission check was logged. */ @Test @OperateOnDeployment(SD_WITHOUT_LOGIN_PERMISSION) public void testFailedPermissionCheck() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_UNAUTHORIZED); assertTrue("Failed permission check was not logged", loggedFailedPermissionCheck(AUDIT_LOG_FILE, USER)); } /** * Tests audit log file encoding. */ @Test @OperateOnDeployment(SD_WITHOUT_LOGIN_PERMISSION) public void testAuditLogFileEncoding() throws Exception { final URL servletUrl = new URL(url.toExternalForm() + "role1"); discardCurrentContents(AUDIT_LOG_FILE); Utils.makeCallWithBasicAuthn(servletUrl, USER, PASSWORD, SC_UNAUTHORIZED); //Read the logged event using the same encoding "UTF-16BE" as the audit log file setup assertTrue(loggedAuthResult(AUDIT_LOG_FILE, USER, UNSUCCESSFUL_PERMISSION_CHECK_EVENT, StandardCharsets.UTF_16BE)); //Read the logged event using different encoding assertFalse(loggedAuthResult(AUDIT_LOG_FILE, USER, UNSUCCESSFUL_PERMISSION_CHECK_EVENT, StandardCharsets.UTF_8)); } /** * Creates Elytron 'file-audit-log' and sets it as ApplicationDomain's security listener. */ static class FileAuditLogSetupTask implements ServerSetupTask { FileAuditLog auditLog; @Override public void setup(ManagementClient managementClient, String string) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { createEmptyDirectory(WORK_DIR); auditLog = FileAuditLog.builder().withName(NAME) .withPath(asAbsolutePath(AUDIT_LOG_FILE)) .withEncoding(ENCODING_16BE) .build(); auditLog.create(cli); setEventListenerOfApplicationDomain(cli, NAME); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { setDefaultEventListenerOfApplicationDomain(cli); auditLog.remove(cli); FileUtils.deleteDirectory(WORK_DIR); } ServerReload.reloadIfRequired(managementClient); } } private static boolean loggedSuccessfulAuth(File file, String user) throws Exception { return loggedAuthResult(file, user, SUCCESSFUL_AUTH_EVENT); } private static boolean loggedFailedAuth(File file, String user) throws Exception { return loggedAuthResult(file, user, UNSUCCESSFUL_AUTH_EVENT); } private static boolean loggedSuccessfulPermissionCheck(File file, String user) throws Exception { return loggedAuthResult(file, user, SUCCESSFUL_PERMISSION_CHECK_EVENT); } private static boolean loggedFailedPermissionCheck(File file, String user) throws Exception { return loggedAuthResult(file, user, UNSUCCESSFUL_PERMISSION_CHECK_EVENT); } private static boolean loggedAuthResult(File file, String user, String expectedEvent) throws Exception { return loggedAuthResult(file, user, expectedEvent, StandardCharsets.UTF_16BE); } private static boolean loggedAuthResult(File file, String user, String expectedEvent, Charset charset) throws Exception { List<String> lines = Files.readAllLines(file.toPath(), charset); for (String line : lines) { if (line.contains(expectedEvent) && line.contains(user)) { return true; } } return false; } private static void discardCurrentContents(File file) throws Exception { try (PrintWriter writer = new PrintWriter(file)) { writer.print(""); } } private static void createEmptyDirectory(File workDir) throws Exception { FileUtils.deleteDirectory(workDir); workDir.mkdirs(); Assert.assertTrue(workDir.exists()); Assert.assertTrue(workDir.isDirectory()); } }
9,893
38.895161
125
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/audit/AbstractAuditLogTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.audit; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.UndertowDomainMapper; /** * Abstract class for Elytron Audit Logging tests. It provides a deployment with {@link SimpleServlet} and a couple of helper * methods. * * @author Jan Tymel */ public abstract class AbstractAuditLogTestCase { @ArquillianResource protected URL url; protected static final String SUCCESSFUL_AUTH_EVENT = "SecurityAuthenticationSuccessfulEvent"; protected static final String UNSUCCESSFUL_AUTH_EVENT = "SecurityAuthenticationFailedEvent"; protected static final String SUCCESSFUL_PERMISSION_CHECK_EVENT = "SecurityPermissionCheckSuccessfulEvent"; protected static final String UNSUCCESSFUL_PERMISSION_CHECK_EVENT = "SecurityPermissionCheckFailedEvent"; protected static final String USER = "user1"; protected static final String UNKNOWN_USER = "unknown-user"; protected static final String PASSWORD = "password1"; protected static final String WRONG_PASSWORD = "wrongPassword"; protected static final String EMPTY_PASSWORD = ""; protected static final String SD_DEFAULT = "other"; protected static final String SD_WITHOUT_LOGIN_PERMISSION = "no-login-permission"; private static final String NAME = "AuditlogTestCase"; /** * Creates WAR with a secured servlet and BASIC authentication configured in web.xml deployment descriptor. * It uses default security domain. */ @Deployment(testable = false, name = SD_DEFAULT) public static WebArchive standardDeployment() { return createWar(SD_DEFAULT); } /** * Creates WAR with a secured servlet and BASIC authentication configured in web.xml deployment descriptor. * It uses newly created security domain {@link SD_WITHOUT_LOGIN_PERMISSION}. */ @Deployment(testable = false, name = SD_WITHOUT_LOGIN_PERMISSION) public static WebArchive customizedDeployment() { return createWar(SD_WITHOUT_LOGIN_PERMISSION) .addAsWebInfResource(Utils.getJBossWebXmlAsset(SD_WITHOUT_LOGIN_PERMISSION), "jboss-web.xml"); } /** * This {@link ServerSetupTask} creates new security domain in Elytron and Undertow in order to fire * permission check fail event. */ static class SecurityDomainSetupTask implements ServerSetupTask { SimpleSecurityDomain securityDomain; UndertowDomainMapper applicationSecurityDomain; @Override public void setup(ManagementClient managementClient, String string) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { securityDomain = createSecurityDomainWithoutPermissionMapper(SD_WITHOUT_LOGIN_PERMISSION); securityDomain.create(managementClient.getControllerClient(), cli); applicationSecurityDomain = UndertowDomainMapper.builder().withName(SD_WITHOUT_LOGIN_PERMISSION) .withApplicationDomains(SD_WITHOUT_LOGIN_PERMISSION).build(); applicationSecurityDomain.create(cli); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { applicationSecurityDomain.remove(cli); securityDomain.remove(managementClient.getControllerClient(), cli); } ServerReload.reloadIfRequired(managementClient); } } protected static void setDefaultEventListenerOfApplicationDomain(CLIWrapper cli) { setEventListenerOfApplicationDomain(cli, "local-audit"); } protected static void setEventListenerOfApplicationDomain(CLIWrapper cli, String auditlog) { cli.sendLine(String.format( "/subsystem=elytron/security-domain=ApplicationDomain:write-attribute(name=security-event-listener,value=%s)", auditlog)); cli.sendLine(String.format( "/subsystem=elytron/security-domain=%s:write-attribute(name=security-event-listener,value=%s)", SD_WITHOUT_LOGIN_PERMISSION, auditlog)); } protected static SimpleSecurityDomain createSecurityDomainWithoutPermissionMapper(String domainName) { return SimpleSecurityDomain.builder().withName(domainName) .withDefaultRealm("ApplicationFsRealm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("ApplicationFsRealm") .withRoleDecoder("groups-to-roles").build()) .build(); } private static WebArchive createWar(String warName) { return ShrinkWrap.create(WebArchive.class, warName + ".war") .addClasses(SimpleServlet.class) .addAsWebInfResource(FileAuditLogTestCase.class.getPackage(), "BasicAuthentication-web.xml", "web.xml"); } }
6,705
45.569444
126
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/CommonBase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.certs; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.net.URISyntaxException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import org.apache.http.Header; import org.hamcrest.MatcherAssert; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.logging.Logger; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.hamcrest.CoreMatchers; import org.junit.Assert; /** * Common methods that are used for both CRL and OCSP tests. * * @author Jan Stourac <jstourac@redhat.com> */ public class CommonBase { private Logger logger = Logger.getLogger(CommonBase.class); protected void setSoftFail(boolean value) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { cli.sendLine(String.format( "/subsystem=elytron/trust-manager=serverTrustManager:write-attribute(name=soft-fail, value=\"%s\")", value)); } finally { cli.sendLine(String.format("reload")); } } } protected void setCrl(String crlFile) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { if (crlFile != null) { cli.sendLine(String.format( "/subsystem=elytron/trust-manager=serverTrustManager:write-attribute(name=certificate-revocation-list, value={path=%s})", crlFile)); } else { cli.sendLine( "/subsystem=elytron/trust-manager=serverTrustManager:undefine-attribute(name=certificate-revocation-list)"); } } finally { cli.sendLine(String.format("reload")); } } } protected void setPreferCrls(Boolean preferCrls) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { if (preferCrls != null) { cli.sendLine(String.format( "/subsystem=elytron/trust-manager=serverTrustManager:write-attribute(name=ocsp.prefer-crls, value=%s)", preferCrls)); } else { cli.sendLine( "/subsystem=elytron/trust-manager=serverTrustManager:undefine-attribute(name=ocsp.prefer-crls)"); } } finally { cli.sendLine(String.format("reload")); } } } protected void setOcspUrl(String ocspResponderUrl) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { if (ocspResponderUrl != null) { cli.sendLine(String.format( "/subsystem=elytron/trust-manager=serverTrustManager:write-attribute(name=ocsp.responder, value=%s)", ocspResponderUrl)); } else { cli.sendLine( "/subsystem=elytron/trust-manager=serverTrustManager:undefine-attribute(name=ocsp.responder)"); } } finally { cli.sendLine(String.format("reload")); } } } protected void setMaxCertChain(Integer maximumCertPath) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { try { if (maximumCertPath != null) { cli.sendLine(String.format( "/subsystem=elytron/trust-manager=serverTrustManager:write-attribute(name=maximum-cert-path, value=%s)", maximumCertPath)); } else { cli.sendLine( "/subsystem=elytron/trust-manager=serverTrustManager:undefine-attribute(name=maximum-cert-path)"); } } finally { cli.sendLine(String.format("reload")); } } } protected void testCommon(KeyStore clientKeystore, KeyStore clientTruststore, String password, boolean expectValid) throws Exception { Assert.assertNotNull("Keystore for client is null!", clientKeystore); Assert.assertNotNull("Truststore for client is null!", clientTruststore); final SSLContext clientContext = createSSLContext(clientKeystore, clientTruststore, password); performConnectionTest(clientContext, expectValid); } private SSLContext createSSLContext(KeyStore clientKeystore, KeyStore clientTruststore, String password) throws Exception { try { return SSLContexts.custom().loadTrustMaterial(clientTruststore, new TrustSelfSignedStrategy()).loadKeyMaterial(clientKeystore, password.toCharArray()).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | UnrecoverableKeyException e) { throw new RuntimeException("Failed to read keystore", e); } } private void performConnectionTest(SSLContext clientContext, boolean expectValid) throws Exception { // perform request from client to server with appropriate client ssl context (certificate) ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<SSLSocket> socketFuture = executorService.submit(() -> { try { logger.info("About to connect client"); SSLSocket sslSocket = (SSLSocket) clientContext.getSocketFactory().createSocket(InetAddress.getLoopbackAddress(), 8443); sslSocket.getSession(); return sslSocket; } catch (Exception e) { throw new RuntimeException(e); } finally { logger.info("Client connected"); } }); SSLSocket clientSocket = socketFuture.get(); SSLSession clientSession = clientSocket.getSession(); try { if (expectValid) { Assert.assertTrue("Client SSL Session should be Valid", clientSession.isValid()); } else { Assert.assertFalse("Client SSL Session should be Invalid", clientSession.isValid()); } } finally { safeClose(clientSocket); } if (expectValid) { // Now check that complete HTTPS GET request can be performed successfully. performHttpGet(clientContext); } } protected void performHttpGet(SSLContext clientContext) throws Exception { URL url = new URIBuilder().setScheme("https").setHost("localhost").setPort(8443).setPath("/").build().toURL(); performHttpGet(clientContext, url, HttpStatus.SC_OK, "Welcome to "); } protected void performHttpGet(KeyStore clientKeystore, KeyStore clientTruststore, String password, URL url, int expectedStatus, String containedText, Header... headers) throws Exception { performHttpGet(createSSLContext(clientKeystore, clientTruststore, password), url, expectedStatus, containedText, headers); } protected void performHttpGet(SSLContext clientContext, URL url, int expectedStatus, String containedText, Header... headers) throws IOException, URISyntaxException { HttpEntity httpEntity = null; CloseableHttpResponse response = null; int statusCode = 0; String responseString = ""; try (final CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(clientContext).build()) { HttpGet httpget = new HttpGet(url.toURI()); httpget.setHeaders(headers); response = httpClient.execute(httpget); httpEntity = response.getEntity(); Assert.assertNotNull("HTTP entity is null, which is not expected!", httpEntity); statusCode = response.getStatusLine().getStatusCode(); responseString = EntityUtils.toString(httpEntity); Assert.assertEquals(expectedStatus, statusCode); if (expectedStatus == HttpStatus.SC_OK) { MatcherAssert.assertThat(responseString, CoreMatchers.containsString(containedText)); } } finally { if (httpEntity != null) { EntityUtils.consumeQuietly(httpEntity); } } } private void safeClose(Closeable closeable) { try { closeable.close(); } catch (Exception ignored) { } } }
10,468
41.21371
170
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/crl/CertificateRevocationListTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.certs.crl; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; /** * Basic simple integration tests to check CRL functionality. * * @author Jan Stourac <jstourac@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient public class CertificateRevocationListTestCase extends CertificateRevocationListTestBase { /** * This test verifies a certificate *not* present in the CRL configured using * the certificate-revocation-list attribute gets accepted. */ @Test public void testTwoWayCertificateNotInServerCrl() throws Exception { configureSSLContext(TWO_WAY_SSL_CONTEXT_NAME); setSoftFail(false); testCommon(goodCertKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(goodCertKeyStore, trustStore, PASSWORD, true); restoreConfiguration(); } /** * This test verifies certificate present in the CRL configured in the server * using the certificate-revocation-list attribute gets rejected. */ @Test public void testTwoWayCertificateInServerCrl() throws Exception { configureSSLContext(TWO_WAY_SSL_CONTEXT_NAME); setSoftFail(false); testCommon(revokedCertKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(revokedCertKeyStore, trustStore, PASSWORD, false); restoreConfiguration(); } /** * This test verifies a certificate present in the single CRL configured using the certificate-revocation-lists * attribute gets rejected. */ @Test public void testTwoWayCertificateInServerCrls() throws Exception { configureSSLContext(TWO_WAY_SINGLE_CRL_SSL_CONTEXT); setSoftFail(false); testCommon(revokedCertKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(revokedCertKeyStore, trustStore, PASSWORD, false); restoreConfiguration(); } /** * This test verifies certificates present in any CRL configured with the * certificate-revocation-lists attribute gets rejected. */ @Test public void testTwoWayCertificateInMultipleServerCrls() throws Exception { configureSSLContext(TWO_WAY_MULTIPLE_CRL_SSL_CONTEXT); setSoftFail(false); testCommon(revokedCertKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(revokedCertKeyStore, trustStore, PASSWORD, false); restoreConfiguration(); } /** * This test verifies certificates *not* present in any of the CRLs configured with * the certificate-revocation-lists attribute gets accepted. */ @Test public void testTwoWayCertificateNotInMultipleServerCrls() throws Exception { configureSSLContext(TWO_WAY_MULTIPLE_CRL_SSL_CONTEXT); setSoftFail(false); testCommon(goodCertKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(goodCertKeyStore, trustStore, PASSWORD, true); restoreConfiguration(); } }
4,205
32.648
115
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/crl/CertificateRevocationListTestBase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.certs.crl; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.net.URL; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.Principal; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; import javax.security.auth.x500.X500Principal; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.shared.CliUtils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.wildfly.security.x500.cert.BasicConstraintsExtension; import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey; import org.wildfly.security.x500.cert.X509CertificateBuilder; import org.wildfly.test.integration.elytron.certs.CommonBase; import org.wildfly.test.integration.elytron.util.WelcomeContent; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.CertificateRevocationList; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleKeyManager; import org.wildfly.test.security.common.elytron.SimpleKeyStore; import org.wildfly.test.security.common.elytron.SimpleServerSslContext; import org.wildfly.test.security.common.elytron.SimpleTrustManager; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.X509v2CRLBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.MiscPEMGenerator; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.util.io.pem.PemWriter; import org.junit.Assert; import org.junit.runner.RunWith; /** * Auxiliary methods and variables for @{@link CertificateRevocationListTestCase}. * * @author Jan Stourac <jstourac@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({CertificateRevocationListTestBase.CrlServerSetup.class, WelcomeContent.SetupTask.class }) public class CertificateRevocationListTestBase extends CommonBase { protected static KeyStore trustStore; protected static KeyStore goodCertKeyStore; protected static KeyStore revokedCertKeyStore; protected static KeyStore otherRevokedCertKeyStore; protected static final String PASSWORD = "Elytron"; protected static final String TWO_WAY_SSL_CONTEXT_NAME = "serverSslContext"; protected static final String TWO_WAY_MULTIPLE_CRL_SSL_CONTEXT = "otherServerSslContext"; protected static final String TWO_WAY_SINGLE_CRL_SSL_CONTEXT = "singleCrlSslContext"; private static final char[] PASSWORD_CHAR = PASSWORD.toCharArray(); private static final String HTTPS = "https"; private static final String CA_JKS_LOCATION = "." + File.separator + "target" + File.separator + "test-classes" + File.separator + "ca" + File.separator + "jks"; private static final File WORKING_DIR_CA = new File(CA_JKS_LOCATION); private static final File LADYBIRD_FILE = new File(WORKING_DIR_CA, "ladybird.keystore"); private static final File CHECKED_GOOD_FILE = new File(WORKING_DIR_CA, "checked-good.keystore"); private static final File CHECKED_REVOKED_FILE = new File(WORKING_DIR_CA, "checked-revoked.keystore"); private static final File OTHER_REVOKED_FILE = new File(WORKING_DIR_CA, "other-revoked.keystore"); private static final File TRUST_FILE = new File(WORKING_DIR_CA, "ca.truststore"); private static final String CA_CRL_LOCATION = "." + File.separator + "target" + File.separator + "test-classes" + File.separator + "ca" + File.separator + "crl"; private static final File WORKING_DIR_CACRL = new File(CA_CRL_LOCATION); private static final File CA_BLANK_PEM_CRL = new File(WORKING_DIR_CACRL, "blank.pem"); private static final File CA_OTHER_PEM_CRL = new File(WORKING_DIR_CACRL, "other.pem"); private static KeyStore createKeyStore() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); return ks; } private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile, char[] password) throws Exception { if (!outputFile.exists()) { outputFile.createNewFile(); } try (FileOutputStream fos = new FileOutputStream(outputFile)) { keyStore.store(fos, password); } } private static X500Name convertSunStyleToBCStyle(Principal dn) { String dnName = dn.getName(); String[] dnComponents = dnName.split(", "); StringBuilder dnBuffer = new StringBuilder(dnName.length()); dnBuffer.append(dnComponents[dnComponents.length - 1]); for (int i = dnComponents.length - 2; i >= 0; i--) { dnBuffer.append(','); dnBuffer.append(dnComponents[i]); } return new X500Name(dnBuffer.toString()); } public static void beforeTest() throws Exception { Assert.assertTrue(WORKING_DIR_CA.mkdirs()); Assert.assertTrue(WORKING_DIR_CACRL.mkdirs()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); Security.addProvider(new BouncyCastleProvider()); X500Principal issuerDN = new X500Principal( "CN=Elytron CA, ST=Elytron, C=UK, EMAILADDRESS=elytron@wildfly.org, O=Root Certificate Authority"); KeyStore ladybirdKeyStore = createKeyStore(); trustStore = createKeyStore(); // Generates the issuer certificate and adds it to the keystores SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder() .setDn(issuerDN) .setKeyAlgorithmName("RSA") .setSignatureAlgorithmName("SHA256withRSA") .addExtension(false, "BasicConstraints","CA:true,pathlen:2147483647") .build(); X509Certificate issuerCertificate = issuerSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); ladybirdKeyStore.setCertificateEntry("ca", issuerCertificate); trustStore.setCertificateEntry("mykey", issuerCertificate); // Generates certificate and keystore for Ladybird KeyPair ladybirdKeys = keyPairGenerator.generateKeyPair(); PrivateKey ladybirdSigningKey = ladybirdKeys.getPrivate(); PublicKey ladybirdPublicKey = ladybirdKeys.getPublic(); X509Certificate ladybirdCertificate = new X509CertificateBuilder().setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ladybirdPublicKey) .setSerialNumber(new BigInteger("3")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); ladybirdKeyStore.setKeyEntry("ladybird", ladybirdSigningKey, PASSWORD_CHAR, new X509Certificate[]{ladybirdCertificate, issuerCertificate}); // Generates GOOD certificate - it is not part of CRL KeyPair checkedGoodKeys = keyPairGenerator.generateKeyPair(); PrivateKey checkedGoodSigningKey = checkedGoodKeys.getPrivate(); PublicKey checkedGoodPublicKey = checkedGoodKeys.getPublic(); X509Certificate checkedGoodCertificate = new X509CertificateBuilder().setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(checkedGoodPublicKey) .setSerialNumber(new BigInteger("16")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); goodCertKeyStore = createKeyStore(); goodCertKeyStore.setCertificateEntry("ca", issuerCertificate); goodCertKeyStore.setKeyEntry("localhost", checkedGoodSigningKey, PASSWORD_CHAR, new X509Certificate[]{checkedGoodCertificate, issuerCertificate}); createTemporaryKeyStoreFile(goodCertKeyStore, CHECKED_GOOD_FILE, PASSWORD_CHAR); // Generates REVOKED certificate - this one will be part of CRL KeyPair checkedRevokedKeys = keyPairGenerator.generateKeyPair(); PrivateKey checkedRevokedSigningKey = checkedRevokedKeys.getPrivate(); PublicKey checkedRevokedPublicKey = checkedRevokedKeys.getPublic(); X509Certificate checkedRevokedCertificate = new X509CertificateBuilder().setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(checkedRevokedPublicKey) .setSerialNumber(new BigInteger("17")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); revokedCertKeyStore = createKeyStore(); revokedCertKeyStore.setCertificateEntry("ca", issuerCertificate); revokedCertKeyStore.setKeyEntry("localhost", checkedRevokedSigningKey, PASSWORD_CHAR, new X509Certificate[]{checkedRevokedCertificate, issuerCertificate}); createTemporaryKeyStoreFile(revokedCertKeyStore, CHECKED_REVOKED_FILE, PASSWORD_CHAR); // Creates the CRL for ca/crl/blank.pem prepareCrlFiles(issuerCertificate, issuerSelfSignedX509CertificateAndSigningKey, checkedRevokedCertificate, CA_BLANK_PEM_CRL); // Generates another REVOKED certificate - this one will be part of another CRL KeyPair otherRevokedKeys = keyPairGenerator.generateKeyPair(); PrivateKey otherRevokedSigningKey = otherRevokedKeys.getPrivate(); PublicKey otherRevokedPublicKey = otherRevokedKeys.getPublic(); X509Certificate otherRevokedCertificate = new X509CertificateBuilder().setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(otherRevokedPublicKey) .setSerialNumber(new BigInteger("17")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); otherRevokedCertKeyStore = createKeyStore(); otherRevokedCertKeyStore.setCertificateEntry("ca", issuerCertificate); otherRevokedCertKeyStore.setKeyEntry("localhost", otherRevokedSigningKey, PASSWORD_CHAR, new X509Certificate[]{otherRevokedCertificate, issuerCertificate}); createTemporaryKeyStoreFile(otherRevokedCertKeyStore, OTHER_REVOKED_FILE, PASSWORD_CHAR); // Creates the CRL for ca/crl/other.pem prepareCrlFiles(issuerCertificate, issuerSelfSignedX509CertificateAndSigningKey, otherRevokedCertificate, CA_OTHER_PEM_CRL); // Create the temporary files createTemporaryKeyStoreFile(ladybirdKeyStore, LADYBIRD_FILE, PASSWORD_CHAR); // keystore for server config createTemporaryKeyStoreFile(trustStore, TRUST_FILE, PASSWORD_CHAR); // trust file for server config } private static void prepareCrlFiles(X509Certificate intermediateIssuerCertificate, SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey, X509Certificate revoked, File crlFile) throws Exception { // Used for all CRLs Calendar calendar = Calendar.getInstance(); Date currentDate = calendar.getTime(); calendar.add(Calendar.YEAR, 1); Date nextYear = calendar.getTime(); calendar.add(Calendar.YEAR, -1); calendar.add(Calendar.SECOND, -30); Date revokeDate = calendar.getTime(); X509v2CRLBuilder caBlankCrlBuilder = new X509v2CRLBuilder(convertSunStyleToBCStyle(intermediateIssuerCertificate.getIssuerDN()), currentDate); caBlankCrlBuilder.addCRLEntry(revoked.getSerialNumber(), currentDate, CRLReason.unspecified); X509CRLHolder caBlankCrlHolder = caBlankCrlBuilder.setNextUpdate(nextYear).build( new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build( issuerSelfSignedX509CertificateAndSigningKey.getSigningKey())); PemWriter caBlankCrlOutput = new PemWriter(new OutputStreamWriter(new FileOutputStream(crlFile))); caBlankCrlOutput.writeObject(new MiscPEMGenerator(caBlankCrlHolder)); caBlankCrlOutput.close(); } public static void afterTest() { Assert.assertTrue(LADYBIRD_FILE.delete()); Assert.assertTrue(CHECKED_GOOD_FILE.delete()); Assert.assertTrue(CHECKED_REVOKED_FILE.delete()); Assert.assertTrue(OTHER_REVOKED_FILE.delete()); Assert.assertTrue(TRUST_FILE.delete()); Assert.assertTrue(WORKING_DIR_CA.delete()); Assert.assertTrue(CA_BLANK_PEM_CRL.delete()); Assert.assertTrue(CA_OTHER_PEM_CRL.delete()); Assert.assertTrue(WORKING_DIR_CACRL.delete()); } protected static void configureSSLContext(String sslContextName) throws Exception { try(CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine("batch"); cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:write-attribute" + "(name=ssl-context,value=%s)", HTTPS, sslContextName)); cli.sendLine("run-batch"); cli.sendLine("reload"); } } protected void restoreConfiguration() throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine("batch"); cli.sendLine(String.format("/subsystem=undertow/server=default-server/https-listener=%s:write-attribute" + "(name=ssl-context,value=%s)", HTTPS, "applicationSSC")); cli.sendLine("run-batch"); cli.sendLine("reload"); } } // This is a dummy deployment just to CrlServerSetup task is kicked off. Not sure about better way ATM. @Deployment protected static WebArchive createDeployment() { return createDeployment("dummy"); } @ArquillianResource protected URL url; protected static WebArchive createDeployment(final String name) { return ShrinkWrap.create(WebArchive.class, name + ".war"); } static class CrlServerSetup extends AbstractElytronSetupTask { @Override protected void setup(ModelControllerClient modelControllerClient) throws Exception { CertificateRevocationListTestBase.beforeTest(); super.setup(modelControllerClient); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); CertificateRevocationListTestBase.afterTest(); } @Override protected ConfigurableElement[] getConfigurableElements() { LinkedList<ConfigurableElement> elements = new LinkedList<>(); CredentialReference serverKeyStoreCredRef = CredentialReference.builder().withClearText(PASSWORD).build(); // Prepare server key-store and key-manager for server ssl context Path serverKeyStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(LADYBIRD_FILE)).build(); SimpleKeyStore serverKeyStore = SimpleKeyStore.builder().withName("serverKeyStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(serverKeyStorePath).build(); elements.add(serverKeyStore); SimpleKeyManager serverKeyManager = SimpleKeyManager.builder().withName("serverKeyManager").withKeyStore( serverKeyStore.getName()).withCredentialReference(serverKeyStoreCredRef).build(); elements.add(serverKeyManager); // Prepare server trust-store (with CRL configuration) and related key-manager for server ssl context Path serverTrustStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(TRUST_FILE)).build(); SimpleKeyStore serverTrustStore = SimpleKeyStore.builder().withName("serverTrustStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(serverTrustStorePath).build(); elements.add(serverTrustStore); CertificateRevocationList crl = CertificateRevocationList.builder().withPath(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)).build(); SimpleTrustManager serverTrustManager = SimpleTrustManager.builder().withName("serverTrustManager").withKeyStore( serverTrustStore.getName()).withSoftFail(false).withCrl(crl).withAlgorithm("PKIX").build(); elements.add(serverTrustManager); // Prepare alternative server trust manager (with multiple CRLs configuration) to test CRLs support CertificateRevocationList crl2 = CertificateRevocationList.builder().withPath(CliUtils.asAbsolutePath(CA_OTHER_PEM_CRL)).build(); List<CertificateRevocationList> crls = new ArrayList<>(); crls.add(crl); crls.add(crl2); SimpleTrustManager multipleCrlServerTrustManager = SimpleTrustManager.builder().withName("multipleCrlServerTrustManager").withKeyStore( serverTrustStore.getName()).withSoftFail(false).withCrls(crls).withAlgorithm("PKIX").build(); elements.add(multipleCrlServerTrustManager); // Prepare trust manager that configures a single CRL using the certificate-revocation-lists attribute crls.remove(crl2); SimpleTrustManager singleCrlServerTrustManager = SimpleTrustManager.builder().withName("singleCrlServerTrustManager").withKeyStore( serverTrustStore.getName()).withSoftFail(false).withCrls(crls).withAlgorithm("PKIX").build(); elements.add(singleCrlServerTrustManager); // Create two way server ssl context with prepared key and trust managers. SimpleServerSslContext twoWayServerSslContext = SimpleServerSslContext.builder().withName(TWO_WAY_SSL_CONTEXT_NAME).withKeyManagers( serverKeyManager.getName()).withNeedClientAuth(true).withTrustManagers( serverTrustManager.getName()).build(); elements.add(twoWayServerSslContext); // Create another two way server ssl context to use the trust manager that supports multiple CRLs SimpleServerSslContext otherTwoWaySslContext = SimpleServerSslContext.builder().withName(TWO_WAY_MULTIPLE_CRL_SSL_CONTEXT).withKeyManagers( serverKeyManager.getName()).withNeedClientAuth(true).withTrustManagers( multipleCrlServerTrustManager.getName()).build(); elements.add(otherTwoWaySslContext); // Creates another two way server ssl context to use the trust manager that has configured a single CRL // using the certificate-revocation-lists attribute SimpleServerSslContext singleCrlTwoWaySslContext = SimpleServerSslContext.builder().withName(TWO_WAY_SINGLE_CRL_SSL_CONTEXT).withKeyManagers( serverKeyManager.getName()).withNeedClientAuth(true).withTrustManagers( singleCrlServerTrustManager.getName()).build(); elements.add(singleCrlTwoWaySslContext); return elements.toArray(new ConfigurableElement[]{}); } } }
22,200
51.360849
134
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/realm/KeystoreRealmTestCase.java
/* * Copyright 2020 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.certs.realm; import java.io.File; import java.io.OutputStream; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; import javax.security.auth.x500.X500Principal; import org.apache.commons.io.FileUtils; import org.apache.http.HttpStatus; import org.apache.http.client.utils.URIBuilder; import org.apache.http.message.BasicHeader; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.PrincipalPrintingServlet; import org.jboss.as.test.shared.CliUtils; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.x500.GeneralName; import org.wildfly.security.x500.cert.BasicConstraintsExtension; import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey; import org.wildfly.security.x500.cert.SubjectAlternativeNamesExtension; import org.wildfly.security.x500.cert.X509CertificateBuilder; import org.wildfly.test.integration.elytron.certs.CommonBase; import org.wildfly.test.integration.elytron.util.WelcomeContent; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.ConstantRoleMapper; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.KeyStoreRealm; import org.wildfly.test.security.common.elytron.MechanismConfiguration; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleHttpAuthenticationFactory; import org.wildfly.test.security.common.elytron.SimpleKeyManager; import org.wildfly.test.security.common.elytron.SimpleKeyStore; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.SimpleServerSslContext; import org.wildfly.test.security.common.elytron.SimpleTrustManager; import org.wildfly.test.security.common.elytron.UndertowSslContext; import org.wildfly.test.security.common.elytron.X500AttributePrincipalDecoder; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * <p>Test for the key-store certificate realm. It checks direct connection * and using proxy headers.</p> * * @author rmartinc */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({KeystoreRealmTestCase.ServerSetup.class, KeystoreRealmTestCase.ForwardingSetup.class, WelcomeContent.SetupTask.class}) public class KeystoreRealmTestCase extends CommonBase { protected static KeyStore trustStore; protected static KeyStore keyStore; protected static KeyStore usersStore; protected static KeyStore user1Store; protected static final String PASSWORD = "Elytron"; private static final char[] PASSWORD_CHAR = PASSWORD.toCharArray(); private static final String CA_JKS_LOCATION = "." + File.separator + "target" + File.separator + "test-classes" + File.separator + "ca" + File.separator + "jks-keystoreRealmTestCase"; private static final File WORKING_DIR_CA = new File(CA_JKS_LOCATION); private static final File TRUST_FILE = new File(WORKING_DIR_CA, "ca.truststore"); private static final File KEYSTORE_FILE = new File(WORKING_DIR_CA, "server.keystore"); private static final File USERS_KEYSTORE_FILE = new File(WORKING_DIR_CA, "users.keystore"); private static final File USER1_KEYSTORE_FILE = new File(WORKING_DIR_CA, "user1.keystore"); private static final String CETIFICATE_DOMAIN = "certificateDomain"; @ArquillianResource protected URL webAppURL; @Deployment(testable = false) protected static WebArchive createDeployment() { final Package currentPackage = KeystoreRealmTestCase.class.getPackage(); return ShrinkWrap.create(WebArchive.class, KeystoreRealmTestCase.class.getSimpleName() + ".war") .addClasses(PrincipalPrintingServlet.class) .addAsWebInfResource(currentPackage, "KeystoreRealmTestCase-web.xml", "web.xml") .addAsWebInfResource(Utils.getJBossWebXmlAsset(CETIFICATE_DOMAIN), "jboss-web.xml"); } protected URL getPrincipalServletURL() throws MalformedURLException, URISyntaxException{ return new URIBuilder() .setScheme("https") .setHost("localhost") .setPort(8443) .setPath(webAppURL.getPath() + PrincipalPrintingServlet.SERVLET_PATH.substring(1)) .build().toURL(); } @Test public void testRootConnectionNoCertificate() throws Exception { // trustStore has no keys => ssl error testCommon(trustStore, trustStore, PASSWORD, false); } @Test public void testUserRootConnection() throws Exception { // user certificate should work at TLS level testCommon(user1Store, trustStore, PASSWORD, true); } @Test public void testServerRootConnection() throws Exception { // server certificate should work at TLS level testCommon(keyStore, trustStore, PASSWORD, true); } @Test public void testUserPrincipal() throws Exception { // user certificate should connect to the servlet app performHttpGet(user1Store, trustStore, PASSWORD, getPrincipalServletURL(), HttpStatus.SC_OK, "user1"); } @Test public void testServerPrincipal() throws Exception { // the server certificate is not in the usersStore performHttpGet(keyStore, trustStore, PASSWORD, getPrincipalServletURL(), HttpStatus.SC_FORBIDDEN, "localhost"); } @Test public void testUserPrincipalWithHeaders() throws Exception { // Using server certificate for TLS connect using proxy for user1 Base64.Encoder encoder = Base64.getMimeEncoder(); String cert = "-----BEGIN CERTIFICATE----- " + encoder.encodeToString(user1Store.getCertificate("user1").getEncoded()) + " -----END CERTIFICATE-----"; cert = cert.replace("\r\n", " "); performHttpGet(keyStore, trustStore, PASSWORD, getPrincipalServletURL(), HttpStatus.SC_OK, "user1", new BasicHeader("SSL_SESSION_ID", "1633d36df6f28e1325912b46f7d214f97370c39a6b3fc24ee374a76b3f9b0fba"), new BasicHeader("SSL_CLIENT_CERT", cert), new BasicHeader("SSL_CIPHER", "ECDHE-RSA-AES128-GCM-SHA256")); } /** * Setup class to establish https and the certificate real. */ static class ServerSetup extends AbstractElytronSetupTask { private static KeyStore createKeyStore() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); return ks; } private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile, char[] password) throws Exception { try (OutputStream fos = Files.newOutputStream(outputFile.toPath())) { keyStore.store(fos, password); } } @Override protected void setup(ModelControllerClient modelControllerClient) throws Exception { if (WORKING_DIR_CA.exists()) { FileUtils.deleteQuietly(WORKING_DIR_CA); } Assert.assertTrue(WORKING_DIR_CA.mkdirs()); keyStore = createKeyStore(); trustStore = createKeyStore(); usersStore = createKeyStore(); user1Store = createKeyStore(); // generate the CA key and certificate KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); X500Principal issuerDN = new X500Principal("C=UK, O=elytron.com, CN=Elytron CA"); SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder() .setDn(issuerDN) .setKeyAlgorithmName("RSA") .setSignatureAlgorithmName("SHA256withRSA") .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647") .build(); X509Certificate issuerCertificate = issuerSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setCertificateEntry("ca", issuerCertificate); trustStore.setCertificateEntry("ca", issuerCertificate); // generate the server key and keystore KeyPair serverKeys = keyPairGenerator.generateKeyPair(); X509Certificate serverCertificate = new X509CertificateBuilder().setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("C=UK, O=elytron.com, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(serverKeys.getPublic()) .setSerialNumber(new BigInteger("3")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .addExtension(new SubjectAlternativeNamesExtension(false, Arrays.asList(new GeneralName.DNSName("localhost"), new GeneralName.IPAddress("127.0.0.1")))) .build(); keyStore.setKeyEntry("localhost", serverKeys.getPrivate(), PASSWORD_CHAR, new X509Certificate[]{serverCertificate, issuerCertificate}); // generate the users store with user1 and the server itself KeyPair user1Keys = keyPairGenerator.generateKeyPair(); X509Certificate user1Certificate = new X509CertificateBuilder().setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("C=UK, O=elytron.com, CN=user1")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(user1Keys.getPublic()) .setSerialNumber(new BigInteger("3")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); user1Store.setKeyEntry("user1", user1Keys.getPrivate(), PASSWORD_CHAR, new X509Certificate[]{user1Certificate, issuerCertificate}); usersStore.setCertificateEntry("user1", user1Certificate); createTemporaryKeyStoreFile(keyStore, KEYSTORE_FILE, PASSWORD_CHAR); createTemporaryKeyStoreFile(trustStore, TRUST_FILE, PASSWORD_CHAR); createTemporaryKeyStoreFile(usersStore, USERS_KEYSTORE_FILE, PASSWORD_CHAR); createTemporaryKeyStoreFile(user1Store, USER1_KEYSTORE_FILE, PASSWORD_CHAR); super.setup(modelControllerClient); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); Assert.assertTrue(TRUST_FILE.delete()); Assert.assertTrue(KEYSTORE_FILE.delete()); Assert.assertTrue(USERS_KEYSTORE_FILE.delete()); Assert.assertTrue(USER1_KEYSTORE_FILE.delete()); Assert.assertTrue(WORKING_DIR_CA.delete()); } @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); // credential reference for all the stores CredentialReference serverKeyStoreCredRef = CredentialReference.builder().withClearText(PASSWORD).build(); // create the keystore for the server Path serverKeyStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(KEYSTORE_FILE)).build(); SimpleKeyStore serverKeyStore = SimpleKeyStore.builder().withName("serverKeyStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(serverKeyStorePath).build(); elements.add(serverKeyStore); SimpleKeyManager serverKeyManager = SimpleKeyManager.builder().withName("serverKeyManager").withKeyStore( serverKeyStore.getName()).withCredentialReference(serverKeyStoreCredRef).build(); elements.add(serverKeyManager); // Prepare server trust-store (with CRL configuration) and related key-manager for server ssl context Path serverTrustStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(TRUST_FILE)).build(); SimpleKeyStore serverTrustStore = SimpleKeyStore.builder().withName("serverTrustStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(serverTrustStorePath).build(); elements.add(serverTrustStore); // create the trust-manager SimpleTrustManager serverTrustManager = SimpleTrustManager.builder().withName("serverTrustManager").withKeyStore( serverTrustStore.getName()).withAlgorithm("PKIX").build(); elements.add(serverTrustManager); // Create final server ssl context with prepared key and trust managers. SimpleServerSslContext serverSslContext = SimpleServerSslContext.builder().withName("serverSslContext").withKeyManagers( serverKeyManager.getName()).withNeedClientAuth(true).withTrustManagers( serverTrustManager.getName()).build(); elements.add(serverSslContext); // Configure created server ssl context for undertow default HTTPS listener. UndertowSslContext undertowSslContext = UndertowSslContext.builder().withHttpsListener("https").withName( serverSslContext.getName()).build(); elements.add(undertowSslContext); // create the keystore realm for users Path usersStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(USERS_KEYSTORE_FILE)).build(); SimpleKeyStore usersKeyStore = SimpleKeyStore.builder().withName("usersKeyStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(usersStorePath).build(); elements.add(usersKeyStore); KeyStoreRealm usersKeyStoreRealm = KeyStoreRealm.builder().withName("usersKeyStoreRealm").withKeyStore("usersKeyStore").build(); elements.add(usersKeyStoreRealm); ConstantRoleMapper usersRoleMapper = ConstantRoleMapper.builder().withName("usersRoleMapper").withRoles("Users").build(); elements.add(usersRoleMapper); X500AttributePrincipalDecoder cnUsersDecoder = X500AttributePrincipalDecoder.builder().withName("cnUsersDecoder") .withOid("2.5.4.3").withMaximumSegments(1).build(); elements.add(cnUsersDecoder); SimpleSecurityDomain certificateDomain = SimpleSecurityDomain.builder().withName(CETIFICATE_DOMAIN) .withDefaultRealm("usersKeyStoreRealm") .withPrincipalDecoder("cnUsersDecoder") .withRoleMapper("usersRoleMapper") .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("usersKeyStoreRealm") .build()) .build(); elements.add(certificateDomain); SimpleHttpAuthenticationFactory certificateHttpAuthFact = SimpleHttpAuthenticationFactory.builder() .withName("certificateHttpAuthFact") .withHttpServerMechanismFactory("global") .withSecurityDomain("certificateDomain") .addMechanismConfiguration(MechanismConfiguration.builder() .withMechanismName("CLIENT_CERT").build()) .build(); elements.add(certificateHttpAuthFact); UndertowApplicationSecurityDomain undertowDomain = UndertowApplicationSecurityDomain.builder() .withName(CETIFICATE_DOMAIN) .httpAuthenticationFactory("certificateHttpAuthFact") .build(); elements.add(undertowDomain); return elements.toArray(new ConfigurableElement[0]); } } /** * Helper class to enable the forwarding options to true. */ static class ForwardingSetup implements ServerSetupTask { private PathAddress getHttpsPath() { return PathAddress.pathAddress().append("subsystem", "undertow") .append("server", "default-server") .append("https-listener", "https"); } @Override public void setup(ManagementClient mc, String string) throws Exception { ModelNode op = Util.createOperation(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, getHttpsPath()); op.get(ModelDescriptionConstants.NAME).set("certificate-forwarding"); op.get(ModelDescriptionConstants.VALUE).set("true"); CoreUtils.applyUpdate(op, mc.getControllerClient()); op = Util.createOperation(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION, getHttpsPath()); op.get(ModelDescriptionConstants.NAME).set("proxy-address-forwarding"); op.get(ModelDescriptionConstants.VALUE).set("true"); CoreUtils.applyUpdate(op, mc.getControllerClient()); ServerReload.reloadIfRequired(mc); } @Override public void tearDown(ManagementClient mc, String string) throws Exception { ModelNode op = Util.createOperation(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, getHttpsPath()); op.get(ModelDescriptionConstants.NAME).set("certificate-forwarding"); CoreUtils.applyUpdate(op, mc.getControllerClient()); op = Util.createOperation(ModelDescriptionConstants.UNDEFINE_ATTRIBUTE_OPERATION, getHttpsPath()); op.get(ModelDescriptionConstants.NAME).set("proxy-address-forwarding"); CoreUtils.applyUpdate(op, mc.getControllerClient()); ServerReload.reloadIfRequired(mc); } } }
19,998
52.330667
158
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/ocsp/TestingOcspServer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.certs.ocsp; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.time.Instant; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import org.junit.Assert; import org.mockserver.integration.ClientAndServer; import org.mockserver.matchers.Times; import org.mockserver.model.Header; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse; import org.mockserver.model.NottableString; import org.wildfly.common.iteration.ByteIterator; import org.xipki.datasource.DataSourceFactory; import org.xipki.datasource.DataSourceWrapper; import org.xipki.http.servlet.ServletURI; import org.xipki.http.servlet.SslReverseProxyMode; import org.xipki.ocsp.server.impl.HttpOcspServlet; import org.xipki.ocsp.server.impl.OcspServer; import org.xipki.security.SecurityFactoryImpl; import org.xipki.security.SignerFactoryRegisterImpl; /** * Trivial XiPKI based OCSP server for OCSP support testing. */ public class TestingOcspServer { private int port; private OcspServer ocspServer = null; private ClientAndServer server; private Connection connection; private SecurityFactoryImpl securityFactory = new SecurityFactoryImpl(); public TestingOcspServer(int port) throws Exception { this.port = port; initDatabase(); } private void initDatabase() throws Exception { DataSourceFactory dataSourceFactory = new DataSourceFactory(); DataSourceWrapper dataSourceWrapper = dataSourceFactory.createDataSource("datasource1", TestingOcspServer.class.getResource("ocsp-db.properties").openStream(), securityFactory.getPasswordResolver()); connection = dataSourceWrapper.getConnection(); // structure described in: // https://github.com/xipki/xipki/blob/v3.0.0/ca-server/src/main/resources/sql/ocsp-init.xml connection.prepareStatement("CREATE TABLE ISSUER (\n" + " ID INT NOT NULL,\n" + " SUBJECT VARCHAR(350) NOT NULL,\n" + " NBEFORE BIGINT NOT NULL,\n" // notBefore + " NAFTER BIGINT NOT NULL,\n" // notAfter + " S1C CHAR(28) NOT NULL,\n" // base64 encoded SHA1 sum of the certificate + " REV SMALLINT DEFAULT 0,\n" // whether the certificate is revoked + " RR SMALLINT,\n" // revocation reason + " RT BIGINT,\n" // revocation time + " RIT BIGINT,\n" // revocation invalidity time + " CERT VARCHAR(4000) NOT NULL,\n" + " CRL_INFO VARCHAR(1000)\n" // CRL information if this issuer is imported from a CRL + ");").execute(); connection.prepareStatement("CREATE TABLE CERT (\n" + " ID BIGINT NOT NULL,\n" + " IID INT NOT NULL,\n" // issuer id (reference into ISSUER table) + " SN VARCHAR(40) NOT NULL,\n" // serial number + " LUPDATE BIGINT NOT NULL,\n" // last update + " NBEFORE BIGINT,\n" // notBefore + " NAFTER BIGINT,\n" // notAfter + " REV SMALLINT DEFAULT 0,\n" // whether the certificate is revoked + " RR SMALLINT,\n" // revocation reason + " RT BIGINT,\n" // revocation time + " RIT BIGINT,\n" // revocation invalidity time + " PN VARCHAR(45)\n" // certificate profile name + ");").execute(); } public void start() throws Exception { Assert.assertNull("OCSP server already started", ocspServer); ocspServer = new OcspServer(); ocspServer.setConfFile(TestingOcspServer.class.getResource("ocsp-responder.xml").getFile()); securityFactory.setSignerFactoryRegister(new SignerFactoryRegisterImpl()); ocspServer.setSecurityFactory(securityFactory); ocspServer.init(); HttpOcspServlet servlet = new HttpOcspServlet(); servlet.setServer(ocspServer); server = new ClientAndServer(port); server.when( request() .withMethod("POST") .withPath("/ocsp"), Times.unlimited()) .respond(request -> getHttpResponse(request, servlet)); server.when( request() .withMethod("GET") .withPath("/ocsp/.*"), Times.unlimited()) .respond(request -> getHttpResponse(request, servlet)); } public HttpResponse getHttpResponse(HttpRequest request, HttpOcspServlet servlet){ byte[] body; HttpMethod method; if (request.getBody() == null) { method = HttpMethod.GET; body = request.getPath().getValue().split("/ocsp/", 2)[1].getBytes(UTF_8); } else { method = HttpMethod.POST; body = request.getBody().getRawBytes(); } ByteBuf buffer = Unpooled.wrappedBuffer(body); FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, method, request.getPath().getValue(), buffer); for (Header header : request.getHeaderList()) { for (NottableString value : header.getValues()) { nettyRequest.headers().add(header.getName().getValue(), value.getValue()); } } FullHttpResponse nettyResponse; try { nettyResponse = servlet.service(nettyRequest, new ServletURI(request.getPath().getValue()), null, SslReverseProxyMode.NONE); } catch (Exception e) { throw new RuntimeException(e); } HttpResponse response = response() .withStatusCode(nettyResponse.status().code()) .withBody(nettyResponse.content().array()); for (Map.Entry<String, String> header : nettyResponse.headers()) { response.withHeader(header.getKey(), header.getValue()); } return response; } public void stop() throws SQLException { Assert.assertNotNull("OCSP server not started", ocspServer); if (server !=null ) { server.stop(); } ocspServer.shutdown(); if (connection != null) { connection.close(); } ocspServer = null; } public void createIssuer(int id, X509Certificate issuer) throws SQLException, CertificateException, NoSuchAlgorithmException { Assert.assertNull("OCSP server already started", ocspServer); MessageDigest digest = MessageDigest.getInstance("SHA-1"); PreparedStatement statement = connection.prepareStatement("INSERT INTO ISSUER (ID, SUBJECT, NBEFORE, NAFTER, S1C, CERT) VALUES (?, ?, ?, ?, ?, ?)"); statement.setInt(1, id); statement.setString(2, issuer.getSubjectDN().toString()); statement.setLong(3, issuer.getNotBefore().toInstant().getEpochSecond()); statement.setLong(4, issuer.getNotAfter().toInstant().getEpochSecond()); statement.setString(5, ByteIterator.ofBytes(digest.digest(issuer.getEncoded())).base64Encode().drainToString()); statement.setString(6, ByteIterator.ofBytes(issuer.getEncoded()).base64Encode().drainToString()); statement.execute(); } public void createCertificate(int id, int issuerId, X509Certificate certificate) throws SQLException { long time = Instant.now().getEpochSecond(); PreparedStatement statement = connection.prepareStatement("INSERT INTO CERT (ID, IID, SN, LUPDATE, NBEFORE, NAFTER) VALUES (?, ?, ?, ?, ?, ?)"); statement.setInt(1, id); statement.setInt(2, issuerId); statement.setString(3, certificate.getSerialNumber().toString(16)); statement.setLong(4, time); statement.setLong(5, certificate.getNotBefore().toInstant().getEpochSecond()); statement.setLong(6, certificate.getNotAfter().toInstant().getEpochSecond()); statement.execute(); } public void revokeCertificate(int id, int reason) throws SQLException { long time = Instant.now().getEpochSecond(); PreparedStatement statement = connection.prepareStatement("UPDATE CERT SET REV = 1, RR = ?, RT = ?, RIT = ? WHERE ID = ?"); statement.setInt(1, reason); statement.setLong(2, time); statement.setLong(3, time); statement.setInt(4, id); statement.execute(); } }
9,862
42.258772
207
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/ocsp/OcspTestBase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.certs.ocsp; import static org.wildfly.security.x500.X500.OID_AD_OCSP; import static org.wildfly.security.x500.X500.OID_KP_OCSP_SIGNING; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.Principal; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import javax.security.auth.x500.X500Principal; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.shared.CliUtils; import org.wildfly.security.x500.GeneralName; import org.wildfly.security.x500.cert.AccessDescription; import org.wildfly.security.x500.cert.AuthorityInformationAccessExtension; import org.wildfly.security.x500.cert.BasicConstraintsExtension; import org.wildfly.security.x500.cert.ExtendedKeyUsageExtension; import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey; import org.wildfly.security.x500.cert.X509CertificateBuilder; import org.wildfly.test.integration.elytron.certs.CommonBase; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.CertificateRevocationList; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.Ocsp; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleKeyManager; import org.wildfly.test.security.common.elytron.SimpleKeyStore; import org.wildfly.test.security.common.elytron.SimpleServerSslContext; import org.wildfly.test.security.common.elytron.SimpleTrustManager; import org.wildfly.test.security.common.elytron.UndertowSslContext; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509CRLHolder; import org.bouncycastle.cert.X509v2CRLBuilder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.MiscPEMGenerator; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.util.io.pem.PemWriter; import org.junit.Assert; /** * Auxiliary methods and variables for OCSP tests. * * @author Jan Stourac <jstourac@redhat.com> */ public class OcspTestBase extends CommonBase { protected static KeyStore trustStore; protected static KeyStore ocspCheckedGoodKeyStore; protected static KeyStore ocspCheckedGoodNoUrlKeyStore; protected static KeyStore ocspCheckedRevokedKeyStore; protected static KeyStore ocspCheckedUnknownKeyStore; protected static KeyStore ocspCheckedTooLongChainKeyStore; private static final int OCSP_PORT = 4854; protected static TestingOcspServer ocspServer = null; protected static final String PASSWORD = "Elytron"; protected static final char[] PASSWORD_CHAR = PASSWORD.toCharArray(); protected static final String CA_JKS_LOCATION = "." + File.separator + "target" + File.separator + "test-classes" + File.separator + "ca" + File.separator + "jks"; protected static final File WORKING_DIR_CA = new File(CA_JKS_LOCATION); protected static final File LADYBIRD_FILE = new File(WORKING_DIR_CA,"ladybird.keystore"); protected static final File OCSP_RESPONDER_FILE = new File(WORKING_DIR_CA,"ocsp-responder.keystore"); protected static final File OCSP_CHECKED_GOOD_FILE = new File(WORKING_DIR_CA,"ocsp-checked-good.keystore"); protected static final File OCSP_CHECKED_GOOD_NO_URL_FILE = new File(WORKING_DIR_CA,"ocsp-checked-good-no-url.keystore"); protected static final File OCSP_CHECKED_REVOKED_FILE = new File(WORKING_DIR_CA, "ocsp-checked-revoked.keystore"); protected static final File OCSP_CHECKED_UNKNOWN_FILE = new File(WORKING_DIR_CA, "ocsp-checked-unknown.keystore"); protected static final File OCSP_CHECKED_TOO_LONG_CHAIN_FILE = new File(WORKING_DIR_CA, "ocsp-checked-too-long-chain.keystore"); private static final String CA_CRL_LOCATION = "." + File.separator + "target" + File.separator + "test-classes" + File.separator + "ca" + File.separator + "crl"; private static final File WORKING_DIR_CACRL = new File(CA_CRL_LOCATION); protected static final File CA_BLANK_PEM_CRL = new File(WORKING_DIR_CACRL, "blank.pem"); protected static final File TRUST_FILE = new File(WORKING_DIR_CA,"ca.truststore"); protected static final String OCSP_RESPONDER_URL = "http://localhost:" + OCSP_PORT + "/ocsp"; private static KeyStore createKeyStore() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null,null); return ks; } private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile, char[] password) throws Exception { if (!outputFile.exists()) { outputFile.createNewFile(); } try (FileOutputStream fos = new FileOutputStream(outputFile)){ keyStore.store(fos, password); } } private static org.bouncycastle.asn1.x500.X500Name convertSunStyleToBCStyle(Principal dn) { String dnName = dn.getName(); String[] dnComponents = dnName.split(", "); StringBuilder dnBuffer = new StringBuilder(dnName.length()); dnBuffer.append(dnComponents[dnComponents.length-1]); for(int i = dnComponents.length-2; i >= 0; i--){ dnBuffer.append(','); dnBuffer.append(dnComponents[i]); } return new X500Name(dnBuffer.toString()); } private static X509Certificate issuerCertificate; private static X509Certificate intermediateIssuerCertificate; private static X509Certificate ocspCheckedGoodCertificate; private static X509Certificate ocspCheckedGoodNoUrlCertificate; private static X509Certificate ocspCheckedRevokedCertificate; private static X509Certificate ocspCheckedTooLongChainCertificate; public static void beforeTest() throws Exception { Assert.assertTrue(WORKING_DIR_CA.mkdirs()); Assert.assertTrue(WORKING_DIR_CACRL.mkdirs()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); Security.addProvider(new BouncyCastleProvider()); X500Principal issuerDN = new X500Principal("CN=Elytron CA, ST=Elytron, C=UK, EMAILADDRESS=elytron@wildfly.org, O=Root Certificate Authority"); X500Principal intermediateIssuerDN = new X500Principal("CN=Elytron ICA, ST=Elytron, C=UK, O=Intermediate Certificate Authority"); KeyStore ladybirdKeyStore = createKeyStore(); trustStore = createKeyStore(); // Generates the issuer certificate and adds it to the keystores SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder() .setDn(issuerDN) .setKeyAlgorithmName("RSA") .setSignatureAlgorithmName("SHA256withRSA") .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647") .build(); issuerCertificate = issuerSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); ladybirdKeyStore.setCertificateEntry("ca", issuerCertificate); trustStore.setCertificateEntry("mykey",issuerCertificate); // Generates certificate and keystore for Ladybird KeyPair ladybirdKeys = keyPairGenerator.generateKeyPair(); PrivateKey ladybirdSigningKey = ladybirdKeys.getPrivate(); PublicKey ladybirdPublicKey = ladybirdKeys.getPublic(); X509Certificate ladybirdCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ladybirdPublicKey) .setSerialNumber(new BigInteger("3")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); ladybirdKeyStore.setKeyEntry("ladybird", ladybirdSigningKey, PASSWORD_CHAR, new X509Certificate[]{ladybirdCertificate, issuerCertificate}); // Generates certificate and keystore for OCSP responder KeyPair ocspResponderKeys = keyPairGenerator.generateKeyPair(); PrivateKey ocspResponderSigningKey = ocspResponderKeys.getPrivate(); PublicKey ocspResponderPublicKey = ocspResponderKeys.getPublic(); X509Certificate ocspResponderCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=OcspResponder")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ocspResponderPublicKey) .setSerialNumber(new BigInteger("15")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .addExtension(new ExtendedKeyUsageExtension(false, Collections.singletonList(OID_KP_OCSP_SIGNING))) .build(); KeyStore ocspResponderKeyStore = createKeyStore(); ocspResponderKeyStore.setCertificateEntry("ca", issuerCertificate); ocspResponderKeyStore.setKeyEntry("ocspResponder", ocspResponderSigningKey, PASSWORD_CHAR, new X509Certificate[]{ocspResponderCertificate, issuerCertificate}); createTemporaryKeyStoreFile(ocspResponderKeyStore, OCSP_RESPONDER_FILE, PASSWORD_CHAR); // Generates GOOD certificate referencing the OCSP responder KeyPair ocspCheckedGoodKeys = keyPairGenerator.generateKeyPair(); PrivateKey ocspCheckedGoodSigningKey = ocspCheckedGoodKeys.getPrivate(); PublicKey ocspCheckedGoodPublicKey = ocspCheckedGoodKeys.getPublic(); ocspCheckedGoodCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ocspCheckedGoodPublicKey) .setSerialNumber(new BigInteger("16")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .addExtension(new AuthorityInformationAccessExtension(Collections.singletonList( new AccessDescription(OID_AD_OCSP, new GeneralName.URIName(OCSP_RESPONDER_URL)) ))).build(); ocspCheckedGoodKeyStore = createKeyStore(); ocspCheckedGoodKeyStore.setCertificateEntry("ca", issuerCertificate); ocspCheckedGoodKeyStore.setKeyEntry("localhost", ocspCheckedGoodSigningKey, PASSWORD_CHAR, new X509Certificate[]{ocspCheckedGoodCertificate, issuerCertificate}); createTemporaryKeyStoreFile(ocspCheckedGoodKeyStore, OCSP_CHECKED_GOOD_FILE, PASSWORD_CHAR); // Generates GOOD certificate but not referencing OCSP responder KeyPair ocspCheckedGoodNoUrlKeys = keyPairGenerator.generateKeyPair(); PrivateKey ocspCheckedGoodNoUrlSigningKey = ocspCheckedGoodNoUrlKeys.getPrivate(); PublicKey ocspCheckedGoodNoUrlPublicKey = ocspCheckedGoodNoUrlKeys.getPublic(); ocspCheckedGoodNoUrlCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ocspCheckedGoodNoUrlPublicKey) .setSerialNumber(new BigInteger("53")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); ocspCheckedGoodNoUrlKeyStore = createKeyStore(); ocspCheckedGoodNoUrlKeyStore.setCertificateEntry("ca", issuerCertificate); ocspCheckedGoodNoUrlKeyStore.setKeyEntry("localhost", ocspCheckedGoodNoUrlSigningKey, PASSWORD_CHAR, new X509Certificate[]{ocspCheckedGoodNoUrlCertificate, issuerCertificate}); createTemporaryKeyStoreFile(ocspCheckedGoodNoUrlKeyStore, OCSP_CHECKED_GOOD_NO_URL_FILE, PASSWORD_CHAR); // Generates REVOKED certificate referencing the OCSP responder KeyPair ocspCheckedRevokedKeys = keyPairGenerator.generateKeyPair(); PrivateKey ocspCheckedRevokedSigningKey = ocspCheckedRevokedKeys.getPrivate(); PublicKey ocspCheckedRevokedPublicKey = ocspCheckedRevokedKeys.getPublic(); ocspCheckedRevokedCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ocspCheckedRevokedPublicKey) .setSerialNumber(new BigInteger("17")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .addExtension(new AuthorityInformationAccessExtension(Collections.singletonList( new AccessDescription(OID_AD_OCSP, new GeneralName.URIName(OCSP_RESPONDER_URL)) ))) .build(); ocspCheckedRevokedKeyStore = createKeyStore(); ocspCheckedRevokedKeyStore.setCertificateEntry("ca", issuerCertificate); ocspCheckedRevokedKeyStore.setKeyEntry("localhost", ocspCheckedRevokedSigningKey, PASSWORD_CHAR, new X509Certificate[]{ocspCheckedRevokedCertificate, issuerCertificate}); createTemporaryKeyStoreFile(ocspCheckedRevokedKeyStore, OCSP_CHECKED_REVOKED_FILE, PASSWORD_CHAR); // Generates UNKNOWN certificate referencing the OCSP responder KeyPair ocspCheckedUnknownKeys = keyPairGenerator.generateKeyPair(); PrivateKey ocspCheckedUnknownSigningKey = ocspCheckedUnknownKeys.getPrivate(); PublicKey ocspCheckedUnknownPublicKey = ocspCheckedUnknownKeys.getPublic(); X509Certificate ocspCheckedUnknownCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=ocspCheckedUnknown")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(ocspCheckedUnknownPublicKey) .setSerialNumber(new BigInteger("18")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .addExtension(new AuthorityInformationAccessExtension(Collections.singletonList( new AccessDescription(OID_AD_OCSP, new GeneralName.URIName(OCSP_RESPONDER_URL)) ))) .build(); ocspCheckedUnknownKeyStore = createKeyStore(); ocspCheckedUnknownKeyStore.setCertificateEntry("ca", issuerCertificate); ocspCheckedUnknownKeyStore.setKeyEntry("localhost", ocspCheckedUnknownSigningKey, PASSWORD_CHAR, new X509Certificate[]{ocspCheckedUnknownCertificate, issuerCertificate}); createTemporaryKeyStoreFile(ocspCheckedUnknownKeyStore, OCSP_CHECKED_UNKNOWN_FILE, PASSWORD_CHAR); // Generates the intermediate issuer certificate KeyPair intermediateIssuerKeys = keyPairGenerator.generateKeyPair(); PrivateKey intermediateIssuerSigningKey = intermediateIssuerKeys.getPrivate(); PublicKey intermediateIssuerPublicKey = intermediateIssuerKeys.getPublic(); intermediateIssuerCertificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(intermediateIssuerDN) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) .setPublicKey(intermediateIssuerPublicKey) .setSerialNumber(new BigInteger("6")) .addExtension(new BasicConstraintsExtension(false, true, -1)) .addExtension(new AuthorityInformationAccessExtension(Collections.singletonList( new AccessDescription(OID_AD_OCSP, new GeneralName.URIName(OCSP_RESPONDER_URL)) ))) .build(); // Generates GOOD certificate with more intermediate certificates referencing the OCSP responder KeyPair ocspCheckedTooLongChainKeys = keyPairGenerator.generateKeyPair(); PrivateKey ocspCheckedTooLongChainSigningKey = ocspCheckedTooLongChainKeys.getPrivate(); PublicKey ocspCheckedTooLongChainPublicKey = ocspCheckedTooLongChainKeys.getPublic(); ocspCheckedTooLongChainCertificate = new X509CertificateBuilder() .setIssuerDn(intermediateIssuerDN) .setSubjectDn(new X500Principal("OU=Elytron, O=Elytron, C=UK, ST=Elytron, CN=localhost")) .setSignatureAlgorithmName("SHA256withRSA") .setSigningKey(intermediateIssuerSigningKey) .setPublicKey(ocspCheckedTooLongChainPublicKey) .setSerialNumber(new BigInteger("20")) .addExtension(new BasicConstraintsExtension(false, false, -1)) .addExtension(new AuthorityInformationAccessExtension(Collections.singletonList( new AccessDescription(OID_AD_OCSP, new GeneralName.URIName(OCSP_RESPONDER_URL)) ))).build(); ocspCheckedTooLongChainKeyStore = createKeyStore(); ocspCheckedTooLongChainKeyStore.setCertificateEntry("ca", issuerCertificate); ocspCheckedTooLongChainKeyStore.setCertificateEntry("ca2", intermediateIssuerCertificate); ocspCheckedTooLongChainKeyStore.setKeyEntry("localhost", ocspCheckedTooLongChainSigningKey, PASSWORD_CHAR, new X509Certificate[]{ocspCheckedTooLongChainCertificate, intermediateIssuerCertificate, issuerCertificate}); createTemporaryKeyStoreFile(ocspCheckedTooLongChainKeyStore, OCSP_CHECKED_TOO_LONG_CHAIN_FILE, PASSWORD_CHAR); prepareCrlFiles(intermediateIssuerCertificate, issuerSelfSignedX509CertificateAndSigningKey); // Create the temporary files createTemporaryKeyStoreFile(ladybirdKeyStore, LADYBIRD_FILE, PASSWORD_CHAR); createTemporaryKeyStoreFile(trustStore, TRUST_FILE, PASSWORD_CHAR); // trust file for server config } public static void startOcspServer() throws Exception { ocspServer = new TestingOcspServer(OCSP_PORT); ocspServer.createIssuer(1, issuerCertificate); ocspServer.createIssuer(2, intermediateIssuerCertificate); ocspServer.createCertificate(3, 1, intermediateIssuerCertificate); ocspServer.createCertificate(1, 1, ocspCheckedGoodCertificate); ocspServer.createCertificate(2, 1, ocspCheckedRevokedCertificate); ocspServer.revokeCertificate(2, 4); ocspServer.createCertificate(3, 2, ocspCheckedTooLongChainCertificate); ocspServer.createCertificate(4, 1, ocspCheckedGoodNoUrlCertificate); ocspServer.start(); } private static void prepareCrlFiles(X509Certificate intermediateIssuerCertificate, SelfSignedX509CertificateAndSigningKey issuerSelfSignedX509CertificateAndSigningKey) throws Exception { // Used for all CRLs Calendar calendar = Calendar.getInstance(); Date currentDate = calendar.getTime(); calendar.add(Calendar.YEAR, 1); Date nextYear = calendar.getTime(); calendar.add(Calendar.YEAR, -1); calendar.add(Calendar.SECOND, -30); // Creates the CRL for ca/crl/blank.pem X509v2CRLBuilder caBlankCrlBuilder = new X509v2CRLBuilder( convertSunStyleToBCStyle(intermediateIssuerCertificate.getIssuerDN()), currentDate ); X509CRLHolder caBlankCrlHolder = caBlankCrlBuilder.setNextUpdate(nextYear).build( new JcaContentSignerBuilder("SHA256withRSA") .setProvider("BC") .build(issuerSelfSignedX509CertificateAndSigningKey.getSigningKey()) ); PemWriter caBlankCrlOutput = new PemWriter(new OutputStreamWriter(new FileOutputStream(CA_BLANK_PEM_CRL))); caBlankCrlOutput.writeObject(new MiscPEMGenerator(caBlankCrlHolder)); caBlankCrlOutput.close(); } public static void stopOcspServer() throws Exception { if (ocspServer != null) { ocspServer.stop(); } } public static void afterTest() { Assert.assertTrue(LADYBIRD_FILE.delete()); Assert.assertTrue(OCSP_RESPONDER_FILE.delete()); Assert.assertTrue(OCSP_CHECKED_GOOD_FILE.delete()); Assert.assertTrue(OCSP_CHECKED_GOOD_NO_URL_FILE.delete()); Assert.assertTrue(OCSP_CHECKED_REVOKED_FILE.delete()); Assert.assertTrue(OCSP_CHECKED_UNKNOWN_FILE.delete()); Assert.assertTrue(OCSP_CHECKED_TOO_LONG_CHAIN_FILE.delete()); Assert.assertTrue(TRUST_FILE.delete()); Assert.assertTrue(WORKING_DIR_CA.delete()); Assert.assertTrue(CA_BLANK_PEM_CRL.delete()); Assert.assertTrue(WORKING_DIR_CACRL.delete()); } /** * Server setup task that configures OCSP and related dependencies but OCSP responder is not started. */ static class OcspResponderDownServerSetup extends AbstractElytronSetupTask { @Override protected void setup(ModelControllerClient modelControllerClient) throws Exception { OcspTestBase.beforeTest(); super.setup(modelControllerClient); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); OcspTestBase.afterTest(); } @Override protected ConfigurableElement[] getConfigurableElements() { return getConfigurableElementsCommon(); } } /** * Server setup task that configures OCSP and related dependencies with also fully functional OCSP responder. */ static class OcspServerSetup extends AbstractElytronSetupTask { @Override protected void setup(ModelControllerClient modelControllerClient) throws Exception { OcspTestBase.beforeTest(); startOcspServer(); super.setup(modelControllerClient); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); stopOcspServer(); OcspTestBase.afterTest(); } @Override protected ConfigurableElement[] getConfigurableElements() { return getConfigurableElementsCommon(); } } /** * Common part of server configuration that is used for OCSP testing. * * @return list of configurable elements that shall be setup on server */ private static ConfigurableElement[] getConfigurableElementsCommon() { LinkedList<ConfigurableElement> elements = new LinkedList<>(); CredentialReference serverKeyStoreCredRef = CredentialReference.builder().withClearText(PASSWORD).build(); CredentialReference ocspResponderKeyStoreCredRef = CredentialReference.builder().withClearText(PASSWORD).build(); // Prepare server key-store and key-manager for server ssl context Path serverKeyStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(LADYBIRD_FILE)).build(); SimpleKeyStore serverKeyStore = SimpleKeyStore.builder().withName("serverKeyStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(serverKeyStorePath).build(); elements.add(serverKeyStore); SimpleKeyManager serverKeyManager = SimpleKeyManager.builder().withName("serverKeyManager").withKeyStore( serverKeyStore.getName()).withCredentialReference(serverKeyStoreCredRef).build(); elements.add(serverKeyManager); // Prepare server trust-store (with OCSP configuration) and related key-manager for server ssl context Path serverTrustStorePath = Path.builder().withPath(CliUtils.asAbsolutePath(TRUST_FILE)).build(); SimpleKeyStore serverTrustStore = SimpleKeyStore.builder().withName("serverTrustStore").withCredentialReference( serverKeyStoreCredRef).withType("JKS").withPath(serverTrustStorePath).build(); elements.add(serverTrustStore); // Add OCSP responder key store Path ocspResponderKeyStorePath = Path.builder().withPath(OCSP_RESPONDER_FILE.getAbsolutePath()).build(); SimpleKeyStore ocspResponderKeyStore = SimpleKeyStore.builder().withName("ocspResponderKeyStore").withCredentialReference( ocspResponderKeyStoreCredRef).withType("JKS").withPath(ocspResponderKeyStorePath).build(); elements.add(ocspResponderKeyStore); Ocsp ocsp = Ocsp.builder() .withPreferCrls(false) .withResponderKeyStore("ocspResponderKeyStore") .withResponderCertificate("ocspResponder").build(); CertificateRevocationList crl = CertificateRevocationList.builder().withPath(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)).build(); SimpleTrustManager serverTrustManager = SimpleTrustManager.builder() .withName("serverTrustManager") .withKeyStore(serverTrustStore.getName()) .withOcsp(ocsp) .withSoftFail(false) .withCrl(crl) .withAlgorithm("PKIX").build(); elements.add(serverTrustManager); // Create final server ssl context with prepared key and trust managers. SimpleServerSslContext serverSslContext = SimpleServerSslContext.builder().withName("serverSslContext").withKeyManagers( serverKeyManager.getName()).withNeedClientAuth(true).withTrustManagers( serverTrustManager.getName()).build(); elements.add(serverSslContext); // Configure created server ssl context for undertow default HTTPS listener. UndertowSslContext undertowSslContext = UndertowSslContext.builder().withHttpsListener("https").withName(serverSslContext.getName()).build(); elements.add(undertowSslContext); return elements.toArray(new ConfigurableElement[]{}); } }
28,356
52.503774
150
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/ocsp/OcspResponderDownTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.certs.ocsp; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CliUtils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.elytron.util.WelcomeContent; /** * Tests to check OCSP feature when no OCSP responder is available. * * @author Jan Stourac <jstourac@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({OcspTestBase.OcspResponderDownServerSetup.class, WelcomeContent.SetupTask.class }) public class OcspResponderDownTestCase extends OcspTestBase { /** * Let's check connection to server using a valid certificate. OCSP responder is disabled; CRL not configured. * Expected behavior: server rejects connection for soft-fail=false variant but accepts connection for * soft-fail=true variant. * * @throws Exception */ @Test public void testOcspGoodResponderDown() throws Exception { setCrl(null); setSoftFail(false); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using a valid certificate. OCSP responder is disabled; CRL configured. * Expected behavior: server rejects connection for soft-fail=false variant but accepts connection for * soft-fail=true variant. * * @throws Exception */ @Test public void testOcspGoodResponderDownCrlActive() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using a revoked certificate. OCSP responder is disabled; CRL not configured. * Expected behavior: server rejects connection for both soft-fail values. * * @throws Exception */ @Test public void testOcspRevokedResponderDown() throws Exception { setCrl(null); setSoftFail(false); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using a revoked certificate. OCSP responder is disabled; CRL configured. * Expected behavior: server rejects connection for both soft-fail values. * * @throws Exception */ @Test public void testOcspRevokedResponderDownCrlActive() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using an unknown certificate. OCSP responder is disabled; CRL not configured. * Expected behavior: server accepts connections for both soft-fail values. * * @throws Exception */ @Test public void testOcspUnknownResponderDown() throws Exception { setCrl(null); setSoftFail(false); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using an unknown certificate. OCSP responder is disabled; CRL configured. * Expected behavior: server accepts connections for both soft-fail values. * * @throws Exception */ @Test public void testOcspUnknownResponderDownCrlActive() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, true); } /** * This deployment is required just so OcspServerSetup task is executed. */ @Deployment protected static WebArchive createDeployment() { return createDeployment("dummy"); } @ArquillianResource protected URL url; protected static WebArchive createDeployment(final String name) { return ShrinkWrap.create(WebArchive.class, name + ".war"); } }
5,936
34.339286
117
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/certs/ocsp/OcspTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.certs.ocsp; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.CliUtils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.integration.elytron.util.WelcomeContent; /** * Tests to check OCSP feature using XiPKI OCSP responder. * * @author Jan Stourac <jstourac@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({OcspTestBase.OcspServerSetup.class, WelcomeContent.SetupTask.class}) public class OcspTestCase extends OcspTestBase { /** * Let's check connection to server using a valid certificate. OCSP responder is active; CRL not configured. * Expected behavior: server accepts connection for both soft-fail values. * * @throws Exception */ @Test public void testOcspGood() throws Exception { setCrl(null); setSoftFail(false); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using a valid certificate. OCSP responder is active; CRL configured. * Expected behavior: server accepts connection for both soft-fail values. * * @throws Exception */ @Test public void testOcspGoodCrlActive() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(ocspCheckedGoodKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using a revoked certificate. OCSP responder is enabled; CRL not configured. * Expected behavior: server rejects connection for both soft-fail values. * * @throws Exception */ @Test public void testOcspRevoked() throws Exception { setCrl(null); setSoftFail(false); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, false); } /** * Let's check connection to server using a revoked certificate. OCSP responder is enabled; CRL configured. * Expected behavior: server rejects connection for both soft-fail values. * * @throws Exception */ @Test public void testOcspRevokedCrlActive() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, false); } /** * Let's check connection to server using an unknown certificate. OCSP responder is enabled; CRL not configured. * Expected behavior: server rejects connection for soft-fail=false but accepts connection for soft-fail=true. * * @throws Exception */ @Test public void testOcspUnknown() throws Exception { setCrl(null); setSoftFail(false); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, false); setSoftFail(true); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using an unknown certificate. OCSP responder is enabled; CRL configured. * Expected behavior: server rejects connection for soft-fail=false but accepts connection for soft-fail=true. * * @throws Exception */ @Test public void testOcspUnknownCrlActive() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, true); setSoftFail(true); testCommon(ocspCheckedUnknownKeyStore, trustStore, PASSWORD, true); } /** * Let's check connection to server using a certificate which has been revoked in OCSP responder, although not in * CRL. Based on the value of 'prefer-crls' we expect server to either reject connection or accept the connection. * Expected behavior: server rejects connection for prefer-crls=false but accepts connection for prefer-crls=true. * * @throws Exception */ @Test public void testOcspPreferCrls() throws Exception { setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); setSoftFail(false); try { setPreferCrls(false); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, false); setPreferCrls(true); testCommon(ocspCheckedRevokedKeyStore, trustStore, PASSWORD, true); } finally { setPreferCrls(null); } } /** * Let's check that OCPS URL attribute is working. Certificate in use doesn't have specified its OCSP URL, we need * to specify it manually in our configuration. If this is not specified, we expect server to reject the connection. * * @throws Exception */ @Test public void testOcspUrl() throws Exception { setCrl(null); setPreferCrls(false); setSoftFail(false); testCommon(ocspCheckedGoodNoUrlKeyStore, trustStore, PASSWORD, false); try { setOcspUrl(OCSP_RESPONDER_URL); testCommon(ocspCheckedGoodNoUrlKeyStore, trustStore, PASSWORD, true); } finally { setOcspUrl(null); setPreferCrls(null); } } /** * Let's check that server respects 'maximum-cert-path' attribute. Use certificate with longer certificate chain * than what is allowed. Expected behavior: with default 'maximum-cert-path' attribute value the server accepts * given client certificate; with more restricted value of 'maximum-cert-path' the request is rejected. * * @throws Exception */ @Test public void testOcspTooLongCertChain() throws Exception { setSoftFail(false); setCrl(null); testCommon(ocspCheckedTooLongChainKeyStore, trustStore, PASSWORD, true); try { setMaxCertChain(1); testCommon(ocspCheckedTooLongChainKeyStore, trustStore, PASSWORD, false); } finally { setMaxCertChain(null); } } /** * Let's check that server respects 'maximum-cert-path' attribute. Use certificate with longer certificate chain * than what is allowed; CRL configured. Expected behavior: with default 'maximum-cert-path' attribute value the * server accepts given client certificate; with more restricted value of 'maximum-cert-path' the request is * rejected. * * @throws Exception */ @Test public void testOcspTooLongCertChainCrlActive() throws Exception { setSoftFail(false); setCrl(CliUtils.asAbsolutePath(CA_BLANK_PEM_CRL)); testCommon(ocspCheckedTooLongChainKeyStore, trustStore, PASSWORD, true); try { setMaxCertChain(1); testCommon(ocspCheckedTooLongChainKeyStore, trustStore, PASSWORD, false); } finally { setMaxCertChain(null); } } /** * This deployment is required just so OcspServerSetup task is executed. */ @Deployment protected static WebArchive createDeployment() { return createDeployment("dummy"); } @ArquillianResource protected URL url; protected static WebArchive createDeployment(final String name) { return ShrinkWrap.create(WebArchive.class, name + ".war"); } }
9,047
34.904762
120
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/web/WebAuthenticationTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.web; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test case to test authentication to web applications, initially programatic authentication. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @RunWith(Arquillian.class) @ServerSetup({ WebAuthenticationTestCaseBase.ElytronDomainSetupOverride.class, ServletElytronDomainSetup.class }) public class WebAuthenticationTestCase extends WebAuthenticationTestCaseBase { @Override protected String getWebXmlName() { return "web.xml"; } }
1,773
38.422222
113
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/web/WebAuthenticationTestCaseBase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.web; import static java.util.concurrent.TimeUnit.SECONDS; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.wildfly.test.integration.elytron.util.HttpUtil.get; import java.io.File; import java.net.SocketPermission; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.wildfly.test.integration.elytron.ejb.AuthenticationTestCase; import org.wildfly.test.integration.elytron.util.HttpUtil; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test case to test authentication to web applications, initially programatic authentication. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ abstract class WebAuthenticationTestCaseBase { @ArquillianResource protected URL url; @Deployment public static Archive<?> deployment() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = AuthenticationTestCase.class.getPackage(); // using JavaArchive doesn't work, because of a bug in Arquillian, it only deploys wars properly return ShrinkWrap.create(WebArchive.class, "websecurity.war") .addClass(LoginServlet.class).addClass(HttpUtil.class) .addClass(WebAuthenticationTestCaseBase.class) .addClasses(ElytronDomainSetup.class, ServletElytronDomainSetup.class) .addAsResource(currentPackage, "users.properties", "users.properties") .addAsResource(currentPackage, "roles.properties", "roles.properties") .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml") .addAsManifestResource(createPermissionsXmlAsset( // AuthenticationTestCase#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // AuthenticationTestCase#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve") ), "permissions.xml"); } protected abstract String getWebXmlName(); @Test public void testProgramaticAuthentication() throws Exception { Map<String, String> headers = Collections.emptyMap(); AtomicReference<String> sessionCookie = new AtomicReference<>(); // Test Unauthenticated Call is 'null' String identity = get(url + "login", headers, 10, SECONDS, sessionCookie); assertEquals("Expected Identity", "null", identity); // Test Call can login and identity established. identity = get(url + "login?action=login&username=user1&password=password1", headers, 10, SECONDS, sessionCookie); assertEquals("Expected Identity", "user1", identity); // Test follow up call still has identity. identity = get(url + "login", headers, 10, SECONDS, sessionCookie); assertEquals("Expected Identity", "user1", identity); // Logout and check back to 'null'. identity = get(url + "login?action=logout", headers, 10, SECONDS, sessionCookie); assertEquals("Expected Identity", "null", identity); // Once more call to be sure we really are null. identity = get(url + "login", headers, 10, SECONDS, sessionCookie); assertEquals("Expected Identity", "null", identity); } static class ElytronDomainSetupOverride extends ElytronDomainSetup { public ElytronDomainSetupOverride() { super(new File(WebAuthenticationTestCase.class.getResource("users.properties").getFile()).getAbsolutePath(), new File(WebAuthenticationTestCase.class.getResource("roles.properties").getFile()).getAbsolutePath()); } } }
5,576
47.077586
123
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/web/ListenerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.web; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ALLOW_RESOURCE_SERVICE_RESTART; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.COMPOSITE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.STEPS; import static org.jboss.as.test.integration.management.util.ModelUtil.createOpNode; import static org.jboss.as.test.integration.security.common.SSLTruststoreUtil.HTTPS_PORT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileOutputStream; import java.net.Socket; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.security.auth.x500.X500Principal; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.http.util.TestHttpClientUtils; import org.jboss.as.test.integration.common.HttpRequest; import org.jboss.as.test.integration.management.Listener; import org.jboss.as.test.integration.management.base.ContainerResourceMgmtTestBase; import org.jboss.as.test.integration.management.util.WebUtil; import org.jboss.as.test.integration.security.common.SecurityTestConstants; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.CredentialReference; import org.wildfly.test.security.common.elytron.Path; import org.wildfly.test.security.common.elytron.SimpleKeyManager; import org.wildfly.test.security.common.elytron.SimpleKeyStore; import org.wildfly.test.security.common.elytron.SimpleServerSslContext; import org.wildfly.test.security.common.elytron.SimpleTrustManager; import io.undertow.util.FileUtils; /** * @author Dominik Pospisil <dpospisi@redhat.com> */ @RunWith(Arquillian.class) @ServerSetup(ListenerTestCase.SslContextSetup.class) @RunAsClient public class ListenerTestCase extends ContainerResourceMgmtTestBase { /** * We use a different socket binding name for each test, as if the socket is still up the service * will not be removed. Rather than adding a sleep we use this approach */ private static int socketBindingCount = 0; @ArquillianResource private URL url; private static final char[] GENERATED_KEYSTORE_PASSWORD = "changeit".toCharArray(); private static final String WORKING_DIRECTORY_LOCATION = "./target/test-classes/security"; private static final String CLIENT_ALIAS = "client"; private static final String CLIENT_2_ALIAS = "client2"; private static final String TEST_ALIAS = "test"; private static final File KEY_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, "server.keystore"); private static final File TRUST_STORE_FILE = new File(WORKING_DIRECTORY_LOCATION, "jsse.keystore"); private static final String TEST_CLIENT_DN = "CN=Test Client, OU=JBoss, O=Red Hat, L=Raleigh, ST=North Carolina, C=US"; private static final String TEST_CLIENT_2_DN = "CN=Test Client 2, OU=JBoss, O=Red Hat, L=Raleigh, ST=North Carolina, C=US"; private static final String AS_7_DN = "CN=AS7, OU=JBoss, O=Red Hat, L=Raleigh, ST=North Carolina, C=US"; private static final String SHA_256_RSA = "SHA256withRSA"; private static final String NAME = ListenerTestCase.class.getSimpleName(); private static KeyStore loadKeyStore() throws Exception{ KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); return ks; } private static SelfSignedX509CertificateAndSigningKey createSelfSigned(String DN) { return SelfSignedX509CertificateAndSigningKey.builder() .setDn(new X500Principal(DN)) .setKeyAlgorithmName("RSA") .setSignatureAlgorithmName(SHA_256_RSA) .build(); } private static void addKeyEntry(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, KeyStore keyStore) throws Exception { X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setKeyEntry(TEST_ALIAS, selfSignedX509CertificateAndSigningKey.getSigningKey(), GENERATED_KEYSTORE_PASSWORD, new X509Certificate[]{certificate}); } private static void addCertEntry(SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey, String alias, KeyStore keyStore) throws Exception { X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setCertificateEntry(alias, certificate); } private static void createTemporaryKeyStoreFile(KeyStore keyStore, File outputFile) throws Exception { try (FileOutputStream fos = new FileOutputStream(outputFile)){ keyStore.store(fos, GENERATED_KEYSTORE_PASSWORD); } } private static void setUpKeyStores() throws Exception { File workingDir = new File(WORKING_DIRECTORY_LOCATION); if (workingDir.exists() == false) { workingDir.mkdirs(); } KeyStore keyStore = loadKeyStore(); KeyStore trustStore = loadKeyStore(); SelfSignedX509CertificateAndSigningKey testClientSelfSignedX509CertificateAndSigningKey = createSelfSigned(TEST_CLIENT_DN); SelfSignedX509CertificateAndSigningKey testClient2SelfSignedX509CertificateAndSigningKey = createSelfSigned(TEST_CLIENT_2_DN); SelfSignedX509CertificateAndSigningKey aS7SelfSignedX509CertificateAndSigningKey = createSelfSigned(AS_7_DN); addCertEntry(testClient2SelfSignedX509CertificateAndSigningKey, CLIENT_2_ALIAS, keyStore); addCertEntry(testClientSelfSignedX509CertificateAndSigningKey, CLIENT_ALIAS, keyStore); addKeyEntry(aS7SelfSignedX509CertificateAndSigningKey, keyStore); addCertEntry(testClient2SelfSignedX509CertificateAndSigningKey, CLIENT_2_ALIAS, trustStore); addCertEntry(testClientSelfSignedX509CertificateAndSigningKey, CLIENT_ALIAS, trustStore); createTemporaryKeyStoreFile(keyStore, KEY_STORE_FILE); createTemporaryKeyStoreFile(trustStore, TRUST_STORE_FILE); } private static void deleteKeyStoreFiles() { File[] testFiles = { KEY_STORE_FILE, TRUST_STORE_FILE }; for (File file : testFiles) { if (file.exists()) { file.delete(); } } } @AfterClass public static void afterTests() { deleteKeyStoreFiles(); } @Deployment public static Archive<?> getDeployment() { WebArchive ja = ShrinkWrap.create(WebArchive.class, "proxy.war"); ja.addClasses(ListenerTestCase.class, RemoteIpServlet.class); return ja; } @Test public void testDefaultConnectorList() throws Exception { // only http connector present as a default Map<String, Set<String>> listeners = getListenerList(); Set<String> listenerNames = listeners.get("http"); assertEquals(1, listenerNames.size()); assertTrue("HTTP connector missing.", listenerNames.contains("default")); } @Test public void testHttpConnector() throws Exception { addListener(Listener.HTTP); // check that the connector is live String cURL = "http://" + url.getHost() + ":8181"; String response = HttpRequest.get(cURL, 10, TimeUnit.SECONDS); assertTrue("Invalid response: " + response, response.indexOf("JBoss") >= 0); removeListener(Listener.HTTP, 5000); } @Test public void testHttpsConnector() throws Exception { addListener(Listener.HTTPS); // check that the connector is live try (CloseableHttpClient httpClient = TestHttpClientUtils.getHttpsClient(null)){ String cURL = "https://" + url.getHost() + ":8181"; HttpGet get = new HttpGet(cURL); HttpResponse hr = httpClient.execute(get); String response = EntityUtils.toString(hr.getEntity()); assertTrue("Invalid response: " + response, response.indexOf("JBoss") >= 0); } finally { removeListener(Listener.HTTPS); } } @Test public void testAjpConnector() throws Exception { addListener(Listener.AJP); removeListener(Listener.AJP); } @Test public void testAddAndRemoveRollbacks() throws Exception { // execute and rollback add socket ModelNode addSocketOp = getAddSocketBindingOp(Listener.HTTP); ModelNode ret = executeAndRollbackOperation(addSocketOp); assertTrue("failed".equals(ret.get("outcome").asString())); // add socket again executeOperation(addSocketOp); // execute and rollback add connector ModelNode addConnectorOp = getAddListenerOp(Listener.HTTP, false); ret = executeAndRollbackOperation(addConnectorOp); assertTrue("failed".equals(ret.get("outcome").asString())); // add connector again executeOperation(addConnectorOp); // check it is listed assertTrue(getListenerList().get("http").contains("test-" + Listener.HTTP.getName() + "-listener")); // execute and rollback remove connector ModelNode removeConnOp = getRemoveConnectorOp(Listener.HTTP); ret = executeAndRollbackOperation(removeConnOp); assertEquals("failed", ret.get("outcome").asString()); // execute remove connector again executeOperation(removeConnOp); Thread.sleep(1000); // check that the connector is not live String cURL = Listener.HTTP.getScheme() + "://" + url.getHost() + ":8181"; assertFalse("Connector not removed.", WebUtil.testHttpURL(cURL)); // execute and rollback remove socket binding ModelNode removeSocketOp = getRemoveSocketBindingOp(Listener.HTTP); ret = executeAndRollbackOperation(removeSocketOp); assertEquals("failed", ret.get("outcome").asString()); // execute remove socket again executeOperation(removeSocketOp); } @Test public void testProxyProtocolOverHTTP() throws Exception { addListener(Listener.HTTP, true); try (Socket s = new Socket(url.getHost(), 8181)) { s.getOutputStream().write("PROXY TCP4 1.2.3.4 5.6.7.8 444 555\r\nGET /proxy/addr HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); String result = FileUtils.readFile(s.getInputStream()); Assert.assertTrue(result, result.contains("result:1.2.3.4:444 5.6.7.8:555")); } finally { removeListener(Listener.HTTP); } } @Test public void testProxyProtocolOverHTTPS() throws Exception { addListener(Listener.HTTPS, true); try (Socket s = new Socket(url.getHost(), 8181)) { s.getOutputStream().write("PROXY TCP4 1.2.3.4 5.6.7.8 444 555\r\n".getBytes(StandardCharsets.US_ASCII)); Socket ssl = TestHttpClientUtils.getSslContext().getSocketFactory().createSocket(s, url.getHost(), HTTPS_PORT, true); ssl.getOutputStream().write("GET /proxy/addr HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); String result = FileUtils.readFile(ssl.getInputStream()); Assert.assertTrue(result, result.contains("result:1.2.3.4:444 5.6.7.8:555")); } finally { removeListener(Listener.HTTPS); } } private void addListener(Listener conn) throws Exception { addListener(conn, false); } private void addListener(Listener conn, boolean proxyProtocol) throws Exception { // add socket binding ModelNode op = getAddSocketBindingOp(conn); executeOperation(op); // add connector op = getAddListenerOp(conn, proxyProtocol); executeOperation(op); // check it is listed assertTrue(getListenerList().get(conn.getScheme()).contains("test-" + conn.getName() + "-listener")); } private ModelNode getAddSocketBindingOp(Listener conn) { ModelNode op = createOpNode("socket-binding-group=standard-sockets/socket-binding=test-" + conn.getName() + (++socketBindingCount), "add"); op.get("port").set(8181); return op; } private ModelNode getAddListenerOp(Listener conn, boolean proxyProtocol) { final ModelNode composite = Util.getEmptyOperation(COMPOSITE, new ModelNode()); final ModelNode steps = composite.get(STEPS); ModelNode op = createOpNode("subsystem=undertow/server=default-server/" + conn.getScheme() + "-listener=test-" + conn.getName() + "-listener", "add"); op.get("socket-binding").set("test-" + conn.getName() + socketBindingCount); if(proxyProtocol) { op.get("proxy-protocol").set(true); } if (conn.isSecure()) { op.get("ssl-context").set(NAME); } steps.add(op); return composite; } private void removeListener(Listener conn) throws Exception { removeListener(conn, 300); } private void removeListener(Listener conn, int delay) throws Exception { // remove connector ModelNode op = getRemoveConnectorOp(conn); executeOperation(op); Thread.sleep(delay); // check that the connector is not live String cURL = conn.getScheme() + "://" + url.getHost() + ":8181"; assertFalse("Listener not removed.", WebUtil.testHttpURL(cURL)); // remove socket binding op = getRemoveSocketBindingOp(conn); executeOperation(op); } private ModelNode getRemoveSocketBindingOp(Listener conn) { return createOpNode("socket-binding-group=standard-sockets/socket-binding=test-" + conn.getName() + socketBindingCount, "remove"); } private ModelNode getRemoveConnectorOp(Listener conn) { ModelNode op = createOpNode("subsystem=undertow/server=default-server/" + conn.getScheme() + "-listener=test-" + conn.getName() + "-listener", "remove"); op.get(OPERATION_HEADERS, ALLOW_RESOURCE_SERVICE_RESTART).set(true); return op; } private Map<String, Set<String>> getListenerList() throws Exception { HashMap<String, Set<String>> result = new HashMap<>(); result.put("http", getListenersByType("http-listener")); result.put("https", getListenersByType("https-listener")); result.put("ajp", getListenersByType("ajp-listener")); return result; } private Set<String> getListenersByType(String type) throws Exception { ModelNode op = createOpNode("subsystem=undertow/server=default-server", "read-children-names"); op.get("child-type").set(type); ModelNode result = executeOperation(op); List<ModelNode> connectors = result.asList(); HashSet<String> connNames = new HashSet<>(); for (ModelNode n : connectors) { connNames.add(n.asString()); } return connNames; } static class SslContextSetup extends AbstractElytronSetupTask { @Override protected void setup(final ModelControllerClient modelControllerClient) throws Exception { setUpKeyStores(); super.setup(modelControllerClient); } @Override protected ConfigurableElement[] getConfigurableElements() { URL keystoreResource = Thread.currentThread().getContextClassLoader().getResource("security/server.keystore"); URL truststoreResource = Thread.currentThread().getContextClassLoader().getResource("security/jsse.keystore"); return new ConfigurableElement[] { SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_KEYSTORE) .withPath(Path.builder().withPath(keystoreResource.getPath()).build()) .withCredentialReference(CredentialReference.builder().withClearText("changeit").build()) .build(), SimpleKeyStore.builder().withName(NAME + SecurityTestConstants.SERVER_TRUSTSTORE) .withPath(Path.builder().withPath(truststoreResource.getPath()).build()) .withCredentialReference(CredentialReference.builder().withClearText("changeit").build()) .build(), SimpleKeyManager.builder().withName(NAME) .withKeyStore(NAME + SecurityTestConstants.SERVER_KEYSTORE) .withCredentialReference(CredentialReference.builder().withClearText("changeit").build()) .build(), SimpleTrustManager.builder().withName(NAME) .withKeyStore(NAME + SecurityTestConstants.SERVER_TRUSTSTORE) .build(), SimpleServerSslContext.builder().withName(NAME) .withKeyManagers(NAME) .withTrustManagers(NAME) .build(), }; } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); } } }
19,584
42.233996
167
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/web/LoginServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.web; import static org.wildfly.common.Assert.checkNotNullParam; import java.io.IOException; import java.io.Writer; import java.security.Principal; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A simple servlet to test programatic authentication. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @WebServlet(urlPatterns = "/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 7207484039745630987L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = (String) req.getParameter("action"); System.out.println("Action = " + action); if (action != null) { switch (action) { case "login": String username = checkNotNullParam("username", (String) req.getParameter("username")); String password = checkNotNullParam("password", (String) req.getParameter("password")); System.out.println("username = " + username + " password = " + password); req.login(username, password); break; case "logout": req.logout(); break; } } Writer writer = resp.getWriter(); Principal principal = req.getUserPrincipal(); writer.write(principal != null ? principal.getName() : "null"); } }
2,759
38.428571
113
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/web/MinimalWebAuthenticationTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.web; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ServerSetup; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test case to test authentication to web applications using programatic authentication. * * This test uses an application security-domain mapping to a security domain instead of an authentication factory. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @RunWith(Arquillian.class) @ServerSetup({ WebAuthenticationTestCaseBase.ElytronDomainSetupOverride.class, MinimalWebAuthenticationTestCase.ElytronServletSetupOverride.class }) public class MinimalWebAuthenticationTestCase extends WebAuthenticationTestCaseBase { @Override protected String getWebXmlName() { return "minimal-web.xml"; } public static class ElytronServletSetupOverride extends ServletElytronDomainSetup { @Override protected boolean useAuthenticationFactory() { return false; } } }
2,143
37.285714
148
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/web/RemoteIpServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.web; import java.io.IOException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/addr") public class RemoteIpServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("result:" + req.getRemoteAddr() + ":" + req.getRemotePort() + " " + req.getLocalAddr() + ":" + req.getLocalPort()); } }
1,700
41.525
147
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/JdbcTestServlet.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import java.util.Map.Entry; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.authz.Attributes; /** * A simple servlet that just writes back a string. * */ @WebServlet(urlPatterns = { JdbcTestServlet.SERVLET_PATH }) public class JdbcTestServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String SERVLET_PATH = "/test"; /** The String returned in the HTTP response body. */ public static final String RESPONSE_BODY = "GOOD"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); final PrintWriter writer = resp.getWriter(); Map<String, String[]> parameters = req.getParameterMap(); SecurityDomain securityDomain = SecurityDomain.getCurrent(); SecurityIdentity securityIdentity = securityDomain.getCurrentSecurityIdentity(); Attributes attributes = securityIdentity.getAttributes(); for (Entry<String, String[]> entry : parameters.entrySet()) { for (String value : entry.getValue()) { if (attributes.containsValue(entry.getKey(), value) == false) { writer.write(String.format("Attribute %s with value %s missing from the Attributes associated with the current SecurityIdentity.", entry.getKey(), value)); writer.close(); return; } } } writer.write(RESPONSE_BODY); writer.close(); } }
2,615
33.88
175
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/DistributedRealmTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.jboss.as.test.integration.security.common.Utils.makeCallWithTokenAuthn; import static org.jboss.as.test.shared.CliUtils.asAbsolutePath; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.PrintWriter; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Base64; import java.util.Base64.Encoder; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.DirContext; import org.wildfly.test.security.common.elytron.DistributedRealm; import org.wildfly.test.security.common.elytron.FileAuditLog; import org.wildfly.test.security.common.elytron.LdapRealm; import org.wildfly.test.security.common.elytron.MechanismConfiguration; import org.wildfly.test.security.common.elytron.PropertiesRealm; import org.wildfly.test.security.common.elytron.SimpleHttpAuthenticationFactory; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.TokenRealm; import org.wildfly.test.security.common.elytron.UserWithAttributeValues; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Tests the {@link DistributedRealm} within the Elytron subsystem. The tests cover both the credential and evidence * based authn, trying all identities distributed among the realms backing a distributed-realm by invoking deployed applications. * * For the credential based authn testing, there are three properties-realm containing identities with corresponding numbers. * For the evidence based authn testing, there are two JWT token-realm that differ in accepted issuers. * To test the ability to distinguish between the authn types, these realms are mixed into one distributed-realm * that backs secured deployments for both the authn types testing (BASIC and BEARER_TOKEN methods are used). * * To test the behavior when a realm is not available, there is also a deployment backed by a distributed-realm with * an unavailable LDAP realm among the properties-realm. * * @author Ondrej Kotek */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({DistributedRealmTestCase.ServerSetup.class}) public class DistributedRealmTestCase { private static final String DEPLOYMENT_FOR_CREDENTIALS = "DistributedRealmDeployment-Credentials"; private static final String DEPLOYMENT_FOR_EVIDENCE = "DistributedRealmDeployment-Evidence"; private static final String DEPLOYMENT_FOR_UNAVAILABLE_REALM = "DistributedRealmDeployment-UnavailableRealm"; private static final String DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_FALSE = "DistributedRealmDeployment-IgnoreUnavailableRealmFalse"; private static final String DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM = "DistributedRealmDeployment-IgnoreUnavailableRealm"; private static final String DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_DISABLED = "DistributedRealmDeployment-IgnoreUnavailableRealmDisabled"; private static final String INDEX_PAGE_CONTENT = "index page content"; private static final String SECURITY_REALM_UNAVAILABLE_EVENT = "SecurityRealmUnavailableEvent"; private static final Encoder B64_ENCODER = Base64.getUrlEncoder().withoutPadding(); private static final String JWT_HEADER_B64 = B64_ENCODER .encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8)); private static final String JWT_ISSUER_1 = "issuer1.wildfly.org"; private static final String JWT_ISSUER_2 = "issuer2.wildfly.org"; private static final File AUDIT_LOG_FILE = Paths.get("target", DistributedRealmTestCase.class.getSimpleName() + "-test-audit.log").toFile(); @Deployment(name = DEPLOYMENT_FOR_CREDENTIALS) public static WebArchive deployment() { return deployment(DEPLOYMENT_FOR_CREDENTIALS, "distributed-realm-web.xml"); } @Deployment(name = DEPLOYMENT_FOR_EVIDENCE) public static WebArchive deploymentForEvidence() { return deployment(DEPLOYMENT_FOR_EVIDENCE, "distributed-realm-bearer-token-web.xml"); } @Deployment(name = DEPLOYMENT_FOR_UNAVAILABLE_REALM) public static WebArchive deploymentForUnavailableRealm() { return deployment(DEPLOYMENT_FOR_UNAVAILABLE_REALM, "distributed-realm-web.xml"); } @Deployment(name = DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_FALSE) public static WebArchive deploymentForIgnoreUnavailableRealmFalse() { return deployment(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_FALSE, "distributed-realm-web.xml"); } @Deployment(name = DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM) public static WebArchive deploymentForIgnoreUnavailableRealm() { return deployment(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM, "distributed-realm-web.xml"); } @Deployment(name = DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_DISABLED) public static WebArchive deploymentForIgnoreUnavailableRealmDisabled() { return deployment(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_DISABLED, "distributed-realm-web.xml"); } private static WebArchive deployment(String name, String webXml) { final WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war"); war.add(new StringAsset(INDEX_PAGE_CONTENT), "index.html"); war.addAsWebInfResource(DistributedRealmTestCase.class.getPackage(), webXml, "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(name), "jboss-web.xml"); return war; } @Test @OperateOnDeployment(DEPLOYMENT_FOR_CREDENTIALS) public void testIdentityPerRealm_Success(@ArquillianResource URL webAppUrl) throws Exception { String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user2", "password2", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user3", "password3", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_CREDENTIALS) public void testIdentityPerRealm_WrongPassword(@ArquillianResource URL webAppUrl) throws Exception { String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "wrongPassword1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user2", "wrongPassword2", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user3", "wrongPassword3", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_CREDENTIALS) public void testWrongUserName(@ArquillianResource URL webAppUrl) throws Exception { String result = Utils.makeCallWithBasicAuthn(webAppUrl, "non-existing-user1", "password1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_CREDENTIALS) public void testIdentityInTwoRealms_FirstRealmUsed(@ArquillianResource URL webAppUrl) throws Exception { String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user12", "passwordInRealm1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user12", "passwordInRealm2", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_UNAVAILABLE_REALM) public void testIdentityPerRealm_UnavailableRealm(@ArquillianResource URL webAppUrl) throws Exception { // user1 and user2 are in the realms that are before the unavailable realm String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user2", "password2", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); // user3 is in the realm that is after the unavailable realm result = Utils.makeCallWithBasicAuthn(webAppUrl, "user3", "password3", SC_INTERNAL_SERVER_ERROR); assertNotEquals(INDEX_PAGE_CONTENT, result); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_FALSE) public void testIdentityPerRealm_UnavailableRealmFalse(@ArquillianResource URL webAppUrl) throws Exception { // user1 and user2 are in the realms that are before the unavailable realm String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user2", "password2", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); // user3 is in the realm that is after the unavailable realm result = Utils.makeCallWithBasicAuthn(webAppUrl, "user3", "password3", SC_INTERNAL_SERVER_ERROR); assertNotEquals(INDEX_PAGE_CONTENT, result); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM) public void testIdentityPerRealm_IgnoreUnavailableRealm(@ArquillianResource URL webAppUrl) throws Exception { // user1 and user2 are in the realms that are before the unavailable realm String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user2", "password2", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); cleanAuditLog(); // user3 is in the realm that is after the unavailable realm result = Utils.makeCallWithBasicAuthn(webAppUrl, "user3", "password3", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged("unavailable_ldap_realm")); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_DISABLED) public void testIdentityPerRealm_IgnoreUnavailableRealmDisabled(@ArquillianResource URL webAppUrl) throws Exception { // user1 and user2 are in the realms that are before the unavailable realm String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user2", "password2", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); cleanAuditLog(); // user3 is in the realm that is after the unavailable realm result = Utils.makeCallWithBasicAuthn(webAppUrl, "user3", "password3", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); assertFalse("SecurityRealmUnavailableEvent should not be logged", isSecurityRealmUnavailableEventLogged("unavailable_ldap_realm")); } @Test @OperateOnDeployment(DEPLOYMENT_FOR_EVIDENCE) public void testIdentityPerRealm_Evidence(@ArquillianResource URL webAppUrl) throws Exception { String result = makeCallWithTokenAuthn(webAppUrl, createJwtToken("userA", JWT_ISSUER_1), SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = makeCallWithTokenAuthn(webAppUrl, createJwtToken("userB", JWT_ISSUER_2), SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); result = makeCallWithTokenAuthn(webAppUrl, createJwtToken("userC", "unknown_issuer"), SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); } private String createJwtToken(String userName, String issuer) { String jwtPayload = String.format("{" // + "\"iss\": \"%1$s\"," // + "\"sub\": \"elytron@wildfly.org\"," // + "\"exp\": 2051222399," // + "\"aud\": \"%1$s\"," // + "\"groups\": [\"%2$s\"]" // + "}", issuer, userName); return JWT_HEADER_B64 + "." + B64_ENCODER.encodeToString(jwtPayload.getBytes(StandardCharsets.UTF_8)) + "."; } private static boolean isSecurityRealmUnavailableEventLogged(String realmName) throws Exception { List<String> lines = Files.readAllLines(AUDIT_LOG_FILE.toPath(), StandardCharsets.UTF_8); for (String line : lines) { if (line.contains(SECURITY_REALM_UNAVAILABLE_EVENT) && line.contains(realmName)) { return true; } } return false; } private static void cleanAuditLog() throws Exception { try (PrintWriter writer = new PrintWriter(AUDIT_LOG_FILE)) { writer.print(""); } } static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); // this audit log is checked for presence of SecurityRealmUnavailableEvent configurableElements.add(FileAuditLog.builder() .withName("audit_log_for_distributed_realm") .withPath(asAbsolutePath(AUDIT_LOG_FILE)) .build()); // properties-realm for credential based authn, used by all distributed-realm configurableElements.add(PropertiesRealm.builder() .withName("properties_realm_1") .withUser(UserWithAttributeValues.builder() .withName("user1") .withPassword("password1") .withValues("user") .build()) .withUser(UserWithAttributeValues.builder() .withName("user12") .withPassword("passwordInRealm1") .withValues("user") .build()) .build()); configurableElements.add(PropertiesRealm.builder() .withName("properties_realm_2") .withUser(UserWithAttributeValues.builder() .withName("user2") .withPassword("password2") .withValues("user") .build()) .withUser(UserWithAttributeValues.builder() .withName("user12") .withPassword("passwordInRealm2") .withValues("user") .build()) .build()); configurableElements.add(PropertiesRealm.builder() .withName("properties_realm_3") .withUser(UserWithAttributeValues.builder() .withName("user3") .withPassword("password3") .withValues("user") .build()) .build()); // token-realm for evidence based authn, differ just in accepted JWT issuers configurableElements.add(TokenRealm.builder("token_realm1") .withJwt(TokenRealm.jwtBuilder().withIssuer(JWT_ISSUER_1).build()) .withPrincipalClaim("aud") .build()); configurableElements.add(TokenRealm.builder("token_realm2") .withJwt(TokenRealm.jwtBuilder().withIssuer(JWT_ISSUER_2).build()) .withPrincipalClaim("aud") .build()); // the credential and evidence based realms are mixed into one distributed-realm that is used for both the authn types configurableElements.add(DistributedRealm.builder("distributed_realm") .withRealms("properties_realm_1", "token_realm1", "properties_realm_2", "token_realm2", "properties_realm_3") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("distributed_realm_domain") .withDefaultRealm("distributed_realm") .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("distributed_realm") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FOR_CREDENTIALS) .withSecurityDomain("distributed_realm_domain") .build()); configurableElements.add(SimpleHttpAuthenticationFactory.builder() .withName(DEPLOYMENT_FOR_EVIDENCE) .withHttpServerMechanismFactory("global") .withSecurityDomain("distributed_realm_domain") .addMechanismConfiguration(MechanismConfiguration.builder() .withMechanismName("BEARER_TOKEN") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FOR_EVIDENCE) .httpAuthenticationFactory(DEPLOYMENT_FOR_EVIDENCE) .build()); // a deployment backed by a distributed-realm with an unavailable ldap-realm (RealmUnavailableException) configurableElements.add(DirContext.builder("unavailable_dir_context") .withUrl("invalid_url") .build()); configurableElements.add(LdapRealm.builder("unavailable_ldap_realm") .withDirContext("unavailable_dir_context") .withIdentityMapping(LdapRealm.identityMappingBuilder() .withRdnIdentifier("invalid") .build()) .build()); configurableElements.add(DistributedRealm.builder("distributed_realm_with_unavailable_realm") .withRealms("properties_realm_1", "properties_realm_2", "unavailable_ldap_realm", "properties_realm_3") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("distributed_realm_domain_with_unavailable_realm") .withDefaultRealm("distributed_realm_with_unavailable_realm") .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("distributed_realm_with_unavailable_realm") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FOR_UNAVAILABLE_REALM) .withSecurityDomain("distributed_realm_domain_with_unavailable_realm") .build()); // a deployment backed by a distributed-realm with an unavailable ldap-realm (RealmUnavailableException), ignore set to false configurableElements.add(DistributedRealm.builder("distributed_realm_with_ignore_unavailable_realm_false") .withRealms("properties_realm_1", "properties_realm_2", "unavailable_ldap_realm", "properties_realm_3") .withIgnoreUnavailableRealms(false) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("distributed_realm_domain_with_ignore_unavailable_realm_false") .withDefaultRealm("distributed_realm_with_ignore_unavailable_realm_false") .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("distributed_realm_with_ignore_unavailable_realm_false") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_FALSE) .withSecurityDomain("distributed_realm_domain_with_ignore_unavailable_realm_false") .build()); // a deployment backed by a distributed-realm with an unavailable ldap-realm (RealmUnavailableException), ignore set to true, emiting enabled configurableElements.add(DistributedRealm.builder("distributed_realm_with_ignore_unavailable_realm") .withRealms("properties_realm_1", "properties_realm_2", "unavailable_ldap_realm", "properties_realm_3") .withIgnoreUnavailableRealms(true) .withEmitEvents(true) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("distributed_realm_domain_with_ignore_unavailable_realm") .withDefaultRealm("distributed_realm_with_ignore_unavailable_realm") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_distributed_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("distributed_realm_with_ignore_unavailable_realm") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM) .withSecurityDomain("distributed_realm_domain_with_ignore_unavailable_realm") .build()); // a deployment backed by a distributed-realm with an unavailable ldap-realm (RealmUnavailableException), ignore set to true, emiting disabled configurableElements.add(DistributedRealm.builder("distributed_realm_with_ignore_unavailable_realm_disabled") .withRealms("properties_realm_1", "properties_realm_2", "unavailable_ldap_realm", "properties_realm_3") .withIgnoreUnavailableRealms(true) .withEmitEvents(false) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("distributed_realm_domain_with_ignore_unavailable_realm_disabled") .withDefaultRealm("distributed_realm_with_ignore_unavailable_realm_disabled") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_distributed_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("distributed_realm_with_ignore_unavailable_realm_disabled") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FOR_IGNORE_UNAVAILABLE_REALM_DISABLED) .withSecurityDomain("distributed_realm_domain_with_ignore_unavailable_realm_disabled") .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); Files.deleteIfExists(AUDIT_LOG_FILE.toPath()); } } }
26,331
54.203354
154
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/PropertiesRealmTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import java.net.MalformedURLException; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Full authentication tests for Elytron Property realm using hash encoding and * hash charsets. * * @author Sonia Zaldana Calles <szaldana@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({PropertiesRealmTestCase.SetUpTask.class}) public class PropertiesRealmTestCase { private static final String DEPLOYMENT_ENCODED = "propRealmEncoded"; private static final String DEPLOYMENT_WITH_CHARSET_ENCODED = "propRealmEncodedCharset"; private static final String USER_ENCODED = "elytron"; private static final String USER_WITH_CHARSET_ENCODED = "elytron4"; private static final String CHARSET_PASSWORD = "password密码"; private static final String ENCODED_PASSWORD = "passwd12#$"; @Deployment(name = DEPLOYMENT_ENCODED) public static WebArchive deploymentWithCharset() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_ENCODED + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(PropertiesRealmTestCase.class.getPackage(), "property-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_ENCODED), "jboss-web.xml"); return war; } @Deployment(name = DEPLOYMENT_WITH_CHARSET_ENCODED) public static WebArchive deploymentWithCharsetAndEncoded() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_WITH_CHARSET_ENCODED + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(PropertiesRealmTestCase.class.getPackage(), "property-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_WITH_CHARSET_ENCODED), "jboss-web.xml"); return war; } /** * * Test Properties realm correctly handles a password using a different character set than * UTF-8 when converting the password string to a byte array. */ @Test @OperateOnDeployment(DEPLOYMENT_ENCODED) public void testCorrectUserCorrectPasswordWithAlternativeCharset(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER_ENCODED, ENCODED_PASSWORD, SC_OK); } /** * * Test Properties realm correctly handles a password using a different character set to * and base64 encoding as the string format for the password if they are not stored in plain text. */ @Test @OperateOnDeployment(DEPLOYMENT_WITH_CHARSET_ENCODED) public void testCorrectUserCorrectPasswordBase64Encoded(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER_WITH_CHARSET_ENCODED, CHARSET_PASSWORD, SC_OK); } private URL prepareURL(URL url) throws MalformedURLException { return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); } static class SetUpTask implements ServerSetupTask { private static final String REALM_NAME_ENCODED = "propRealmEncoded"; private static final String REALM_NAME_ENCODING_CHARSET = "propRealmEncodingCharset"; private static final String DOMAIN_NAME_ENCODED = "propDomainEncoded"; private static final String DOMAIN_NAME_ENCODING_CHARSET = "propDomainEncodingCharset"; private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global"; @Override public void setup(ManagementClient managementClient, java.lang.String s) throws Exception { setUpTestDomain(DOMAIN_NAME_ENCODED, REALM_NAME_ENCODED, DEPLOYMENT_ENCODED, "users-hashedbase64.properties", "base64", "UTF-8"); setUpTestDomain(DOMAIN_NAME_ENCODING_CHARSET, REALM_NAME_ENCODING_CHARSET, DEPLOYMENT_WITH_CHARSET_ENCODED, "users-hashedbase64charset", "base64", "GB2312"); ServerReload.reloadIfRequired(managementClient); } private void setUpTestDomain(String domainName, String realmName, String deployment, String fileName, String hashEncoding, String hashCharset) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/properties-realm=%s:add(groups-attribute=groups, user-properties={path=%s, relative-to=jboss.server.config.dir}, " + "hash-encoding=%s, hash-charset=%s)", realmName, fileName, hashEncoding, hashCharset)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s,role-decoder=groups-to-roles}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName)); cli.sendLine(String.format( "/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s," + "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])", domainName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY)); cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)", deployment, domainName)); } } @Override public void tearDown(ManagementClient managementClient, java.lang.String s) throws Exception { tearDownDomain(DEPLOYMENT_ENCODED, DOMAIN_NAME_ENCODED, REALM_NAME_ENCODED); tearDownDomain(DEPLOYMENT_WITH_CHARSET_ENCODED, DOMAIN_NAME_ENCODING_CHARSET, REALM_NAME_ENCODING_CHARSET); ServerReload.reloadIfRequired(managementClient); } private void tearDownDomain(String deployment, String domainName, String realmName) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deployment)); cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/properties-realm=%s:remove()", realmName)); } } } }
8,729
50.964286
204
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/FilesystemRealmTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import java.net.MalformedURLException; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Full authentication tests for Elytron Filesystem Realm using hash encoding and * hash charsets. * * @author Sonia Zaldana Calles <szaldana@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({FilesystemRealmTestCase.SetUpTask.class}) public class FilesystemRealmTestCase { private static final String DEPLOYMENT_ENCODED = "filesystemRealmEncoded"; private static final String DEPLOYMENT_ENCODED_CHARSET = "filesystemRealmEncodedCharset"; private static final String USER = "plainUser"; private static final String ENCODED_PASSWORD = "secretPassword"; private static final String ENCODED_CHARSET_PASSWORD = "password密码"; @Deployment(name = DEPLOYMENT_ENCODED) public static WebArchive deploymentWithCharset() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_ENCODED + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(FilesystemRealmTestCase.class.getPackage(), "filesystem-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_ENCODED), "jboss-web.xml"); return war; } @Deployment(name = DEPLOYMENT_ENCODED_CHARSET) public static WebArchive deploymentWithCharsetAndEncoded() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_ENCODED_CHARSET + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(FilesystemRealmTestCase.class.getPackage(), "filesystem-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_ENCODED_CHARSET), "jboss-web.xml"); return war; } /** * * Test Filesystem realm correctly handles a password using a different string format than * base64 when the password is not stored in plain text. */ @Test @OperateOnDeployment(DEPLOYMENT_ENCODED) public void testHexEncodedPassword(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, ENCODED_PASSWORD, SC_OK); } /** * * Test Filesystem realm correctly handles a password using a different character set than UTF-8 * and a different string format than base64. */ @Test @OperateOnDeployment(DEPLOYMENT_ENCODED_CHARSET) public void testHexEncodedPasswordAndCharset(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, ENCODED_CHARSET_PASSWORD, SC_OK); } private URL prepareURL(URL url) throws MalformedURLException { return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); } static class SetUpTask implements ServerSetupTask { private static final String REALM_NAME_ENCODED = "fsRealmEncoded"; private static final String REALM_NAME_ENCODING_CHARSET = "fsRealmEncodingCharset"; private static final String DOMAIN_NAME_ENCODED = "fsDomainEncoded"; private static final String DOMAIN_NAME_ENCODING_CHARSET = "fsDomainEncodingCharset"; private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global"; @Override public void setup(ManagementClient managementClient, java.lang.String s) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine("/subsystem=elytron/simple-role-decoder=from-roles-attribute:add(attribute=Roles)"); } setUpTestDomain(DOMAIN_NAME_ENCODED, REALM_NAME_ENCODED, "filesystem1", USER, ENCODED_PASSWORD, DEPLOYMENT_ENCODED, "hex", "UTF-8"); setUpTestDomain(DOMAIN_NAME_ENCODING_CHARSET, REALM_NAME_ENCODING_CHARSET, "filesystem2", USER, ENCODED_CHARSET_PASSWORD, DEPLOYMENT_ENCODED_CHARSET, "hex", "GB2312"); ServerReload.reloadIfRequired(managementClient); } private void setUpTestDomain(String domainName, String realmName, String path, String username, String password, String deployment, String hashEncoding, String hashCharset) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s,relative-to=jboss.server.config.dir, hash-encoding=%s, hash-charset=%s)", realmName, path, hashEncoding, hashCharset)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%1$s:set-password(identity=%2$s, digest={algorithm=digest-md5, realm=%1$s, password=%3$s})", realmName, username, password)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=Roles, value=[JBossAdmin])", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s,role-decoder=from-roles-attribute}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName)); cli.sendLine(String.format( "/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s," + "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])", domainName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY)); cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)", deployment, domainName)); } } @Override public void tearDown(ManagementClient managementClient, java.lang.String s) throws Exception { tearDownDomain(DEPLOYMENT_ENCODED, DOMAIN_NAME_ENCODED, REALM_NAME_ENCODED, USER); tearDownDomain(DEPLOYMENT_ENCODED_CHARSET, DOMAIN_NAME_ENCODING_CHARSET, REALM_NAME_ENCODING_CHARSET, USER); try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine("/subsystem=elytron/simple-role-decoder=from-roles-attribute:remove()"); } ServerReload.reloadIfRequired(managementClient); } private void tearDownDomain(String deployment, String domainName, String realmName, String username) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deployment)); cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove()", realmName)); } } } }
9,583
53.146893
209
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/AggregateRealmWrongPrincipalSetupTestCase.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.AggregateSecurityRealm; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.FileSystemRealm; import org.wildfly.test.security.common.elytron.RegexPrincipalTransformer; import java.util.ArrayList; /** * Negative scenarios for management operations about Elytron Aggregate Realm with Principal transformer * * https://issues.jboss.org/browse/WFLY-12202 * https://issues.jboss.org/browse/WFCORE-4496 * https://issues.jboss.org/browse/ELY-1829 */ @RunWith(Arquillian.class) @RunAsClient public class AggregateRealmWrongPrincipalSetupTestCase { private static final String AGGREGATE_REALM_NAME = "elytron-aggregate-realm-same-type"; private static final String FILESYSTEM_REALM_AUTHN_NAME = "elytron-authn-filesystem-realm"; private static final String FILESYSTEM_REALM_AUTHZ_NAME = "elytron-authz-filesystem-realm"; private static final String VALID_PRINCIPAL_TRANSFORMER = "elytron-custom-principal-transformer"; private static final String NON_EXISTING_PRINCIPAL_TRANSFORMER = "invalid-elytron-custom-principal-transformer"; private static final String EMPTY_PRINCIPAL_TRANSFORMER = ""; /** * Prerequisites for test case */ private static InitSetupTask initSetupTask = new InitSetupTask(); /** * Management client */ private static final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); private static final ManagementClient mClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); /** * Prepare prerequisites */ @BeforeClass public static void prepare() throws Exception { initSetupTask.setup(mClient, null); } /** * Test cleanup */ @AfterClass public static void cleanup() throws Exception { initSetupTask.tearDown(mClient, null); } /** * Adding an "aggregate-realm" with a "principal-transformer". * Non-existing principal transformer is used. * Check that correct error message is printed. */ @Test public void nonExistingPrincipalTransformer() throws Exception { InvalidTransformerSetupTask task = new InvalidTransformerSetupTask(); boolean expectedErrorFound = false; try { task.setup(mClient, null); } catch (Exception e) { String msg = e.getMessage(); if (msg.contains("WFLYCTL0369") && msg.contains(NON_EXISTING_PRINCIPAL_TRANSFORMER)) { expectedErrorFound = true; } } if (!expectedErrorFound) { try { task.tearDown(mClient, null); } catch (Exception e) { // tearDown needs to be done as a cleanup for sure // originally, realm should not be created, but expectation was not fulfilled } Assert.fail("Expected error containing WFLYCTL0369 and " + NON_EXISTING_PRINCIPAL_TRANSFORMER + " doesn't occur"); } } /** * Adding an "aggregate-realm" with a "principal-transformer". * Name of principal transformer is empty string. * Check that correct error message is printed. */ @Test public void emptyPrincipalTransformer() throws Exception { EmptyTransformerSetupTask task = new EmptyTransformerSetupTask(); boolean expectedErrorFound = false; try { task.setup(mClient, null); } catch (Exception e) { String msg = e.getMessage(); if (msg.contains("WFLYCTL0113") && msg.contains("principal-transformer")) { expectedErrorFound = true; } } if (!expectedErrorFound) { try { task.tearDown(mClient, null); } catch (Exception e) { // tearDown needs to be done as a cleanup for sure // originally, realm should not be created, but expectation was not fulfilled } Assert.fail("Expected error containing WFLYCTL0113 and principal-transformer doesn't occur"); } } /** * Server setup task tries to prepare aggregate security realm with non-existing principal transformer */ static class InvalidTransformerSetupTask extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_NAME) .withAuthenticationRealm(FILESYSTEM_REALM_AUTHN_NAME) .withAuthorizationRealm(FILESYSTEM_REALM_AUTHZ_NAME) .withPrincipalTransformer(NON_EXISTING_PRINCIPAL_TRANSFORMER) .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } } /** * Server setup task tries to prepare aggregate security realm with principal transformer with empty name */ static class EmptyTransformerSetupTask extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_NAME) .withAuthenticationRealm(FILESYSTEM_REALM_AUTHN_NAME) .withAuthorizationRealm(FILESYSTEM_REALM_AUTHZ_NAME) .withPrincipalTransformer(EMPTY_PRINCIPAL_TRANSFORMER) .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } } /** * Testcase prerequisites * Create principal transformer, authentication and authorization realm */ static class InitSetupTask extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); // prepare principal transcormer configurableElements.add(RegexPrincipalTransformer.builder(VALID_PRINCIPAL_TRANSFORMER) .withPattern("a") .withReplacement("b") .build()); // filesystem-realm realm for authentication configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_AUTHN_NAME) .build()); // filesystem-realm realm for authorization configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_AUTHZ_NAME) .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } } }
8,226
39.930348
175
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/FailoverRealmTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.jboss.as.test.integration.security.common.Utils.makeCallWithTokenAuthn; import static org.jboss.as.test.shared.CliUtils.asAbsolutePath; import static org.jboss.as.test.shared.CliUtils.escapePath; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import java.io.File; import java.io.PrintWriter; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Base64; import java.util.Base64.Encoder; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.cli.Util; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.DirContext; import org.wildfly.test.security.common.elytron.FailoverRealm; import org.wildfly.test.security.common.elytron.FileAuditLog; import org.wildfly.test.security.common.elytron.FileSystemRealm; import org.wildfly.test.security.common.elytron.JdbcSecurityRealm; import org.wildfly.test.security.common.elytron.LdapRealm; import org.wildfly.test.security.common.elytron.MechanismConfiguration; import org.wildfly.test.security.common.elytron.PropertiesRealm; import org.wildfly.test.security.common.elytron.SimpleHttpAuthenticationFactory; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.TokenRealm; import org.wildfly.test.security.common.elytron.UserWithAttributeValues; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Tests the {@link FailoverRealm} within the Elytron subsystem. The tests cover filesystem-realm, jdbc-realm, ldap-realm, * properties-realm, and token-realm, trying the failover to a properties-realm when the primary (delegate) realm is unavailable * (throws RealmUnavailableException). * * It's also tested whether the SecurityRealmUnavailableEvent is emitted when expected. * * @author Ondrej Kotek */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({FailoverRealmTestCase.ServerSetup.class}) public class FailoverRealmTestCase { private static final String DEPLOYMENT_FIRST_AVAILABLE = "FailoverRealmDeployment-FirstAvailable"; private static final String DEPLOYMENT_FILESYSTEM = "FailoverRealmDeployment-Filesystem"; private static final String DEPLOYMENT_JDBC = "FailoverRealmDeployment-JDBC"; private static final String DEPLOYMENT_LDAP = "FailoverRealmDeployment-LDAP"; private static final String DEPLOYMENT_PROPERTIES = "FailoverRealmDeployment-properties"; private static final String DEPLOYMENT_BOTH_UNAVAILABLE = "FailoverRealmDeployment-BothUnvailable"; private static final String DEPLOYMENT_EVENT_DISABLED = "FailoverRealmDeployment-EventDisabled"; private static final String DEPLOYMENT_BEARER_TOKEN = "FailoverRealmDeployment-BearerToken"; private static final String INDEX_PAGE_CONTENT = "index page content"; private static final Encoder B64_ENCODER = Base64.getUrlEncoder().withoutPadding(); private static final String JWT_HEADER_B64 = B64_ENCODER .encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8)); private static final File AUDIT_LOG_FILE = Paths.get("target", FailoverRealmTestCase.class.getSimpleName() + "-test-audit.log").toFile(); @Deployment(name = DEPLOYMENT_FIRST_AVAILABLE) public static WebArchive deploymentForFirstRealmAvailable() { return deployment(DEPLOYMENT_FIRST_AVAILABLE, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_FILESYSTEM) public static WebArchive deploymentForFilesystemRealm() { return deployment(DEPLOYMENT_FILESYSTEM, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_JDBC) public static WebArchive deploymentForJdbcRealm() { return deployment(DEPLOYMENT_JDBC, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_LDAP) public static WebArchive deploymentForLdapRealm() { return deployment(DEPLOYMENT_LDAP, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_PROPERTIES) public static WebArchive deploymentForPropertiesRealmUnavailable() { return deployment(DEPLOYMENT_PROPERTIES, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_BOTH_UNAVAILABLE) public static WebArchive deploymentForBothRealmsUnavailable() { return deployment(DEPLOYMENT_BOTH_UNAVAILABLE, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_EVENT_DISABLED) public static WebArchive deploymentForEventDisabled() { return deployment(DEPLOYMENT_EVENT_DISABLED, "failover-realm-web.xml"); } @Deployment(name = DEPLOYMENT_BEARER_TOKEN) public static WebArchive deploymentForBearerToken() { return deployment(DEPLOYMENT_BEARER_TOKEN, "failover-realm-bearer-token-web.xml"); } private static WebArchive deployment(String name, String webXml) { final WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war"); war.add(new StringAsset(INDEX_PAGE_CONTENT), "index.html"); war.addAsWebInfResource(FailoverRealmTestCase.class.getPackage(), webXml, "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(name), "jboss-web.xml"); return war; } @Test @OperateOnDeployment(DEPLOYMENT_FIRST_AVAILABLE) public void testFirstRealmAvailable(@ArquillianResource URL webAppUrl) throws Exception { testCredentialBasedRealmsNoFailover(webAppUrl); } @Test @OperateOnDeployment(DEPLOYMENT_FILESYSTEM) public void testFilesystemRealmUnavailable(@ArquillianResource URL webAppUrl) throws Exception { assumeFalse(Util.isWindows()); // no easy and robust way to prepare the conditions on Windows testCredentialBasedRealmsFailover(webAppUrl); } @Test @OperateOnDeployment(DEPLOYMENT_JDBC) public void testJdbcRealmUnavailable(@ArquillianResource URL webAppUrl) throws Exception { testCredentialBasedRealmsFailover(webAppUrl); } @Test @OperateOnDeployment(DEPLOYMENT_LDAP) public void testLdapRealmUnavailable(@ArquillianResource URL webAppUrl) throws Exception { testCredentialBasedRealmsFailover(webAppUrl); } @Test @OperateOnDeployment(DEPLOYMENT_PROPERTIES) public void testPropertiesRealmUnavailable(@ArquillianResource URL webAppUrl) throws Exception { cleanAuditLog(); String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); cleanAuditLog(); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "wrongPassword1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); // no failover, just user1 is known in the first realm (its unhashed password causes the failover) cleanAuditLog(); result = Utils.makeCallWithBasicAuthn(webAppUrl, "non-existing-user1", "password1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertFalse("SecurityRealmUnavailableEvent should not be logged", isSecurityRealmUnavailableEventLogged()); } @Test @OperateOnDeployment(DEPLOYMENT_BOTH_UNAVAILABLE) public void testBothCredentialBasedRealmsUnavailable(@ArquillianResource URL webAppUrl) throws Exception { cleanAuditLog(); String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_INTERNAL_SERVER_ERROR); assertNotEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); } @Test @OperateOnDeployment(DEPLOYMENT_EVENT_DISABLED) public void testEventDisabled(@ArquillianResource URL webAppUrl) throws Exception { // failovers happen but are not logged, like in case of no failovers testCredentialBasedRealmsNoFailover(webAppUrl); } @Test @OperateOnDeployment(DEPLOYMENT_BEARER_TOKEN) public void testTokenRealmUnvailable(@ArquillianResource URL webAppUrl) throws Exception { cleanAuditLog(); String result = makeCallWithTokenAuthn(webAppUrl, createJwtToken("userA", "issuer.wildfly.org"), SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); cleanAuditLog(); result = makeCallWithTokenAuthn(webAppUrl, createJwtToken("userC", "unknown_issuer"), SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); } private void testCredentialBasedRealmsFailover(URL webAppUrl) throws Exception { cleanAuditLog(); String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); cleanAuditLog(); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "wrongPassword1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); cleanAuditLog(); result = Utils.makeCallWithBasicAuthn(webAppUrl, "non-existing-user1", "password1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertTrue("SecurityRealmUnavailableEvent should be logged", isSecurityRealmUnavailableEventLogged()); } private void testCredentialBasedRealmsNoFailover(URL webAppUrl) throws Exception { cleanAuditLog(); String result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "password1", SC_OK); assertEquals(INDEX_PAGE_CONTENT, result); assertFalse("SecurityRealmUnavailableEvent should not be logged", isSecurityRealmUnavailableEventLogged()); cleanAuditLog(); result = Utils.makeCallWithBasicAuthn(webAppUrl, "user1", "wrongPassword1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertFalse("SecurityRealmUnavailableEvent should not be logged", isSecurityRealmUnavailableEventLogged()); cleanAuditLog(); result = Utils.makeCallWithBasicAuthn(webAppUrl, "non-existing-user1", "password1", SC_UNAUTHORIZED); assertNotEquals(INDEX_PAGE_CONTENT, result); assertFalse("SecurityRealmUnavailableEvent should not be logged", isSecurityRealmUnavailableEventLogged()); } private static boolean isSecurityRealmUnavailableEventLogged() throws Exception { List<String> lines = Files.readAllLines(AUDIT_LOG_FILE.toPath(), StandardCharsets.UTF_8); for (String line : lines) { if (line.contains("SecurityRealmUnavailableEvent")) { return true; } } return false; } private static void cleanAuditLog() throws Exception { try (PrintWriter writer = new PrintWriter(AUDIT_LOG_FILE)) { writer.print(""); } } private static String createJwtToken(String userName, String issuer) { String jwtPayload = String.format("{" + "\"active\": true," + "\"iss\": \"%1$s\"," + "\"sub\": \"elytron@wildfly.org\"," + "\"exp\": 2051222399," + "\"aud\": \"%1$s\"," + "\"groups\": [\"%2$s\"]" + "}", issuer, userName); return JWT_HEADER_B64 + "." + B64_ENCODER.encodeToString(jwtPayload.getBytes(StandardCharsets.UTF_8)) + "."; } static class ServerSetup extends AbstractElytronSetupTask { File unavailableFileSystemRealmDir; @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); // this audit log is checked for presence of SecurityRealmUnavailableEvent configurableElements.add(FileAuditLog.builder() .withName("audit_log_for_failover_realm") .withPath(asAbsolutePath(AUDIT_LOG_FILE)) .build()); // this properties realm is used as a failover realm to test the other credential based failovers configurableElements.add(PropertiesRealm.builder() .withName("properties_realm_1") .withUser(UserWithAttributeValues.builder() .withName("user1") .withPassword("password1") .withValues("user") .build()) .build()); // filesystem realm FileSystemRealm unavailableFileSystemRealm = FileSystemRealm.builder() .withName("unavailable_filesystem_realm") .build(); String unavailableFileSystemRealmPath = unavailableFileSystemRealm.getPath().getPath(); // prevent accessing the temporary directory for the realm unavailableFileSystemRealmDir = new File(escapePath(unavailableFileSystemRealmPath)); unavailableFileSystemRealmDir.setExecutable(false, false); configurableElements.add(unavailableFileSystemRealm); configurableElements.add(FailoverRealm.builder("failover_realm_filesystem") .withDelegateRealm("unavailable_filesystem_realm") .withFailoverRealm("properties_realm_1") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_filesystem") .withDefaultRealm("failover_realm_filesystem") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_filesystem") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FILESYSTEM) .withSecurityDomain("failover_realm_domain_filesystem") .build()); // JDBC realm configurableElements.add(JdbcSecurityRealm.builder("unavailable_jdbc_realm") .withPrincipalQuery("ExampleDS", "invalid SQL") .withPasswordMapper("clear-password-mapper", null, 1, -1, -1) .build() .build()); configurableElements.add(FailoverRealm.builder("failover_realm_jdbc") .withDelegateRealm("unavailable_jdbc_realm") .withFailoverRealm("properties_realm_1") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_jdbc") .withDefaultRealm("failover_realm_jdbc") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_jdbc") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_JDBC) .withSecurityDomain("failover_realm_domain_jdbc") .build()); // LDAP realm configurableElements.add(DirContext.builder("unavailable_dir_context") .withUrl("invalid_url") .build()); configurableElements.add(LdapRealm.builder("unavailable_ldap_realm") .withDirContext("unavailable_dir_context") .withIdentityMapping(LdapRealm.identityMappingBuilder() .withRdnIdentifier("invalid") .withUserPasswordMapper(new LdapRealm.UserPasswordMapperBuilder() .withFrom("invalid") .build()) .build()) .build()); configurableElements.add(FailoverRealm.builder("failover_realm_ldap") .withDelegateRealm("unavailable_ldap_realm") .withFailoverRealm("properties_realm_1") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_ldap") .withDefaultRealm("failover_realm_ldap") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_ldap") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_LDAP) .withSecurityDomain("failover_realm_domain_ldap") .build()); // properties realm configurableElements.add(PropertiesRealm.builder() .withName("unavailable_properties_realm") .withPlainText(false) .withUser(UserWithAttributeValues.builder() .withName("user1") .withPassword("password1") // this is expected to be hashed but it isn't .withValues("user") .build()) .build()); configurableElements.add(FailoverRealm.builder("failover_realm_properties") .withDelegateRealm("unavailable_properties_realm") .withFailoverRealm("properties_realm_1") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_properties") .withDefaultRealm("failover_realm_properties") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_properties") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_PROPERTIES) .withSecurityDomain("failover_realm_domain_properties") .build()); // the delegate realm is available, the failover realm is not (LDAP) configurableElements.add(FailoverRealm.builder("failover_realm_first_available") .withDelegateRealm("properties_realm_1") .withFailoverRealm("unavailable_ldap_realm") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_first_available") .withDefaultRealm("failover_realm_first_available") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_first_available") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_FIRST_AVAILABLE) .withSecurityDomain("failover_realm_domain_first_available") .build()); // both the credentaial based realms are not available configurableElements.add(FailoverRealm.builder("failover_realm_both_unavailable") .withDelegateRealm("unavailable_jdbc_realm") .withFailoverRealm("unavailable_ldap_realm") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_both_unavailable") .withDefaultRealm("failover_realm_both_unavailable") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_both_unavailable") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_BOTH_UNAVAILABLE) .withSecurityDomain("failover_realm_domain_both_unavailable") .build()); // failover with SecurityRealmUnavailableEvent emitting disabled configurableElements.add(FailoverRealm.builder("failover_realm_event_disabled") .withDelegateRealm("unavailable_jdbc_realm") .withFailoverRealm("properties_realm_1") .withEmitEvents(false) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_event_disabled") .withDefaultRealm("failover_realm_event_disabled") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_event_disabled") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_EVENT_DISABLED) .withSecurityDomain("failover_realm_domain_event_disabled") .build()); // token realm configurableElements.add(TokenRealm.builder("token_realm") .withJwt(TokenRealm.jwtBuilder().withIssuer("issuer.wildfly.org").build()) .withPrincipalClaim("aud") .build()); configurableElements.add(TokenRealm.builder("unavailable_token_realm") .withOauth2Introspection(TokenRealm.oauth2IntrospectionBuilder() .withClientId("failover_realm_client") .withClientSecret("failover_realm_client_secret") .withIntrospectionUrl("http://invalid") .build()) .withPrincipalClaim("aud") .build()); configurableElements.add(FailoverRealm.builder("failover_realm_bearer_token") .withDelegateRealm("unavailable_token_realm") .withFailoverRealm("token_realm") .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName("failover_realm_domain_bearer_token") .withDefaultRealm("failover_realm_bearer_token") .withPermissionMapper("default-permission-mapper") .withSecurityEventListener("audit_log_for_failover_realm") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm("failover_realm_bearer_token") .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(SimpleHttpAuthenticationFactory.builder() .withName(DEPLOYMENT_BEARER_TOKEN) .withHttpServerMechanismFactory("global") .withSecurityDomain("failover_realm_domain_bearer_token") .addMechanismConfiguration(MechanismConfiguration.builder() .withMechanismName("BEARER_TOKEN") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT_BEARER_TOKEN) .httpAuthenticationFactory(DEPLOYMENT_BEARER_TOKEN) .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } @Override protected void tearDown(ModelControllerClient modelControllerClient) throws Exception { super.tearDown(modelControllerClient); Files.deleteIfExists(AUDIT_LOG_FILE.toPath()); } } }
28,350
51.308118
128
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/AggregateRealmUtil.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import org.codehaus.plexus.util.StringUtils; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.servlet.AttributePrintingServlet; import java.io.ByteArrayInputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Properties; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Util class for: * * AggregateRealmTestCase * * AggregateRealmWithTransformerTestCase */ public class AggregateRealmUtil { public static void assertNoRoleAssigned(URL webAppURL, String username, String password, String queryRoles) throws Exception { assertHttpCallEndsBy(webAppURL, username, password, SC_FORBIDDEN, queryRoles); } public static void assertAuthenticationFailed(URL webAppURL, String username, String password, String queryRoles) throws Exception { assertHttpCallEndsBy(webAppURL, username, password, SC_UNAUTHORIZED, queryRoles); } public static void assertAuthenticationSuccess(URL webAppURL, String username, String password, String queryRoles) throws Exception { assertHttpCallEndsBy(webAppURL, username, password, SC_OK, queryRoles); } public static void assertHttpCallEndsBy(URL webAppURL, String username, String password, int expectedStatusCode, String queryRoles) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL, queryRoles); Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, expectedStatusCode); } public static URL prepareRolesPrintingURL(URL webAppURL, String queryRoles) throws MalformedURLException { return new URL(webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + queryRoles); } public static Properties getAttributes(URL webAppURL, final String identity, final String password) throws Exception { URL adjustedUrl = new URL(webAppURL.toExternalForm() + AttributePrintingServlet.SERVLET_PATH.substring(1)); final String attributesResponse = Utils.makeCallWithBasicAuthn(adjustedUrl, identity, password, SC_OK); Properties properties = new Properties(); properties.load(new ByteArrayInputStream(attributesResponse.getBytes())); return properties; } public static void assertAttribute(Properties properties, String attributeName, String... attributeValues) { assertTrue("Attribute Exists", properties.containsKey(attributeName)); List<String> values = Arrays.asList(properties.getProperty(attributeName).split(",")); assertEquals("Value Count", attributeValues.length, values.size()); for (String currentValue : attributeValues) { assertTrue("Value Exists", values.contains(currentValue)); } } public static void assertInRole(final String rolePrintResponse, String role) { if (!StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Missing role '" + role + "' assignment"); } } public static void assertNotInRole(final String rolePrintResponse, String role) { if (StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Unexpected role '" + role + "' assignment"); } } public static class CustomFSAttributes implements ConfigurableElement { private final String realm; private final String identity; private final String attributeName; private final String[] values; CustomFSAttributes(String realm, String identity, String attributeName, String... values) { this.realm = realm; this.identity = identity; this.attributeName = attributeName; this.values = values; } @Override public String getName() { return String.format("Attribute '$s' for identity '%s' in realm '%s'", attributeName, identity, realm); } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine(String.format( "/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=%s, value=[%s])", realm, identity, attributeName, String.join(",", values))); } @Override public void remove(CLIWrapper cli) throws Exception { // empty, attributes are not stored in management model } } }
5,624
42.604651
154
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/FilesystemRealmEncryptedWrongSecretKeyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import java.net.MalformedURLException; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Authentication test with invalid SecretKey for Elytron Encrypted Filesystem Realm. * * @author Ashpan Raskar <araskar@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({FilesystemRealmEncryptedWrongSecretKeyTestCase.SetUpTask.class}) public class FilesystemRealmEncryptedWrongSecretKeyTestCase { private static final String DEPLOYMENT_ENCRYPTED = "filesystemRealmEncrypted"; private static final String USER = "plainUser"; private static final String PASSWORD = "secretPassword"; @Deployment(name = DEPLOYMENT_ENCRYPTED) public static WebArchive deploymentWithCharsetAndEncoded() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_ENCRYPTED + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(FilesystemRealmEncryptedWrongSecretKeyTestCase.class.getPackage(), "filesystem-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_ENCRYPTED), "jboss-web.xml"); return war; } /** * * Test Filesystem realm when choosing to encrypt it with a bad Secret Key. */ @Test @OperateOnDeployment(DEPLOYMENT_ENCRYPTED) public void testEncryptionSecretKeyFail(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_INTERNAL_SERVER_ERROR); } private URL prepareURL(URL url) throws MalformedURLException { return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); } static class SetUpTask implements ServerSetupTask { private static final String REALM_NAME = "fsRealmEncrypted"; private static final String DOMAIN_NAME = "fsDomainEncrypted"; private static final String CREDENTIAL_STORE = "mycredstore"; private static final String INVALID_CREDENTIAL_STORE = "invalidcredstore"; private static final String SECRET_KEY = "key"; private static ManagementClient managementClient; @Override public void setup(ManagementClient managementClient, java.lang.String s) throws Exception { setUpTestDomain(DOMAIN_NAME, REALM_NAME, "filesystem", USER, PASSWORD, DEPLOYMENT_ENCRYPTED, CREDENTIAL_STORE, SECRET_KEY, INVALID_CREDENTIAL_STORE); SetUpTask.managementClient = managementClient; ServerReload.reloadIfRequired(managementClient); } private void setUpTestDomain(String domainName, String realmName, String path, String username, String password, String deployment, String credentialStore, String secretKey, String invalidCredentialStore) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%1$s:add(path=%1$s.cs, relative-to=jboss.server.config.dir, create=true, populate=true)", credentialStore)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s,relative-to=jboss.server.config.dir, credential-store=%s, secret-key=%s)", realmName, path, credentialStore, secretKey)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%1$s:set-password(identity=%2$s, digest={algorithm=digest-md5, realm=%1$s, password=%3$s})", realmName, username, password)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=Roles, value=[JBossAdmin])", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%1$s:add(path=%1$s.cs, relative-to=jboss.server.config.dir, create=true, populate=true)", invalidCredentialStore)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s,relative-to=jboss.server.config.dir, credential-store=%s, secret-key=%s)", realmName+"Invalid", path, invalidCredentialStore, secretKey)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName+"Invalid")); cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%s:add(security-domain=%s)", deployment, domainName)); } } @Override public void tearDown(ManagementClient managementClient, java.lang.String s) throws Exception { SetUpTask.managementClient = managementClient; tearDownDomain(DEPLOYMENT_ENCRYPTED, DOMAIN_NAME, REALM_NAME, USER, CREDENTIAL_STORE, INVALID_CREDENTIAL_STORE); ServerReload.reloadIfRequired(managementClient); } private void tearDownDomain(String deployment, String domainName, String realmName, String username, String credentialStore, String invalidCredentialStore) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deployment)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove()", realmName)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove()", realmName+"Invalid")); cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%s:remove()", credentialStore)); cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%s:remove()", invalidCredentialStore)); } } } }
8,497
55.653333
231
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/LdapRealmIgnoreReferralsTestCase.java
/* * Copyright (c) 2022 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of Apache License v2.0 which * accompanies this distribution. * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import java.net.URL; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.junit.runner.RunWith; /** * <p>Configures referral mode to ignore and executes the smoke tests.</p> * * @author rmartinc */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractLdapRealmTest.LDAPServerSetupTask.class, LdapRealmIgnoreReferralsTestCase.SetupTask.class}) public class LdapRealmIgnoreReferralsTestCase extends AbstractLdapRealmTest { @Override public void testReferralUser(@ArquillianResource URL webAppURL) throws Exception { // the referral user should not be found as referrals are ignored assertAuthenticationFailed(webAppURL, USER_REFERRAL, CORRECT_PASSWORD); } /** * SetupTask with referral mode to ignore. */ static class SetupTask extends AbstractLdapRealmTest.SetupTask { @Override public String getReferralMode() { return "ignore"; } } }
1,837
33.037037
113
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/AbstractLdapRealmTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import org.apache.commons.io.FileUtils; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.server.annotations.CreateLdapServer; import org.apache.directory.server.annotations.CreateTransport; import org.apache.directory.server.core.annotations.AnnotationUtils; import org.apache.directory.server.core.annotations.ContextEntry; import org.apache.directory.server.core.annotations.CreateDS; import org.apache.directory.server.core.annotations.CreateIndex; import org.apache.directory.server.core.annotations.CreatePartition; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.factory.DSAnnotationProcessor; import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor; import org.apache.directory.server.factory.ServerAnnotationProcessor; import org.apache.directory.server.ldap.LdapServer; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.codehaus.plexus.util.StringUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.ManagedCreateLdapServer; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; /** * Abstract base test for Elytron Ldap Realm. It tests only basic functionality of Ldap Realm. <br> * Given: Deployed secured application deployment for printing roles<br> * and using BASIC authentication<br> * * @author olukas */ public abstract class AbstractLdapRealmTest { @BeforeClass public static void beforeClass() { // https://issues.redhat.com/browse/WFLY-17383 AssumeTestGroupUtil.assumeJDKVersionBefore(20); } private static final String DEPLOYMENT = "ldapRealmDep"; private static final String DEPLOYMENT_WITH_CHARSET = "ldapRealmDepCharset"; private static final String DEPLOYMENT_HEX_CHARSET = "ldapRealmDepHexCharset"; private static final int LDAP_PORT = 10389; private static final String USER_WITHOUT_ROLE = "userWithoutRole"; private static final String USER_WITH_ONE_ROLE = "userWithOneRole"; private static final String USER_WITH_MORE_ROLES = "userWithMoreRoles"; private static final String USER_NOT_EXIST = "notExistUser"; private static final String USER_WITH_CHARSET = "ssha512UserCharset"; private static final String USER_HEX_CHARSET = "cryptUserCharsetHex"; protected static final String USER_REFERRAL = "referralUser"; private static final String EMPTY_USER = ""; protected static final String CORRECT_PASSWORD = "Password1"; private static final String WRONG_PASSWORD = "WrongPassword"; private static final String EMPTY_PASSWORD = ""; private static final String CHARSET_PASSWORD = "password密码"; static final String[] ALL_TESTED_ROLES = {"TheDuke", "JBossAdmin"}; static final String QUERY_ROLES; static { final List<NameValuePair> qparams = new ArrayList<>(); for (final String role : ALL_TESTED_ROLES) { qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role)); } QUERY_ROLES = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8); } @Deployment(name = DEPLOYMENT) public static WebArchive deployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war"); war.addClasses(RolePrintingServlet.class); war.addAsWebInfResource(AbstractLdapRealmTest.class.getPackage(), "ldap-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT), "jboss-web.xml"); return war; } @Deployment(name = DEPLOYMENT_WITH_CHARSET) public static WebArchive deploymentWithCharset() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_WITH_CHARSET + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(AbstractLdapRealmTest.class.getPackage(), "ldap-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_WITH_CHARSET), "jboss-web.xml"); return war; } @Deployment(name = DEPLOYMENT_HEX_CHARSET) public static WebArchive deploymentEncodedWithCharset() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_HEX_CHARSET + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(AbstractLdapRealmTest.class.getPackage(), "ldap-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_HEX_CHARSET), "jboss-web.xml"); return war; } /** * Given: LDAP maps roles 'TheDuke' and 'JBossAdmin' to user 'userWithMoreRoles'. <br> * When user 'userWithMoreRoles' with correct password tries to authenticate, <br> * then authentication should succeed and just roles 'TheDuke' and 'JBossAdmin' should be assigned to user. */ @Test @OperateOnDeployment(DEPLOYMENT) public void testCorrectUserCorrectPasswordTwoRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_MORE_ROLES, CORRECT_PASSWORD, "TheDuke", "JBossAdmin"); } /** * Given: LDAP maps role 'JBossAdmin' to user 'userWithOneRole'. <br> * When user 'userWithOneRole' with correct password tries to authenticate, <br> * then authentication should succeed and just role 'JBossAdmin' should be assigned to user. */ @Test @OperateOnDeployment(DEPLOYMENT) public void testCorrectUserCorrectPasswordOneRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ONE_ROLE, CORRECT_PASSWORD, "JBossAdmin"); } /** * * Test LDAP realm correctly handles a password using a different character set to * to use when converting the password string to a byte array. */ @Test @OperateOnDeployment(DEPLOYMENT_WITH_CHARSET) public void testCorrectUserCorrectPasswordWithCharset(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER_WITH_CHARSET, CHARSET_PASSWORD, SC_OK); } /** * * Test LDAP realm correctly handles a password using a different character set to * to use when converting the password string to a byte array and hex encoding * as the string format for the password if they are not stored in plain text. */ @Test @OperateOnDeployment(DEPLOYMENT_HEX_CHARSET) public void testCorrectUserCorrectPasswordWithCharsetAndEncoding(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER_HEX_CHARSET, CHARSET_PASSWORD, SC_OK); } /** * Given: LDAP maps no role to user 'userWithoutRole'. <br> * When user 'userWithoutRole' with correct password tries to authenticate, <br> * then authentication should succeed but no roles should be assigned to user (HTTP status 403 is returned). */ @Test @OperateOnDeployment(DEPLOYMENT) public void testCorrectUserCorrectPasswordNoRole(@ArquillianResource URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER_WITHOUT_ROLE, CORRECT_PASSWORD); } /** * When exist user with wrong password tries to authenticate, <br> * then authentication should fail. */ @Test @OperateOnDeployment(DEPLOYMENT) public void testCorrectUserWrongPassword(@ArquillianResource URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_WITH_ONE_ROLE, WRONG_PASSWORD); } /** * When exist user with empty password tries to authenticate, <br> * then authentication should fail. */ @Test @OperateOnDeployment(DEPLOYMENT) public void testCorrectUserEmptyPassword(@ArquillianResource URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_WITH_ONE_ROLE, EMPTY_PASSWORD); } /** * When non-exist user with exist password tries to authenticate, <br> * then authentication should fail. */ @Test @OperateOnDeployment(DEPLOYMENT) public void testWrongUserExistPassword(@ArquillianResource URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_NOT_EXIST, CORRECT_PASSWORD); } /** * When user with empty username with exist password tries to authenticate, <br> * then authentication should fail. */ @Test @OperateOnDeployment(DEPLOYMENT) public void testEmptyUserExistPassword(@ArquillianResource URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, EMPTY_USER, CORRECT_PASSWORD); } @Test @OperateOnDeployment(DEPLOYMENT) public abstract void testReferralUser(@ArquillianResource URL webAppURL) throws Exception; private URL prepareURL(URL url) throws MalformedURLException { return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); } protected void testAssignedRoles(URL webAppURL, String username, String password, String... assignedRoles) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL); final String rolesResponse = Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_OK); final List<String> assignedRolesList = Arrays.asList(assignedRoles); for (String role : ALL_TESTED_ROLES) { if (assignedRolesList.contains(role)) { assertInRole(rolesResponse, role); } else { assertNotInRole(rolesResponse, role); } } } private void assertNoRoleAssigned(URL webAppURL, String username, String password) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL); Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_FORBIDDEN); } protected void assertAuthenticationFailed(URL webAppURL, String username, String password) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL); Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_UNAUTHORIZED); } private URL prepareRolesPrintingURL(URL webAppURL) throws MalformedURLException { return new URL(webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + QUERY_ROLES); } private void assertInRole(final String rolePrintResponse, String role) { if (!StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Missing role '" + role + "' assignment"); } } private void assertNotInRole(final String rolePrintResponse, String role) { if (StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Unexpected role '" + role + "' assignment"); } } protected abstract static class SetupTask implements ServerSetupTask { private static final String LDAP_REALM_RELATED_CONFIGURATION_NAME = "elytronLdapRealmRelatedConfiguration"; private static final String LDAP_REALM_CHARSET_CONFIGURATION_NAME = "elytronLdapRealmCharsetConfiguration"; private static final String LDAP_REALM_CHARSET_ENCODED_CONFIGURATION_NAME = "elytronLdapRealmCharsetEncodedConfiguration"; private static final String PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY = "global"; private static final String DIR_CONTEXT_NAME = "ldapRealmDirContext"; private static final String LDAP_REALM_NAME = "simpleLdapRealm"; private static final String LDAP_REALM_CHARSET_NAME = "ldapRealmCharset"; private static final String LDAP_REALM_ENCODED_CHARSET_NAME = "ldapRealmCharsetEncoded"; public abstract String getReferralMode(); @Override public void setup(ManagementClient mc, String string) throws Exception { String hostname = "ldap://" + TestSuiteEnvironment.getServerAddress() + ":" + LDAP_PORT; try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format( "/subsystem=elytron/dir-context=%s:add(url=\"%s\",principal=\"uid=admin,ou=system\",credential-reference={clear-text=secret},referral-mode=\"%s\")", DIR_CONTEXT_NAME, hostname, getReferralMode())); cli.sendLine("/subsystem=elytron/simple-role-decoder=from-roles-attribute:add(attribute=Roles)\n"); } setUpTestDomain(LDAP_REALM_NAME, LDAP_REALM_RELATED_CONFIGURATION_NAME, DEPLOYMENT); setUpTestDomain(LDAP_REALM_CHARSET_NAME, LDAP_REALM_CHARSET_CONFIGURATION_NAME, DEPLOYMENT_WITH_CHARSET, "GB2312", "base64", false); setUpTestDomain(LDAP_REALM_ENCODED_CHARSET_NAME, LDAP_REALM_CHARSET_ENCODED_CONFIGURATION_NAME, DEPLOYMENT_HEX_CHARSET, "GB2312", "hex", false); ServerReload.reloadIfRequired(mc); } private void setUpTestDomain(String realmName, String domainName, String deployment) throws Exception { setUpTestDomain(realmName, domainName, deployment, "UTF-8", "base64", true); } private void setUpTestDomain(String realmName, String domainName, String deployment, String hashCharset, String hashEncoding, boolean testingRoles) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { if (testingRoles) { cli.sendLine(String.format( "/subsystem=elytron/ldap-realm=%s:add(dir-context=%s, hash-charset=%s, hash-encoding=%s, identity-mapping={rdn-identifier=uid,search-base-dn=\"ou=People,dc=jboss,dc=org\",user-password-mapper={from=userPassword}," + "use-recursive-search=true,attribute-mapping=[{filter-base-dn=\"ou=Roles,dc=jboss,dc=org\",filter=\"(member={1})\",from=cn,to=groups,search-recursive=true}]})", realmName, DIR_CONTEXT_NAME, hashCharset, hashEncoding)); cli.sendLine(String.format( "/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s,role-decoder=groups-to-roles}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName)); } else { cli.sendLine(String.format( "/subsystem=elytron/ldap-realm=%s:add(dir-context=%s, hash-charset=%s, hash-encoding=%s, identity-mapping={rdn-identifier=uid,search-base-dn=\"ou=People,dc=jboss,dc=org\",user-password-mapper={from=userPassword}," + "use-recursive-search=true,attribute-mapping=[{filter-base-dn=\"ou=Roles,dc=jboss,dc=org\",filter=\"(&(objectClass=groupOfNames)(member={1}))\",from=cn,to=Roles,search-recursive=true}]})", realmName, DIR_CONTEXT_NAME, hashCharset, hashEncoding)); cli.sendLine(String.format( "/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s,role-decoder=from-roles-attribute}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName)); } cli.sendLine(String.format( "/subsystem=elytron/http-authentication-factory=%1$s:add(http-server-mechanism-factory=%2$s,security-domain=%1$s," + "mechanism-configurations=[{mechanism-name=BASIC,mechanism-realm-configurations=[{realm-name=\"%1$s\"}]}])", domainName, PREDEFINED_HTTP_SERVER_MECHANISM_FACTORY)); cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%s:add(http-authentication-factory=%s)", deployment, domainName)); } } @Override public void tearDown(ManagementClient mc, String string) throws Exception { tearDownDomain(DEPLOYMENT, LDAP_REALM_RELATED_CONFIGURATION_NAME, LDAP_REALM_NAME); tearDownDomain(DEPLOYMENT_WITH_CHARSET, LDAP_REALM_CHARSET_CONFIGURATION_NAME, LDAP_REALM_CHARSET_NAME); tearDownDomain(DEPLOYMENT_HEX_CHARSET, LDAP_REALM_CHARSET_ENCODED_CONFIGURATION_NAME, LDAP_REALM_ENCODED_CHARSET_NAME); try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/dir-context=%s:remove()", DIR_CONTEXT_NAME)); cli.sendLine("/subsystem=elytron/simple-role-decoder=from-roles-attribute:remove()"); } ServerReload.reloadIfRequired(mc); } private void tearDownDomain(String deployment, String domainName, String realmName) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deployment)); cli.sendLine(String.format("/subsystem=elytron/http-authentication-factory=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/ldap-realm=%s:remove()", realmName)); } } } /** * A server setup task which configures and starts LDAP server. */ //@formatter:off @CreateDS( name = "JBossDS-LdapRealmTestCase", factory = org.jboss.as.test.integration.ldap.InMemoryDirectoryServiceFactory.class, partitions = { @CreatePartition( name = "jboss", suffix = "dc=jboss,dc=org", contextEntry = @ContextEntry( entryLdif = "dn: dc=jboss,dc=org\n" + "dc: jboss\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes = { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou") }) }, additionalInterceptors = {KeyDerivationInterceptor.class}) @CreateLdapServer( transports = { @CreateTransport(protocol = "LDAP", port = LDAP_PORT, address = "0.0.0.0") }, certificatePassword = "secret") //@formatter:on static class LDAPServerSetupTask implements ServerSetupTask { private DirectoryService directoryService; private LdapServer ldapServer; private Entry createReferralEntry(SchemaManager schemaManager, String branch) throws LdapException { Entry referral = new DefaultEntry(schemaManager, "ou=Referral,ou=" + branch + ",dc=jboss,dc=org"); referral.add("objectClass", "referral", "extensibleObject"); referral.add("ou", "Referral"); referral.add("ref", "ldap://" + TestSuiteEnvironment.getServerAddress() + ":" + LDAP_PORT + "/ou=" + branch + "2,dc=jboss,dc=org"); return referral; } public void setup(ManagementClient managementClient, String containerId) throws Exception { directoryService = DSAnnotationProcessor.getDirectoryService(); final SchemaManager schemaManager = directoryService.getSchemaManager(); try { for (LdifEntry ldifEntry : new LdifReader( AbstractLdapRealmTest.class.getResourceAsStream("LdapRealmTestCase.ldif"))) { directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry())); } // create the referrals pointing to the second branch using directory hostname and port directoryService.getAdminSession().add(createReferralEntry(schemaManager, "People")); directoryService.getAdminSession().add(createReferralEntry(schemaManager, "Roles")); } catch (Exception e) { e.printStackTrace(); throw e; } final ManagedCreateLdapServer createLdapServer = new ManagedCreateLdapServer( (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class)); Utils.fixApacheDSTransportAddress(createLdapServer, Utils.getSecondaryTestAddress(managementClient, false)); ldapServer = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService); ldapServer.start(); } public void tearDown(ManagementClient managementClient, String containerId) throws Exception { ldapServer.stop(); directoryService.shutdown(); FileUtils.deleteDirectory(directoryService.getInstanceLayout().getInstanceDirectory()); } } }
23,994
50.825054
243
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/JDBCRealmAdminOnlyModeTestCase.java
/* * JBoss, Home of Professional Open Source * * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.integration.elytron.realm; import static org.junit.Assert.assertEquals; import org.jboss.dmr.ModelNode; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.test.shared.ServerReload; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.JdbcSecurityRealm; /** * A test case to test adding a {@link JdbcSecurityRealm} within the Elytron subsystem in admin only mode. * * @author <a href="mailto:aabdelsa@redhat.com">Ashley Abdel-Sayed</a> */ @RunWith(Arquillian.class) public class JDBCRealmAdminOnlyModeTestCase { @ContainerResource protected ManagementClient managementClient; protected static final int CONNECTION_TIMEOUT_IN_MS = TimeoutUtil.adjust(6 * 1000); protected static final boolean ADMIN_ONLY_MODE = true; @Test @RunAsClient public void testAddJDBCRealmAdminOnlyMode() throws Exception { ModelControllerClient client = managementClient.getControllerClient(); ServerReload.executeReloadAndWaitForCompletion(client, CONNECTION_TIMEOUT_IN_MS, ADMIN_ONLY_MODE, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), null); ModelNode operation = Operations.createReadAttributeOperation(new ModelNode().setEmptyList(), "running-mode"); assertEquals("ADMIN_ONLY", client.execute(operation).get("result").asString()); ModelNode params = new ModelNode(); params.get("sql").set("SELECT * FROM Users WHERE username = ?"); params.get("data-source").set("ExampleDS"); operation = Operations.createAddOperation(Operations.createAddress("subsystem", "elytron", "jdbc-realm", "MyRealm")); operation.get("principal-query").add(params); assertSuccess(client.execute(operation)); operation = Operations.createRemoveOperation(Operations.createAddress("subsystem", "elytron", "jdbc-realm", "MyRealm")); assertSuccess(client.execute(operation)); } @After public void reload() throws Exception { ModelControllerClient client = managementClient.getControllerClient(); ServerReload.executeReloadAndWaitForCompletion(client, CONNECTION_TIMEOUT_IN_MS, !ADMIN_ONLY_MODE, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), null); ModelNode operation = Operations.createReadAttributeOperation(new ModelNode().setEmptyList(), "running-mode"); assertEquals("NORMAL", client.execute(operation).get("result").asString()); } private ModelNode assertSuccess(ModelNode response) { if (!Operations.isSuccessfulOutcome(response)) { Assert.fail(Operations.getFailureDescription(response).asString()); } return response; } }
3,906
39.697917
128
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/JdbcRealmTestCase.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.Provider; import java.security.SecureRandom; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Base64; import java.util.Base64.Encoder; import org.h2.tools.Server; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.security.common.AbstractDataSourceServerSetupTask; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.config.DataSource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.security.WildFlyElytronProvider; import org.wildfly.security.password.PasswordFactory; import org.wildfly.security.password.interfaces.BCryptPassword; import org.wildfly.security.password.interfaces.BSDUnixDESCryptPassword; import org.wildfly.security.password.spec.EncryptablePasswordSpec; import org.wildfly.security.password.spec.IteratedSaltedPasswordAlgorithmSpec; import org.wildfly.security.password.util.ModularCrypt; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.ConstantRealmMapper; import org.wildfly.test.security.common.elytron.JdbcSecurityRealm; import org.wildfly.test.security.common.elytron.JdbcSecurityRealm.Encoding; import org.wildfly.test.security.common.elytron.MappedRegexRealmMapper; import org.wildfly.test.security.common.elytron.RegexPrincipalTransformer; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * A test case to test the {@link JdbcSecurityRealm} within the Elytron subsystem. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({JdbcRealmTestCase.DataSourcesSetup.class, JdbcRealmTestCase.DBSetup.class, JdbcRealmTestCase.ServerSetup.class}) public class JdbcRealmTestCase { private static final String DEPLOYMENT = "JdbcRealmDeployment"; private static final Provider PROVIDER = new WildFlyElytronProvider(); private static final String DATASOURCE_NAME = "JdbcRealmTest"; @Deployment(name = DEPLOYMENT) public static WebArchive deployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war"); war.addClasses(JdbcTestServlet.class); war.addAsWebInfResource(JdbcRealmTestCase.class.getPackage(), "jdbc-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT), "jboss-web.xml") .addAsManifestResource(createPermissionsXmlAsset( new ElytronPermission("getSecurityDomain")), "permissions.xml"); return war; } @Test @OperateOnDeployment(DEPLOYMENT) public void testClearPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userOne%40wildfly.org", "Red", "Green"), "userOne@Clear", "passwordOne", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testBCRYPTPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userTwo%40wildfly.org", "Black", "Blue"), "userTwo@BCRYPT", "passwordTwo", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testCombinedClearPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userThree%40wildfly.org", "Yellow", "Orange"), "userThree@Combined", "passwordThree", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testCombinedBCRYPTPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userFour%40wildfly.org", "White", "Purple"), "userFour@Combined", "passwordFour", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testBCRYPTHexPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userFive%40wildfly.org", "Violet", "Amber"), "userFive@BCRYPT_HEX", "passwordFive", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testCombinedBCRYPTHexPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userSix%40wildfly.org", "Pink", "Gold"), "userSix@Combined", "passwordSix", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testModularCryptPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userSeven%40wildfly.org", "Grey", "Indigo"), "userSeven@MODULAR_CRYPT", "passwordSeven", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testCombinedModularCryptPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userEight%40wildfly.org", "Lilac", "Bergundy"), "userEight@Combined", "passwordEight", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testBCRYPTCharsetPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userNine%40wildfly.org", "Red"), "userNine@BCRYPT_CHARSET", "password密码", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } @Test @OperateOnDeployment(DEPLOYMENT) public void testBCRYPTCharsetHexEncodedPassword_Success(@ArquillianResource URL webAppURL) throws Exception { String result = Utils.makeCallWithBasicAuthn(convert(webAppURL, "userTen%40wildfly.org", "Red"), "userTen@BCRYPT_CHARSET_HEX", "password密码", SC_OK); assertEquals(JdbcTestServlet.RESPONSE_BODY, result); } private URL convert(URL original, final String email, final String... colours) throws Exception { StringBuilder sb = new StringBuilder(original.toExternalForm()) .append(JdbcTestServlet.SERVLET_PATH.substring(1)) .append('?') .append("email=").append(email); for (String colour : colours) { sb.append("&favourite-colours=").append(colour); } return new URL(sb.toString()); } static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] elements = new ConfigurableElement[18]; // Clear Realm elements[0] = JdbcSecurityRealm.builder("clear_realm") .withPrincipalQuery(DATASOURCE_NAME, "select password, email from clear_identities where name = ?") .withPasswordMapper("clear-password-mapper", null, 1, -1, -1) .withAttributeMapper("email", 2) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // Clear Realm Constant Realm Mapper elements[1] = ConstantRealmMapper.newInstance("clear_realm_mapper", "clear_realm"); // BCRYPT Realm elements[2] = JdbcSecurityRealm.builder("bcrypt_realm") .withPrincipalQuery(DATASOURCE_NAME, "select hash, salt, iteration_count, email from bcrypt_identities where name = ?") .withPasswordMapper("bcrypt-mapper", null, 1, 2, 3) .withAttributeMapper("email", 4) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // BCRYPT Realm Mapper elements[3] = ConstantRealmMapper.newInstance("bcrypt_realm_mapper", "bcrypt_realm"); // BCRYPT Hex Realm elements[4] = JdbcSecurityRealm.builder("bcrypt_hex_realm") .withPrincipalQuery(DATASOURCE_NAME, "select hash, salt, iteration_count, email from bcrypt_hex_identities where name = ?") .withPasswordMapper("bcrypt-mapper", null, 1, Encoding.HEX, 2, Encoding.HEX, 3) .withAttributeMapper("email", 4) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // BCRYPT Hex Mapper elements[5] = ConstantRealmMapper.newInstance("bcrypt_hex_realm_mapper", "bcrypt_hex_realm"); // BCRYPT Charset Realm elements[6] = JdbcSecurityRealm.builder("bcrypt_charset_realm") .withHashCharset("GB2312") .withPrincipalQuery(DATASOURCE_NAME, "select hash, salt, iteration_count, email from bcrypt_identities_charset where name = ?") .withPasswordMapper("bcrypt-mapper", null, 1, 2, 3) .withAttributeMapper("email", 4) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // BCRYPT Charset Mapper elements[7] = ConstantRealmMapper.newInstance("bcrypt_charset_realm_mapper", "bcrypt_charset_realm"); // BCRYPT Charset Hex Realm elements[8] = JdbcSecurityRealm.builder("bcrypt_charset_hex_realm") .withHashCharset("GB2312") .withPrincipalQuery(DATASOURCE_NAME, "select hash, salt, iteration_count, email from bcrypt_hex_identities_charset where name = ?") .withPasswordMapper("bcrypt-mapper", null, 1, Encoding.HEX, 2, Encoding.HEX, 3) .withAttributeMapper("email", 4) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // BCRYPT Charset Hex Mapper elements[9] = ConstantRealmMapper.newInstance("bcrypt_charset_hex_realm_mapper", "bcrypt_charset_hex_realm"); // Modular Crypt Realm elements[10] = JdbcSecurityRealm.builder("modular_crypt_realm") .withPrincipalQuery(DATASOURCE_NAME, "select password, email from modular_crypt_identities where name = ?") .withPasswordMapper("modular-crypt-mapper", null, 1, -1, -1) .withAttributeMapper("email", 2) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // Modular Crypt Mapper elements[11] = ConstantRealmMapper.newInstance("modular_crypt_realm_mapper", "modular_crypt_realm"); // Combined Realm elements[12] = JdbcSecurityRealm.builder("combined_realm") .withPrincipalQuery(DATASOURCE_NAME, "select password, email from clear_identities where name = ?") .withPasswordMapper("clear-password-mapper", null, 1, -1, -1) .withAttributeMapper("email", 2) .build() .withPrincipalQuery(DATASOURCE_NAME, "select hash, salt, iteration_count, email from bcrypt_identities where name = ?") .withPasswordMapper("bcrypt-mapper", null, 1, 2, 3) .withAttributeMapper("email", 4) .build() .withPrincipalQuery(DATASOURCE_NAME, "select hash, salt, iteration_count, email from bcrypt_hex_identities where name = ?") .withPasswordMapper("bcrypt-mapper", null, 1, Encoding.HEX, 2, Encoding.HEX, 3) .withAttributeMapper("email", 4) .build() .withPrincipalQuery(DATASOURCE_NAME, "select password, email from modular_crypt_identities where name = ?") .withPasswordMapper("modular-crypt-mapper", null, 1, -1, -1) .withAttributeMapper("email", 2) .build() .withPrincipalQuery(DATASOURCE_NAME, "select colour from colours where name = ?") .withAttributeMapper("favourite-colours", 1) .build() .build(); // Combined Realm Mapper elements[13] = ConstantRealmMapper.newInstance("combined_realm_mapper", "combined_realm"); // RegEx RealmMapper elements[14] = MappedRegexRealmMapper.builder("regex-mapper") .withPattern(".+?@(.+)") // Reluctantly match all characters up to and including the first '@', all remaining characters into a single capturing group. .withRealmMapping("Clear", "clear_realm") .withRealmMapping("BCRYPT", "bcrypt_realm") .withRealmMapping("BCRYPT_HEX", "bcrypt_hex_realm") .withRealmMapping("MODULAR_CRYPT", "modular_crypt_realm") .withRealmMapping("Combined", "combined_realm") .withRealmMapping("BCRYPT_CHARSET", "bcrypt_charset_realm") .withRealmMapping("BCRYPT_CHARSET_HEX", "bcrypt_charset_hex_realm") .build(); // Name Rewriter elements[15] = RegexPrincipalTransformer.builder("realm-stripper") .withPattern("@.+") .withReplacement("") .build(); // Security Domain elements[16] = SimpleSecurityDomain.builder() .withName("JdbcTestDomain") .withPostRealmPrincipalTransformer("realm-stripper") .withRealmMapper("regex-mapper") .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("clear_realm").build(), SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("bcrypt_realm").build(), SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("bcrypt_hex_realm").build(), SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("modular_crypt_realm").build(), SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("combined_realm").build(), SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("bcrypt_charset_realm").build(), SimpleSecurityDomain.SecurityDomainRealm.builder().withRealm("bcrypt_charset_hex_realm").build()) .build(); // Undertow Application Security Domain elements[17] = UndertowApplicationSecurityDomain.builder() .withName(DEPLOYMENT) .withSecurityDomain("JdbcTestDomain") .build(); return elements; } } static class DataSourcesSetup extends AbstractDataSourceServerSetupTask { @Override protected DataSource[] getDataSourceConfigurations(ManagementClient managementClient, String containerId) { return new DataSource[]{new DataSource.Builder() .name(DATASOURCE_NAME) .connectionUrl( "jdbc:h2:tcp://" + Utils.getSecondaryTestAddress(managementClient) + "/mem:" + DATASOURCE_NAME) .driver("h2").username("sa").password("sa").build()}; } } /** * H2 DB configuration setup task. */ static class DBSetup implements ServerSetupTask { private Server server; public void setup(ManagementClient managementClient, String containerId) throws Exception { server = Server.createTcpServer("-tcpAllowOthers").start(); final String dbUrl = "jdbc:h2:mem:" + DATASOURCE_NAME + ";DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"; final Connection conn = DriverManager.getConnection(dbUrl, "sa", "sa"); executeUpdate(conn, "create table clear_identities (name VARCHAR PRIMARY KEY, password VARCHAR, email VARCHAR)"); executeUpdate(conn, "create table bcrypt_identities (name VARCHAR PRIMARY KEY, hash VARCHAR, salt VARCHAR, iteration_count INT, email VARCHAR)"); executeUpdate(conn, "create table bcrypt_hex_identities (name VARCHAR PRIMARY KEY, hash VARCHAR, salt VARCHAR, iteration_count INT, email VARCHAR)"); executeUpdate(conn, "create table colours (name VARCHAR, colour VARCHAR)"); executeUpdate(conn, "create table modular_crypt_identities (name VARCHAR PRIMARY KEY, password VARCHAR, email VARCHAR)"); executeUpdate(conn, "create table bcrypt_identities_charset (name VARCHAR PRIMARY KEY, hash VARCHAR, salt VARCHAR, iteration_count INT, email VARCHAR)"); executeUpdate(conn, "create table bcrypt_hex_identities_charset (name VARCHAR PRIMARY KEY, hash VARCHAR, salt VARCHAR, iteration_count INT, email VARCHAR)"); addClearUser(conn, "userOne", "passwordOne", "userOne@wildfly.org", "Red", "Green"); addBCryptUser(conn, "userTwo", "passwordTwo", "userTwo@wildfly.org", "bcrypt_identities", false, "Black", "Blue"); addClearUser(conn, "userThree", "passwordThree", "userThree@wildfly.org", "Yellow", "Orange"); addBCryptUser(conn, "userFour", "passwordFour", "userFour@wildfly.org", "bcrypt_identities", false, "White", "Purple"); addBCryptUser(conn, "userFive", "passwordFive", "userFive@wildfly.org", "bcrypt_hex_identities", true, "Violet", "Amber"); addBCryptUser(conn, "userSix", "passwordSix", "userSix@wildfly.org", "bcrypt_hex_identities", true, "Pink", "Gold"); addModularCryptUser(conn, "userSeven", "passwordSeven", "userSeven@wildfly.org", "Grey", "Indigo"); addModularCryptUser(conn, "userEight", "passwordEight", "userEight@wildfly.org", "Lilac", "Bergundy"); addBCryptUser(conn, "userNine", "password密码", "userNine@wildfly.org", "bcrypt_identities_charset", false, Charset.forName("GB2312"), "Red"); addBCryptUser(conn, "userTen", "password密码", "userTen@wildfly.org", "bcrypt_hex_identities_charset", true, Charset.forName("GB2312"), "Red"); conn.close(); } private void addClearUser(final Connection conn, final String username, final String password, final String eMail, final String... colours) throws SQLException { executeUpdate(conn, String.format("insert into clear_identities VALUES ('%s', '%s', '%s')", username, password, eMail)); addFavouriteColours(conn, username, colours); } private void addBCryptUser(final Connection conn, final String username, final String password, final String eMail, String tableName, final boolean hexEncoded,final String... colours) throws Exception { addBCryptUser(conn, username, password, eMail, tableName, hexEncoded, StandardCharsets.UTF_8, colours); } private void addBCryptUser(final Connection conn, final String username, final String password, final String eMail, String tableName, final boolean hexEncoded, final Charset hashCharset, final String... colours) throws Exception { int iterationCount = 10; byte[] salt = new byte[BCryptPassword.BCRYPT_SALT_SIZE]; SecureRandom random = new SecureRandom(); random.nextBytes(salt); PasswordFactory passwordFactory = PasswordFactory.getInstance(BCryptPassword.ALGORITHM_BCRYPT, PROVIDER); IteratedSaltedPasswordAlgorithmSpec iteratedAlgorithmSpec = new IteratedSaltedPasswordAlgorithmSpec(iterationCount, salt); EncryptablePasswordSpec encryptableSpec = new EncryptablePasswordSpec(password.toCharArray(), iteratedAlgorithmSpec, hashCharset); BCryptPassword original = (BCryptPassword) passwordFactory.generatePassword(encryptableSpec); byte[] hash = original.getHash(); Encoder encoder = Base64.getEncoder(); final String encodedHash; final String encodedSalt; if (hexEncoded) { encodedHash = ByteIterator.ofBytes(hash).hexEncode().drainToString(); encodedSalt = ByteIterator.ofBytes(salt).hexEncode().drainToString(); } else { encodedHash = encoder.encodeToString(hash); encodedSalt = encoder.encodeToString(salt); } executeUpdate(conn, String.format("insert into %s VALUES ('%s', '%s', '%s', %d, '%s')", tableName, username, encodedHash, encodedSalt, iterationCount, eMail)); addFavouriteColours(conn, username, colours); } private void addModularCryptUser(final Connection conn, final String username, final String password, final String eMail, final String... colours) throws Exception { PasswordFactory passwordFactory = PasswordFactory.getInstance(BSDUnixDESCryptPassword.ALGORITHM_BSD_CRYPT_DES, PROVIDER); int iterationCount = BSDUnixDESCryptPassword.DEFAULT_ITERATION_COUNT; byte[] salt = new byte[BSDUnixDESCryptPassword.BSD_CRYPT_DES_SALT_SIZE]; SecureRandom random = new SecureRandom(); random.nextBytes(salt); IteratedSaltedPasswordAlgorithmSpec iteratedAlgorithmSpec = new IteratedSaltedPasswordAlgorithmSpec(iterationCount, salt); EncryptablePasswordSpec encryptableSpec = new EncryptablePasswordSpec(password.toCharArray(), iteratedAlgorithmSpec); BSDUnixDESCryptPassword original = (BSDUnixDESCryptPassword) passwordFactory.generatePassword(encryptableSpec); String encoded = ModularCrypt.encodeAsString(original); executeUpdate(conn, String.format("insert into modular_crypt_identities VALUES ('%s', '%s', '%s')", username, encoded, eMail)); addFavouriteColours(conn, username, colours); } private void addFavouriteColours(final Connection conn, final String username, final String... colours) throws SQLException { for (String colour : colours) { executeUpdate(conn, String.format("insert into colours VALUES ('%s', '%s')", username, colour)); } } public void tearDown(ManagementClient managementClient, String containerId) throws Exception { server.shutdown(); server = null; } private void executeUpdate(Connection connection, String query) throws SQLException { final Statement statement = connection.createStatement(); statement.executeUpdate(query); statement.close(); } } }
25,781
54.32618
238
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/FilesystemRealmEncryptedTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static jakarta.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import java.net.MalformedURLException; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Full authentication tests for Elytron Encrypted Filesystem Realm. * * @author Ashpan Raskar <araskar@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({FilesystemRealmEncryptedTestCase.SetUpTask.class}) public class FilesystemRealmEncryptedTestCase { private static final String DEPLOYMENT_ENCRYPTED = "filesystemRealmEncrypted"; private static final String USER = "plainUser"; private static final String PASSWORD = "secretPassword"; @Deployment(name = DEPLOYMENT_ENCRYPTED) public static WebArchive deploymentWithCharsetAndEncoded() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT_ENCRYPTED + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(FilesystemRealmEncryptedTestCase.class.getPackage(), "filesystem-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT_ENCRYPTED), "jboss-web.xml"); return war; } /** * * Test Filesystem realm when choosing to encrypt it. */ @Test @OperateOnDeployment(DEPLOYMENT_ENCRYPTED) public void testEncryptionPass(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_OK); } /** * * Test Filesystem realm when choosing to encrypt it with a bad credential. */ @Test @OperateOnDeployment(DEPLOYMENT_ENCRYPTED) public void testEncryptionCredentialFail(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER+"123", PASSWORD, SC_UNAUTHORIZED); } private URL prepareURL(URL url) throws MalformedURLException { return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); } static class SetUpTask implements ServerSetupTask { private static final String REALM_NAME = "fsRealmEncrypted"; private static final String DOMAIN_NAME = "fsDomainEncrypted"; private static final String CREDENTIAL_STORE = "mycredstore"; private static final String INVALID_CREDENTIAL_STORE = "invalidcredstore"; private static final String SECRET_KEY = "key"; private static ManagementClient managementClient; @Override public void setup(ManagementClient managementClient, java.lang.String s) throws Exception { setUpTestDomain(DOMAIN_NAME, REALM_NAME, "filesystem", USER, PASSWORD, DEPLOYMENT_ENCRYPTED, CREDENTIAL_STORE, SECRET_KEY, INVALID_CREDENTIAL_STORE); SetUpTask.managementClient = managementClient; ServerReload.reloadIfRequired(managementClient); } private void setUpTestDomain(String domainName, String realmName, String path, String username, String password, String deployment, String credentialStore, String secretKey, String invalidCredentialStore) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%1$s:add(path=%1$s.cs, relative-to=jboss.server.config.dir, create=true, populate=true)", credentialStore)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s,relative-to=jboss.server.config.dir, credential-store=%s, secret-key=%s)", realmName, path, credentialStore, secretKey)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%1$s:set-password(identity=%2$s, digest={algorithm=digest-md5, realm=%1$s, password=%3$s})", realmName, username, password)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=Roles, value=[JBossAdmin])", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName)); cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%s:add(security-domain=%s)", deployment, domainName)); } } @Override public void tearDown(ManagementClient managementClient, java.lang.String s) throws Exception { SetUpTask.managementClient = managementClient; tearDownDomain(DEPLOYMENT_ENCRYPTED, DOMAIN_NAME, REALM_NAME, USER, CREDENTIAL_STORE, INVALID_CREDENTIAL_STORE); ServerReload.reloadIfRequired(managementClient); } private void tearDownDomain(String deployment, String domainName, String realmName, String username, String credentialStore, String invalidCredentialStore) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deployment)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove()", realmName)); cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%s:remove()", credentialStore)); cli.sendLine(String.format("/subsystem=elytron/secret-key-credential-store=%s:remove()", invalidCredentialStore)); } } } }
8,238
51.14557
231
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/FilesystemRealmIntegrityTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.SimpleSecuredServlet; import org.jboss.as.test.integration.security.common.servlets.SimpleServlet; import org.jboss.as.test.shared.ServerReload; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Full authentication tests for Elytron Integrity Enabled Filesystem Realm. * * @author Ashpan Raskar <araskar@redhat.com> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({FilesystemRealmIntegrityTestCase.SetUpTask.class}) public class FilesystemRealmIntegrityTestCase { private static final String DEPLOYMENT = "filesystemRealmIntegrity"; private static final String USER = "plainUser"; private static final String PASSWORD = "secretPassword"; @Deployment(name = DEPLOYMENT) public static WebArchive deploymentWithIntegrity() { final WebArchive war = ShrinkWrap.create(WebArchive.class, DEPLOYMENT + ".war"); war.addClasses(SimpleServlet.class); war.addClasses(SimpleSecuredServlet.class); war.addAsWebInfResource(FilesystemRealmTestCase.class.getPackage(), "filesystem-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(DEPLOYMENT), "jboss-web.xml"); return war; } /** * * Test Filesystem realm correctly handles integrity being enabled */ @Test @OperateOnDeployment(DEPLOYMENT) public void testIntegrityPass(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_OK); } /** * * Test Filesystem realm correctly handles incorrect credentials when integrity is enabled */ @Test @OperateOnDeployment(DEPLOYMENT) public void testIntegrityFail(@ArquillianResource URL webAppURL) throws Exception { URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, PASSWORD+"123", SC_UNAUTHORIZED); } /** * * Test Filesystem realm correctly handles a keypair being changed */ @Test @OperateOnDeployment(DEPLOYMENT) public void testIntegrityKeyStoreChange(@ArquillianResource URL webAppURL) throws Exception { SetUpTask.setupNewKeystoreAlias(SetUpTask.REALM_NAME, SetUpTask.NEW_KEYSTORE_ALIAS); URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_OK); SetUpTask.tearDownNewKeystoreAlias(SetUpTask.REALM_NAME, SetUpTask.KEYSTORE_ALIAS); } /** * * Test Filesystem realm throws an error when the signature is unexpectedly modified */ @Test @OperateOnDeployment(DEPLOYMENT) public void testIntegrityInvalidSignature(@ArquillianResource URL webAppURL) throws Exception { String identityFile = "./target/wildfly/standalone/configuration/filesystem/p/l/plainuser-OBWGC2LOKVZWK4Q.xml"; Path path = Paths.get(identityFile); Charset charset = StandardCharsets.UTF_8; String content = Files.readString(path, charset); content = content.replaceAll("SignatureValue", "INVALID_SIGNATURE"); Files.write(path, content.getBytes(charset)); URL url = prepareURL(webAppURL); Utils.makeCallWithBasicAuthn(url, USER, PASSWORD, SC_UNAUTHORIZED); content = content.replaceAll("INVALID_SIGNATURE", "SignatureValue"); Files.write(path, content.getBytes(charset)); } private URL prepareURL(URL url) throws MalformedURLException { return new URL(url.toExternalForm() + SimpleSecuredServlet.SERVLET_PATH.substring(1)); } static class SetUpTask implements ServerSetupTask { private static final String REALM_NAME = "fsRealmIntegrity"; private static final String DOMAIN_NAME = "fsDomainIntegrity"; private static final String KEYSTORE_NAME = "keystore"; private static final String KEYSTORE_ALIAS = "keystoreAlias"; private static final String NEW_KEYSTORE_ALIAS = "newKeystoreAlias"; private static ManagementClient managementClient; @Override public void setup(ManagementClient managementClient, java.lang.String s) throws Exception { setUpTestDomain(DOMAIN_NAME, REALM_NAME, "filesystem", USER, PASSWORD, DEPLOYMENT, KEYSTORE_NAME, KEYSTORE_ALIAS, NEW_KEYSTORE_ALIAS); SetUpTask.managementClient = managementClient; ServerReload.reloadIfRequired(managementClient); } private void setUpTestDomain(String domainName, String realmName, String fsPath, String username, String password, String deployment, String keyStoreName, String keyStoreAlias, String newKeyStoreAlias) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/key-store=%1$s:add(path=%1$s, relative-to=jboss.server.config.dir, type=JKS, credential-reference={clear-text=%2$s})", keyStoreName, password)); cli.sendLine(String.format("/subsystem=elytron/key-store=%1$s:generate-key-pair(alias=%2$s,algorithm=RSA,key-size=1024,validity=365,distinguished-name=\"CN=%2$s\")", keyStoreName, keyStoreAlias)); cli.sendLine(String.format("/subsystem=elytron/key-store=%1$s:generate-key-pair(alias=%2$s,algorithm=RSA,key-size=1024,validity=365,distinguished-name=\"CN=%2$s\")", keyStoreName, newKeyStoreAlias)); cli.sendLine(String.format("/subsystem=elytron/key-store=%s:store()", keyStoreName)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add(path=%s, relative-to=jboss.server.config.dir, key-store=%s, key-store-alias=%s)", realmName, fsPath, keyStoreName, keyStoreAlias)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%1$s:set-password(identity=%2$s, digest={algorithm=digest-md5, realm=%1$s, password=%3$s})", realmName, username, password)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=Roles, value=[JBossAdmin])", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%1$s:add(realms=[{realm=%2$s}],default-realm=%2$s,permission-mapper=default-permission-mapper)", domainName, realmName)); cli.sendLine(String.format( "/subsystem=undertow/application-security-domain=%s:add(security-domain=%s)", deployment, domainName)); } } private static void setupNewKeystoreAlias(String realmName, String newKeyStoreAlias) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:write-attribute(name=key-store-alias, value=%s)", realmName, newKeyStoreAlias)); } ServerReload.reloadIfRequired(managementClient); try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:update-key-pair()", realmName)); } ServerReload.reloadIfRequired(managementClient); } private static void tearDownNewKeystoreAlias(String realmName, String keyStoreAlias) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:write-attribute(name=key-store-alias, value=%s)", realmName, keyStoreAlias)); } ServerReload.reloadIfRequired(managementClient); try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:update-key-pair()", realmName)); } ServerReload.reloadIfRequired(managementClient); } @Override public void tearDown(ManagementClient managementClient, java.lang.String s) throws Exception { tearDownDomain(DEPLOYMENT, DOMAIN_NAME, REALM_NAME, USER, KEYSTORE_NAME, KEYSTORE_ALIAS, NEW_KEYSTORE_ALIAS); ServerReload.reloadIfRequired(managementClient); } private void tearDownDomain(String deployment, String domainName, String realmName, String username, String keyStoreName, String keyStoreAlias, String newKeyStoreAlias) throws Exception { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/subsystem=undertow/application-security-domain=%s:remove()", deployment)); cli.sendLine(String.format("/subsystem=elytron/security-domain=%s:remove()", domainName)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove-identity(identity=%s)", realmName, username)); cli.sendLine(String.format("/subsystem=elytron/filesystem-realm=%s:remove()", realmName)); cli.sendLine(String.format("/subsystem=elytron/key-store=%s:remove-alias(alias=%s)", keyStoreName, newKeyStoreAlias)); cli.sendLine(String.format("/subsystem=elytron/key-store=%s:remove-alias(alias=%s)", keyStoreName, keyStoreAlias)); cli.sendLine(String.format("/subsystem=elytron/key-store=%s:store()", keyStoreName)); cli.sendLine(String.format("/subsystem=elytron/key-store=%s:remove()", keyStoreName)); } } } }
11,847
52.369369
228
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/AggregateRealmWithTransformerTestCase.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.hamcrest.MatcherAssert; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.AggregateSecurityRealm; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.FileSystemRealm; import org.wildfly.test.security.common.elytron.PropertiesRealm; import org.wildfly.test.security.common.elytron.RegexPrincipalTransformer; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.UserWithAttributeValues; import org.wildfly.test.security.common.elytron.servlet.AttributePrintingServlet; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.hamcrest.CoreMatchers.is; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertAttribute; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertAuthenticationFailed; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertAuthenticationSuccess; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertInRole; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertNoRoleAssigned; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertNotInRole; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.getAttributes; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.prepareRolesPrintingURL; /** * Test scenarios about Elytron Aggregate Realm usage with Principal transformer * * Most of scenarios are tested for two variants: * * Same type of aggregated realms * ** Authentication realm uses the same type of realm as authorization realm. Specifically, all realms are filesystem-realm. * ** These tests have "_sameTypeRealm" suffix * * Different type of aggregated realms * ** Authentication realm uses different type of realm then authorization realm. Specifically, authentication realm * is properties-realm and authorization realm is filesystem-realm. * ** These tests have "_differentTypeRealm" suffix * * All these scenarios use aggregated-realm with principal transformer. User A is transformed to user B by principal transformer. * Example of the configuration: * /subsystem=elytron/regex-principal-transformer=custom-pt:add(pattern=Auser,replacement=Buser) * /subsystem=elytron/aggregate-realm=custom-aggregate-realm:add(authentication-realm=elytron-authn-properties-realm,authorization-realm=elytron-authz-realm,principal-transformer=custom-pt) * * https://issues.jboss.org/browse/WFLY-12202 * https://issues.jboss.org/browse/WFCORE-4496 * https://issues.jboss.org/browse/ELY-1829 */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AggregateRealmWithTransformerTestCase.SetupTask.class}) public class AggregateRealmWithTransformerTestCase { private static final String AGGREGATE_REALM_SAME_TYPE_NAME = "elytron-aggregate-realm-same-type"; private static final String AGGREGATE_REALM_DIFFERENT_TYPE_NAME = "elytron-aggregate-realm-different-type"; private static final String AGGREGATE_REALM_ATTRIBUTES_NAME = "elytron-aggregate-realm-attributes"; private static final String FILESYSTEM_REALM_1_AUTHN_NAME = "elytron-authn-filesystem-realm"; private static final String PROPERTIES_REALM_AUTHN_NAME = "elytron-authn-properties-realm"; private static final String FILESYSTEM_REALM_2_AUTHZ_NAME = "elytron-authz-filesystem-realm-1"; private static final String FILESYSTEM_REALM_3_AUTHZ_NAME = "elytron-authz-filesystem-realm-2"; private static final String PRINCIPAL_TRANSFORMER = "elytron-custom-principal-transformer"; private static final String REPLACE_STRING = "AUser"; private static final String REPLACE_BY = "BUser"; private static final String A_USER_WITH_ALL = "AUserWithRolesWithAttributesWithPassInAuthz"; private static final String B_USER_WITH_ALL = "BUserWithRolesWithAttributesWithPassInAuthz"; private static final String A_USER_WITHOUT_PASS_IN_AUTHZ = "AUserWithoutPassInAuthz"; private static final String B_USER_WITHOUT_PASS_IN_AUTHZ = "BUserWithoutPassInAuthz"; private static final String A_USERS_WITHOUT_ROLES_IN_AUTHZ = "AUsersWithoutRolesInAuthz"; private static final String B_USERS_WITHOUT_ROLES_IN_AUTHZ = "BUsersWithoutRolesInAuthz"; private static final String A_USER_A_WITHOUT_ROLES_IN_AUTHZ = "AUserAWithoutRolesInAuthz"; private static final String B_USER_A_WITHOUT_ROLES_IN_AUTHZ = "BUserAWithoutRolesInAuthz"; private static final String A_USER_B_WITHOUT_ROLES_IN_AUTHZ = "AUserBWithoutRolesInAuthz"; private static final String B_USER_B_WITHOUT_ROLES_IN_AUTHZ = "BUserBWithoutRolesInAuthz"; private static final String A_USER_WITHOUT_B_USER_IN_ANY_REALM = "AUserWithoutBUserInAnyRealm"; private static final String NON_DEFINED_B_USER_WITHOUT_B_USER_IN_ANY_REALM = "BUserWithoutBUserInAnyRealm"; private static final String A_USER_WITHOUT_B_USER_IN_AUTHZ = "AUserWithoutBUserInAuthz"; private static final String B_USER_WITHOUT_B_USER_IN_AUTHZ = "BUserWithoutBUserInAuthz"; private static final String A_1_PASSWORD = "password1"; private static final String A_2_PASSWORD = "password2"; private static final String A_3_PASSWORD = "password3"; private static final String B_1_PASSWORD = "password4"; private static final String B_2_PASSWORD = "password5"; private static final String B_3_PASSWORD = "password6"; public static final String ROLE_1 = "Group1"; public static final String ROLE_2 = "Group2"; public static final String ROLE_3 = "Group3"; public static final String ROLE_4 = "Group4"; public static final String ROLE_5 = "Group5"; public static final String ROLE_6 = "Group6"; private static final String[] ALL_TESTED_ROLES = {ROLE_1, ROLE_2, ROLE_3, ROLE_4, ROLE_5, ROLE_6}; static final String QUERY_ROLES; static { final List<NameValuePair> qparams = new ArrayList<>(); for (final String role : ALL_TESTED_ROLES) { qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role)); } QUERY_ROLES = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8); } @Deployment(name = AGGREGATE_REALM_SAME_TYPE_NAME) public static WebArchive deploymentSameType() { return deployment(AGGREGATE_REALM_SAME_TYPE_NAME); } @Deployment(name = AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public static WebArchive deploymentDifferentType() { return deployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME); } private static WebArchive deployment(String name) { final WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war"); war.addClasses(RolePrintingServlet.class); war.addClasses(RoleServlets.class, RoleServlets.Role1Servlet.class, RoleServlets.Role2Servlet.class, RoleServlets.Role3Servlet.class, RoleServlets.Role4Servlet.class, RoleServlets.Role5Servlet.class, RoleServlets.Role6Servlet.class); war.addAsWebInfResource(AggregateRealmWithTransformerTestCase.class.getPackage(), "aggregate-realm-with-transformer-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(name), "jboss-web.xml"); return war; } @Deployment(name = AGGREGATE_REALM_ATTRIBUTES_NAME) public static WebArchive deploymentAttributeAggregation() { final WebArchive war = ShrinkWrap.create(WebArchive.class, AGGREGATE_REALM_ATTRIBUTES_NAME + ".war"); war.addClasses(AttributePrintingServlet.class, RolePrintingServlet.class); war.addClasses(RoleServlets.class, RoleServlets.Role1Servlet.class, RoleServlets.Role2Servlet.class, RoleServlets.Role3Servlet.class, RoleServlets.Role4Servlet.class, RoleServlets.Role5Servlet.class, RoleServlets.Role6Servlet.class); war.addAsWebInfResource(AggregateRealmWithTransformerTestCase.class.getPackage(), "aggregate-realm-with-transformer-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(AGGREGATE_REALM_ATTRIBUTES_NAME), "jboss-web.xml"); war.addAsManifestResource(createPermissionsXmlAsset( new ElytronPermission("getSecurityDomain")), "permissions.xml"); return war; } /** * User A is in Group1 group in authentication realm, user B is in Group2 group in authentication realm. * User A is in Group3 group in authorization realm, user B is in Group4 group in authorization realm. * User A with correct password is authenticated and authorized for Group4 role only. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void userWithOneRole_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithOneRole_userInBothRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void userWithOneRole_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithOneRole_userInBothRealm(webAppURL); } private void userWithOneRole_userInBothRealm(URL webAppURL) throws Exception { testAssignedRoles(webAppURL, A_USER_WITH_ALL, A_1_PASSWORD, ROLE_4); testAssignedRoles(webAppURL, B_USER_WITH_ALL, B_1_PASSWORD, ROLE_4); checkRoleServlets(webAppURL.toExternalForm(), A_USER_WITH_ALL, A_1_PASSWORD); checkRoleServlets(webAppURL.toExternalForm(), B_USER_WITH_ALL, B_1_PASSWORD); } /** * Realm used for authorization defines different passwords for the users than realm for authentication * User A with correct username but with password for A from authorization-realm is not authenticated * User A with correct username but with password for B from authorization-realm is not authenticated * User A with correct username but with password for B from authentication-realm is not authenticated * User A with correct username and with password for A from authentication-realm is authenticated */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_differentPasswords_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_differentPasswords_userInBothRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_differentPasswords_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_differentPasswords_userInBothRealm(webAppURL); } private void principal_differentPasswords_userInBothRealm(URL webAppURL) throws Exception { // User A assertAuthenticationSuccess(webAppURL, A_USER_WITH_ALL, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITH_ALL, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITH_ALL, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITH_ALL, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, B_USER_WITH_ALL, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITH_ALL, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationSuccess(webAppURL, B_USER_WITH_ALL, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITH_ALL, B_2_PASSWORD, QUERY_ROLES); } /** * Realm for authorization does not include user's (both A and B) password * User A with correct username and password is authenticated */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_correctPassword_userOnlyInAuthzRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_correctPassword_userOnlyInAuthzRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_correctPassword_userOnlyInAuthzRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_correctPassword_userOnlyInAuthzRealm(webAppURL); } private void principal_correctPassword_userOnlyInAuthzRealm(URL webAppURL) throws Exception { // Roles testAssignedRoles(webAppURL, A_USER_WITHOUT_PASS_IN_AUTHZ, A_1_PASSWORD, ROLE_4); testAssignedRoles(webAppURL, B_USER_WITHOUT_PASS_IN_AUTHZ, B_1_PASSWORD, ROLE_4); checkRoleServlets(webAppURL.toExternalForm(), A_USER_WITHOUT_PASS_IN_AUTHZ, A_1_PASSWORD); checkRoleServlets(webAppURL.toExternalForm(), B_USER_WITHOUT_PASS_IN_AUTHZ, B_1_PASSWORD); // User A assertAuthenticationSuccess(webAppURL, A_USER_WITHOUT_PASS_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_PASS_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_PASS_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_PASS_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, B_USER_WITHOUT_PASS_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITHOUT_PASS_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationSuccess(webAppURL, B_USER_WITHOUT_PASS_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITHOUT_PASS_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); } /** * No roles in authorization realm. User with correct password is authenticated but not authorized. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_usersWithNoRoles_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_usersWithNoRoles_userInBothRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_usersWithNoRoles_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_usersWithNoRoles_userInBothRealm(webAppURL); } private void principal_usersWithNoRoles_userInBothRealm(URL webAppURL) throws Exception { // User A assertNoRoleAssigned(webAppURL, A_USERS_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USERS_WITHOUT_ROLES_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USERS_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USERS_WITHOUT_ROLES_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, B_USERS_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USERS_WITHOUT_ROLES_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertNoRoleAssigned(webAppURL, B_USERS_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USERS_WITHOUT_ROLES_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); } /** * No roles for user B in authorization realm. * One role for user A in authorization realm. * User A with correct password is authenticated but not authorized. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_userBWithNoRoles_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_userBWithNoRoles_userInBothRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_userBWithNoRoles_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_userBWithNoRoles_userInBothRealm(webAppURL); } private void principal_userBWithNoRoles_userInBothRealm(URL webAppURL) throws Exception { // User A assertNoRoleAssigned(webAppURL, A_USER_B_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_B_WITHOUT_ROLES_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_B_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_B_WITHOUT_ROLES_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, B_USER_B_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_B_WITHOUT_ROLES_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertNoRoleAssigned(webAppURL, B_USER_B_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_B_WITHOUT_ROLES_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); } /** * No roles for user A in authorization realm. * One role for user B in authorization realm. * User A with correct password is authenticated and authorized. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_userAWithNoRoles_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_userAWithNoRoles_userInBothRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_userAWithNoRoles_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_userAWithNoRoles_userInBothRealm(webAppURL); } private void principal_userAWithNoRoles_userInBothRealm(URL webAppURL) throws Exception { // Roles testAssignedRoles(webAppURL, A_USER_A_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, ROLE_4); testAssignedRoles(webAppURL, B_USER_A_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, ROLE_4); checkRoleServlets(webAppURL.toExternalForm(), A_USER_A_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD); checkRoleServlets(webAppURL.toExternalForm(), B_USER_A_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD); // User A assertAuthenticationSuccess(webAppURL, A_USER_A_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_A_WITHOUT_ROLES_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_A_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_A_WITHOUT_ROLES_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, B_USER_A_WITHOUT_ROLES_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_A_WITHOUT_ROLES_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationSuccess(webAppURL, B_USER_A_WITHOUT_ROLES_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_A_WITHOUT_ROLES_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); } /** * B is not defined in authorization realm, but B is defined in authentication realm. * User A is authenticated with correct password. * User with correct password is authenticated but not authorized. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_transformedUserIsNotDefinedInAuthorizationRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_transformedUserIsNotDefinedInAuthorizationRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_transformedUserIsNotDefinedInAuthorizationRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_transformedUserIsNotDefinedInAuthorizationRealm(webAppURL); } private void principal_transformedUserIsNotDefinedInAuthorizationRealm(URL webAppURL) throws Exception { // User A assertNoRoleAssigned(webAppURL, A_USER_WITHOUT_B_USER_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_B_USER_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_B_USER_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_B_USER_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, B_USER_WITHOUT_B_USER_IN_AUTHZ, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITHOUT_B_USER_IN_AUTHZ, A_2_PASSWORD, QUERY_ROLES); assertNoRoleAssigned(webAppURL, B_USER_WITHOUT_B_USER_IN_AUTHZ, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITHOUT_B_USER_IN_AUTHZ, B_2_PASSWORD, QUERY_ROLES); } /** * B is not defined in both authorization realm and authentication realm * User A is authenticated with correct password. * User with correct password is authenticated but not authorized */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void principal_transformedUserIsNotDefinedInAnyRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_transformedUserIsNotDefinedInAnyRealm(webAppURL); } @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void principal_transformedUserIsNotDefinedInAnyRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { principal_transformedUserIsNotDefinedInAnyRealm(webAppURL); } private void principal_transformedUserIsNotDefinedInAnyRealm(URL webAppURL) throws Exception { // User A assertNoRoleAssigned(webAppURL, A_USER_WITHOUT_B_USER_IN_ANY_REALM, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_B_USER_IN_ANY_REALM, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_B_USER_IN_ANY_REALM, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITHOUT_B_USER_IN_ANY_REALM, B_2_PASSWORD, QUERY_ROLES); // User B assertAuthenticationFailed(webAppURL, NON_DEFINED_B_USER_WITHOUT_B_USER_IN_ANY_REALM, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, NON_DEFINED_B_USER_WITHOUT_B_USER_IN_ANY_REALM, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, NON_DEFINED_B_USER_WITHOUT_B_USER_IN_ANY_REALM, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, NON_DEFINED_B_USER_WITHOUT_B_USER_IN_ANY_REALM, B_2_PASSWORD, QUERY_ROLES); } /** * User A with correct username and password is authenticated, user A has attributes of B user from both authorization realms. * A user doesn't have any attribute of A user from any authorization realm. * All authorization realms are filesystem-realms (same approach as original tests from AggregateRealmTestCase) */ @Test @OperateOnDeployment(AGGREGATE_REALM_ATTRIBUTES_NAME) public void principal_twoAuthzRealms(@ArquillianResource URL webAppURL) throws Exception { // roles testAssignedRoles(webAppURL, A_USER_WITH_ALL, A_1_PASSWORD, ROLE_4); testAssignedRoles(webAppURL, B_USER_WITH_ALL, B_1_PASSWORD, ROLE_4); checkRoleServlets(webAppURL.toExternalForm(), A_USER_WITH_ALL, A_1_PASSWORD); checkRoleServlets(webAppURL.toExternalForm(), B_USER_WITH_ALL, B_1_PASSWORD); // User A authentication assertAuthenticationSuccess(webAppURL, A_USER_WITH_ALL, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITH_ALL, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITH_ALL, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, A_USER_WITH_ALL, B_2_PASSWORD, QUERY_ROLES); // User B authentication assertAuthenticationFailed(webAppURL, B_USER_WITH_ALL, A_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITH_ALL, A_2_PASSWORD, QUERY_ROLES); assertAuthenticationSuccess(webAppURL, B_USER_WITH_ALL, B_1_PASSWORD, QUERY_ROLES); assertAuthenticationFailed(webAppURL, B_USER_WITH_ALL, B_2_PASSWORD, QUERY_ROLES); // check attributes assertAttributes(webAppURL, A_USER_WITH_ALL, A_1_PASSWORD); assertAttributes(webAppURL, B_USER_WITH_ALL, B_1_PASSWORD); } private void checkRoleServlets(String webAppURL, String user, String password) throws Exception { Utils.makeCallWithBasicAuthn(new URL(webAppURL + ROLE_1), user, password, SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(new URL(webAppURL + ROLE_2), user, password, SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(new URL(webAppURL + ROLE_3), user, password, SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(new URL(webAppURL + ROLE_4), user, password, SC_OK); Utils.makeCallWithBasicAuthn(new URL(webAppURL + ROLE_5), user, password, SC_FORBIDDEN); Utils.makeCallWithBasicAuthn(new URL(webAppURL + ROLE_6), user, password, SC_FORBIDDEN); } private void assertAttributes(URL webAppURL, String user, String password) throws Exception { Properties properties = getAttributes(webAppURL, user, password); MatcherAssert.assertThat("Properties count", properties.size(), is(3)); assertAttribute(properties, "groups", ROLE_4); assertAttribute(properties, "Attribute1", "3", "4"); assertAttribute(properties, "Attribute2", "7", "8"); } private void testAssignedRoles(URL webAppURL, String username, String password, String... assignedRoles) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL, QUERY_ROLES); final String rolesResponse = Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_OK); final List<String> assignedRolesList = Arrays.asList(assignedRoles); for (String role : ALL_TESTED_ROLES) { if (assignedRolesList.contains(role)) { assertInRole(rolesResponse, role); } else { assertNotInRole(rolesResponse, role); } } } static class SetupTask extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); // prepare principal transcormer configurableElements.add(RegexPrincipalTransformer.builder(PRINCIPAL_TRANSFORMER) .withPattern(REPLACE_STRING) .withReplacement(REPLACE_BY) .build()); // properties-realm realm for authentication configurableElements.add(PropertiesRealm.builder() .withName(PROPERTIES_REALM_AUTHN_NAME) .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITH_ALL) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITH_ALL) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_correctPassword_userOnlyInAuthzRealm_sameTypeRealm() // and principal_correctPassword_userOnlyInAuthzRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_PASS_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITHOUT_PASS_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_usersWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_usersWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USERS_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USERS_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_userAWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_userAWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_A_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_A_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_userBWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_userBWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_B_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_B_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_transformedUserIsNotDefinedInAuthorizationRealm_sameTypeRealm() // and principal_transformedUserIsNotDefinedInAuthorizationRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_B_USER_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITHOUT_B_USER_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_transformedUserIsNotDefinedInAnyRealm_sameTypeRealm() // and principal_transformedUserIsNotDefinedInAnyRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_B_USER_IN_ANY_REALM) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .build()); // filesystem-realm realm for authentication configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_1_AUTHN_NAME) .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITH_ALL) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITH_ALL) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_correctPassword_userOnlyInAuthzRealm_sameTypeRealm() // and principal_correctPassword_userOnlyInAuthzRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_PASS_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITHOUT_PASS_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_usersWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_usersWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USERS_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USERS_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_userAWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_userAWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_A_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_A_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_userBWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_userBWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_B_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_B_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_transformedUserIsNotDefinedInAuthorizationRealm_sameTypeRealm() // and principal_transformedUserIsNotDefinedInAuthorizationRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_B_USER_IN_AUTHZ) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITHOUT_B_USER_IN_AUTHZ) .withPassword(B_1_PASSWORD) .withValues(ROLE_2) .build()) // for principal_transformedUserIsNotDefinedInAnyRealm_sameTypeRealm() // and principal_transformedUserIsNotDefinedInAnyRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_B_USER_IN_ANY_REALM) .withPassword(A_1_PASSWORD) .withValues(ROLE_1) .build()) .build()); // filesystem-realm realm for authorization configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_2_AUTHZ_NAME) .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITH_ALL) .withPassword(A_2_PASSWORD) .withValues(ROLE_3) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITH_ALL) .withPassword(B_2_PASSWORD) .withValues(ROLE_4) .build()) // for principal_correctPassword_userOnlyInAuthzRealm_sameTypeRealm() // and principal_correctPassword_userOnlyInAuthzRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITHOUT_PASS_IN_AUTHZ) .withValues(ROLE_3) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITHOUT_PASS_IN_AUTHZ) .withValues(ROLE_4) .build()) // for principal_usersWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_usersWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USERS_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_2_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USERS_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_2_PASSWORD) .build()) // for principal_userAWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_userAWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_A_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_2_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_A_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_2_PASSWORD) .withValues(ROLE_4) .build()) // for principal_userBWithNoRoles_userInBothRealm_sameTypeRealm() // and principal_userBWithNoRoles_userInBothRealm_differentTypeRealm() .withUser(UserWithAttributeValues.builder() .withName(A_USER_B_WITHOUT_ROLES_IN_AUTHZ) .withPassword(A_2_PASSWORD) .withValues(ROLE_3) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_B_WITHOUT_ROLES_IN_AUTHZ) .withPassword(B_2_PASSWORD) .build()) .build()); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_2_AUTHZ_NAME, A_USER_WITH_ALL, "Attribute1", "1", "2")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_2_AUTHZ_NAME, B_USER_WITH_ALL, "Attribute1", "3", "4")); // second file-system realm for authorization, used in attribute tests configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_3_AUTHZ_NAME) .withUser(UserWithAttributeValues.builder() .withName(A_USER_WITH_ALL) .withPassword(A_3_PASSWORD) .withValues(ROLE_5) .build()) .withUser(UserWithAttributeValues.builder() .withName(B_USER_WITH_ALL) .withPassword(B_3_PASSWORD) .withValues(ROLE_6) .build()) .build()); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_3_AUTHZ_NAME, A_USER_WITH_ALL, "Attribute2", "5", "6")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_3_AUTHZ_NAME, B_USER_WITH_ALL, "Attribute2", "7", "8")); // aggregate security realms configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_SAME_TYPE_NAME) .withAuthenticationRealm(FILESYSTEM_REALM_1_AUTHN_NAME) .withAuthorizationRealm(FILESYSTEM_REALM_2_AUTHZ_NAME) .withPrincipalTransformer(PRINCIPAL_TRANSFORMER) .build()); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withAuthenticationRealm(PROPERTIES_REALM_AUTHN_NAME) .withAuthorizationRealm(FILESYSTEM_REALM_2_AUTHZ_NAME) .withPrincipalTransformer(PRINCIPAL_TRANSFORMER) .build()); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_ATTRIBUTES_NAME) .withAuthenticationRealm(FILESYSTEM_REALM_1_AUTHN_NAME) .withAuthorizationRealms(FILESYSTEM_REALM_2_AUTHZ_NAME, FILESYSTEM_REALM_3_AUTHZ_NAME) .withPrincipalTransformer(PRINCIPAL_TRANSFORMER) .build()); // SimpleSecurityDomain configurableElements.add(SimpleSecurityDomain.builder() .withName(AGGREGATE_REALM_SAME_TYPE_NAME) .withDefaultRealm(AGGREGATE_REALM_SAME_TYPE_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(AGGREGATE_REALM_SAME_TYPE_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withDefaultRealm(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName(AGGREGATE_REALM_ATTRIBUTES_NAME) .withDefaultRealm(AGGREGATE_REALM_ATTRIBUTES_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(AGGREGATE_REALM_ATTRIBUTES_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); // Undertow application security domain configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(AGGREGATE_REALM_SAME_TYPE_NAME) .withSecurityDomain(AGGREGATE_REALM_SAME_TYPE_NAME) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withSecurityDomain(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(AGGREGATE_REALM_ATTRIBUTES_NAME) .withSecurityDomain(AGGREGATE_REALM_ATTRIBUTES_NAME) .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } } }
47,201
58.825095
189
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/AggregateRealmTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.realm; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertAttribute; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertAuthenticationFailed; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertInRole; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertNoRoleAssigned; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.assertNotInRole; import static org.wildfly.test.integration.elytron.realm.AggregateRealmUtil.prepareRolesPrintingURL; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.AggregateSecurityRealm; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.FileSystemRealm; import org.wildfly.test.security.common.elytron.PropertiesRealm; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.UserWithAttributeValues; import org.wildfly.test.security.common.elytron.servlet.AttributePrintingServlet; import org.wildfly.test.undertow.common.UndertowApplicationSecurityDomain; /** * Test case for Elytron Aggregate Realm. * * It tests two types of scenarios: * <ul> * <li>Both, authentication and authorization realm, is the same Elytron Realm type (both are Properties Realm for this test * case)</li> * <li>Both is the different Elytron Realm type (Filesystem Realm for authentication and Properties Realm for * authorization)</li> * </ul> * * Given: Secured application for printing roles secured by Aggregate Realm.<br> * * @author olukas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AggregateRealmTestCase.SetupTask.class}) public class AggregateRealmTestCase { private static final String AGGREGATE_REALM_SAME_TYPE_NAME = "elytron-aggregate-realm-same-type"; private static final String AGGREGATE_REALM_DIFFERENT_TYPE_NAME = "elytron-aggregate-realm-different-type"; private static final String AGGREGATE_ATTRIBUTES_NAME = "elytron-aggregate-realm-attributes"; private static final String USER_WITHOUT_ROLE = "userWithoutRole"; private static final String USER_WITH_ONE_ROLE = "userWithOneRole"; private static final String USER_WITH_TWO_ROLES = "userWithTwoRoles"; private static final String USER_WITH_DIFFERENT_ROLE_IN_DIFFERENT_REALM = "userWithDifferentRoleInDifferentRealm"; private static final String USER_ONLY_IN_AUTHORIZATION = "userOnlyInAuthorization"; private static final String WRONG_USER = "wrongUser"; private static final String USER_NO_ATTRIBUTES = "userWithoutAttributes"; private static final String USER_FIRST_ATTRIBUTES = "userFirstAttributes"; private static final String USER_SECOND_ATTRIBUTES = "userSecondAttributes"; private static final String USER_COMBINED_ATTRIBUTES = "userCombinedAttributes"; private static final String CORRECT_PASSWORD = "password"; private static final String AUTHORIZATION_REALM_PASSWORD = "passwordInAuthzRealm"; private static final String WRONG_PASSWORD = "wrongPassword"; private static final String EMPTY_PASSWORD = ""; private static final String ROLE_ADMIN = "Admin"; private static final String ROLE_USER = "User"; private static final String[] ALL_TESTED_ROLES = {ROLE_ADMIN, ROLE_USER}; static final String QUERY_ROLES; static { final List<NameValuePair> qparams = new ArrayList<>(); for (final String role : ALL_TESTED_ROLES) { qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role)); } QUERY_ROLES = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8); } @Deployment(name = AGGREGATE_REALM_SAME_TYPE_NAME) public static WebArchive deploymentSameType() { return deployment(AGGREGATE_REALM_SAME_TYPE_NAME); } @Deployment(name = AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public static WebArchive deploymentDifferentType() { return deployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME); } @Deployment(name = AGGREGATE_ATTRIBUTES_NAME) public static WebArchive deploymentAttributeAggregation() { final WebArchive war = ShrinkWrap.create(WebArchive.class, AGGREGATE_ATTRIBUTES_NAME + ".war"); war.addClasses(AttributePrintingServlet.class); war.addAsWebInfResource(AggregateRealmTestCase.class.getPackage(), "aggregate-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(AGGREGATE_ATTRIBUTES_NAME), "jboss-web.xml"); war.addAsManifestResource(createPermissionsXmlAsset( new ElytronPermission("getSecurityDomain")), "permissions.xml"); return war; } private static WebArchive deployment(String name) { final WebArchive war = ShrinkWrap.create(WebArchive.class, name + ".war"); war.addClasses(RolePrintingServlet.class); war.addAsWebInfResource(AggregateRealmTestCase.class.getPackage(), "aggregate-realm-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(name), "jboss-web.xml"); return war; } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps no roles for the user. <br> * When the user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and authorization should fail - no roles should be assigned to the user (HTTP status 403 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void userWithNoRoles_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithNoRoles_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps role 'User' for the user. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just role 'User' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void userWithOneRole_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithOneRole_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps roles 'User' and 'Admin' for the user. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just roles 'User' and 'Admin' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void userWithTwoRoles_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithTwoRoles_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm.<br> * When the user with correct username but wrong password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void wrongPassword_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { wrongPassword_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm.<br> * When the user with correct username but with empty password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void emptyPassword_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { emptyPassword_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm used for authorization define different password for the user then realm for authentication.<br> * When the user with correct username but with password from realm for authorization tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void passwordFromAuthzRealm_userInBothRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { passwordFromAuthzRealm_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm.<br> * When non-exist user tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void wrongUser_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { wrongUser(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm for authentication maps role 'User' for the user <br> * and realm for authorization maps role 'Admin' for the user. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just role 'Admin' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void userWithDifferentRoleInDifferentRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithDifferentRoleInDifferentRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps role 'User' for the user <br> * and realm for authorization does not include user's username in authentication store. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just role 'User' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void correctPassword_userOnlyInAuthzRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { correctPassword_userOnlyInAuthzRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm for authorization does not include user's username in authentication store. <br> * When the user with correct username but wrong password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void wrongPassword_userOnlyInAuthzRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { wrongPassword_userOnlyInAuthzRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Properties Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm for authorization does not include user's username in authentication store. <br> * When the user with correct username but with empty password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_SAME_TYPE_NAME) public void emptyPassword_userOnlyInAuthzRealm_sameTypeRealm(@ArquillianResource URL webAppURL) throws Exception { emptyPassword_userOnlyInAuthzRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps no roles for the user. <br> * When the user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and authorization should fail - no roles should be assigned to the user (HTTP status 403 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void userWithNoRoles_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithNoRoles_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps role 'User' for the user. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just role 'User' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void userWithOneRole_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithOneRole_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps roles 'User' and 'Admin' for the user. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just roles 'User' and 'Admin' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void userWithTwoRoles_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithTwoRoles_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm.<br> * When the user with correct username but wrong password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void wrongPassword_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { wrongPassword_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm.<br> * When the user with correct username but with empty password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void emptyPassword_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { emptyPassword_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm used for authorization define different password for the user then realm for authentication.<br> * When the user with correct username but with password from realm for authorization tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void passwordFromAuthzRealm_userInBothRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { passwordFromAuthzRealm_userInBothRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm.<br> * When non-exist user tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void wrongUser_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { wrongUser(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm for authentication maps role 'User' for the user <br> * and realm for authorization maps role 'Admin' for the user. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just role 'Admin' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void userWithDifferentRoleInDifferentRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { userWithDifferentRoleInDifferentRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and roles property file maps role 'User' for the user <br> * and realm for authorization does not include user's username in authentication store. <br> * When user with correct username and password tries to authenticate, <br> * then authentication should succeed <br> * and just role 'User' should be assigned to the user. */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void correctPassword_userOnlyInAuthzRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { correctPassword_userOnlyInAuthzRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm for authorization does not include user's username in authentication store. <br> * When the user with correct username but wrong password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void wrongPassword_userOnlyInAuthzRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { wrongPassword_userOnlyInAuthzRealm(webAppURL); } /** * Given: Authentication is provided by Elytron Filesystem Realm<br> * and authorization is provided by another Elytron Properties Realm<br> * and realm for authorization does not include user's username in authentication store. <br> * When the user with correct username but with empty password tries to authenticate, <br> * then authentication should fail (HTTP status 401 is returned). */ @Test @OperateOnDeployment(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) public void emptyPassword_userOnlyInAuthzRealm_differentTypeRealm(@ArquillianResource URL webAppURL) throws Exception { emptyPassword_userOnlyInAuthzRealm(webAppURL); } /* * The next four tests test the aggregation of attributes, in each case a properties realm is used for * authentication and two filesystem realms are used to load the identities attributes. * * All of these tests result in a successful authentication as the tests are verifying the combined attributes * of a successfully authenticated and authorized identity. */ /** * Test the attributes of an identity with no additional attributes loaded other than the groups * required for the test. */ @Test @OperateOnDeployment(AGGREGATE_ATTRIBUTES_NAME) public void userWithoutAttributes(@ArquillianResource URL webAppURL) throws Exception { Properties properties = getAttributes(webAppURL, USER_NO_ATTRIBUTES); assertEquals("Properties count", 1, properties.size()); assertAttribute(properties, "groups", "User"); } /** * Test the attributes of an identity where the attributes are all loaded from the first of the * aggregated authorization realms with no attributes loaded from the second realm. */ @Test @OperateOnDeployment(AGGREGATE_ATTRIBUTES_NAME) public void userFirstAttributes(@ArquillianResource URL webAppURL) throws Exception { Properties properties = getAttributes(webAppURL, USER_FIRST_ATTRIBUTES); assertEquals("Properties count", 2, properties.size()); assertAttribute(properties, "groups", "User"); assertAttribute(properties, "Colours", "Red", "Orange"); } /** * Test the attributes of an identity where attributes other than the group membership information are * loaded from the second aggregated security realm. */ @Test @OperateOnDeployment(AGGREGATE_ATTRIBUTES_NAME) public void userSecondAttributes(@ArquillianResource URL webAppURL) throws Exception { Properties properties = getAttributes(webAppURL, USER_SECOND_ATTRIBUTES); assertEquals("Properties count", 2, properties.size()); assertAttribute(properties, "groups", "User"); assertAttribute(properties, "Colours", "Yellow", "Green"); } /** * Test the attributes of an identity where the attributes are loaded from two authorization realms * and aggregated together. */ @Test @OperateOnDeployment(AGGREGATE_ATTRIBUTES_NAME) public void userCombinedAttributes(@ArquillianResource URL webAppURL) throws Exception { Properties properties = getAttributes(webAppURL, USER_COMBINED_ATTRIBUTES); assertEquals("Properties count", 4, properties.size()); assertAttribute(properties, "groups", "User"); assertAttribute(properties, "Year", "1979"); assertAttribute(properties, "Colours", "Blue", "Violet"); assertAttribute(properties, "City", "San Francisco"); } private static Properties getAttributes(URL webAppURL, final String identity) throws Exception { return AggregateRealmUtil.getAttributes(webAppURL, identity, CORRECT_PASSWORD); } private void userWithNoRoles_userInBothRealm(URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER_WITHOUT_ROLE, CORRECT_PASSWORD, QUERY_ROLES); } private void userWithOneRole_userInBothRealm(URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ONE_ROLE, CORRECT_PASSWORD, ROLE_USER); } private void userWithTwoRoles_userInBothRealm(URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_TWO_ROLES, CORRECT_PASSWORD, ROLE_USER, ROLE_ADMIN); } private void wrongPassword_userInBothRealm(URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_WITH_ONE_ROLE, WRONG_PASSWORD, QUERY_ROLES); } private void emptyPassword_userInBothRealm(URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_WITH_ONE_ROLE, EMPTY_PASSWORD, QUERY_ROLES); } private void passwordFromAuthzRealm_userInBothRealm(URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_WITH_ONE_ROLE, AUTHORIZATION_REALM_PASSWORD, QUERY_ROLES); } private void wrongUser(URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, WRONG_USER, CORRECT_PASSWORD, QUERY_ROLES); } private void userWithDifferentRoleInDifferentRealm(URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_DIFFERENT_ROLE_IN_DIFFERENT_REALM, CORRECT_PASSWORD, ROLE_ADMIN); } private void correctPassword_userOnlyInAuthzRealm(URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_ONLY_IN_AUTHORIZATION, CORRECT_PASSWORD, ROLE_USER); } private void wrongPassword_userOnlyInAuthzRealm(URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_ONLY_IN_AUTHORIZATION, WRONG_PASSWORD, QUERY_ROLES); } private void emptyPassword_userOnlyInAuthzRealm(URL webAppURL) throws Exception { assertAuthenticationFailed(webAppURL, USER_ONLY_IN_AUTHORIZATION, EMPTY_PASSWORD, QUERY_ROLES); } private void testAssignedRoles(URL webAppURL, String username, String password, String... assignedRoles) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL, QUERY_ROLES); final String rolesResponse = Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_OK); final List<String> assignedRolesList = Arrays.asList(assignedRoles); for (String role : ALL_TESTED_ROLES) { if (assignedRolesList.contains(role)) { assertInRole(rolesResponse, role); } else { assertNotInRole(rolesResponse, role); } } } static class SetupTask extends AbstractElytronSetupTask { private static final String PROPERTIES_REALM_AUTHN_NAME = "elytron-authn-properties-realm"; private static final String PROPERTIES_REALM_AUTHZ_NAME = "elytron-authz-properties-realm"; private static final String FILESYSTEM_REALM_AUTHN_NAME = "elytron-authn-filesystem-realm"; private static final String FILESYSTEM_REALM_2_AUTHN_NAME = "elytron-authn-filesystem-realm-2"; @Override protected ConfigurableElement[] getConfigurableElements() { ArrayList<ConfigurableElement> configurableElements = new ArrayList<>(); configurableElements.add(PropertiesRealm.builder() .withName(PROPERTIES_REALM_AUTHN_NAME) .withUser(UserWithAttributeValues.builder() .withName(USER_WITHOUT_ROLE) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_ONE_ROLE) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_TWO_ROLES) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_DIFFERENT_ROLE_IN_DIFFERENT_REALM) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_DIFFERENT_ROLE_IN_DIFFERENT_REALM) .withPassword(CORRECT_PASSWORD) .withValues(ROLE_USER) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_ONLY_IN_AUTHORIZATION) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_NO_ATTRIBUTES) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_FIRST_ATTRIBUTES) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_SECOND_ATTRIBUTES) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_COMBINED_ATTRIBUTES) .withPassword(CORRECT_PASSWORD) .build()) .build()); configurableElements.add(PropertiesRealm.builder() .withName(PROPERTIES_REALM_AUTHZ_NAME) .withUser(UserWithAttributeValues.builder() .withName(USER_WITHOUT_ROLE) .withPassword(AUTHORIZATION_REALM_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_ONE_ROLE) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_USER) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_TWO_ROLES) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_USER, ROLE_ADMIN) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_DIFFERENT_ROLE_IN_DIFFERENT_REALM) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_ADMIN) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_ONLY_IN_AUTHORIZATION) .withValues(ROLE_USER) .build()) .build()); configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_AUTHN_NAME) .withUser(UserWithAttributeValues.builder() .withName(USER_WITHOUT_ROLE) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_ONE_ROLE) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_TWO_ROLES) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_WITH_DIFFERENT_ROLE_IN_DIFFERENT_REALM) .withPassword(CORRECT_PASSWORD) .withValues(ROLE_USER) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_ONLY_IN_AUTHORIZATION) .withPassword(CORRECT_PASSWORD) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_NO_ATTRIBUTES) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_USER) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_FIRST_ATTRIBUTES) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_USER) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_COMBINED_ATTRIBUTES) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_USER) .build()) .build()); configurableElements.add(FileSystemRealm.builder() .withName(FILESYSTEM_REALM_2_AUTHN_NAME) .withUser(UserWithAttributeValues.builder() .withName(USER_SECOND_ATTRIBUTES) .withPassword(AUTHORIZATION_REALM_PASSWORD) .withValues(ROLE_USER) .build()) .withUser(UserWithAttributeValues.builder() .withName(USER_COMBINED_ATTRIBUTES) .withPassword(AUTHORIZATION_REALM_PASSWORD) .build()) .build()); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_SAME_TYPE_NAME) .withAuthenticationRealm(PROPERTIES_REALM_AUTHN_NAME) .withAuthorizationRealm(PROPERTIES_REALM_AUTHZ_NAME) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName(AGGREGATE_REALM_SAME_TYPE_NAME) .withDefaultRealm(AGGREGATE_REALM_SAME_TYPE_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(AGGREGATE_REALM_SAME_TYPE_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withAuthenticationRealm(FILESYSTEM_REALM_AUTHN_NAME) .withAuthorizationRealm(PROPERTIES_REALM_AUTHZ_NAME) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withDefaultRealm(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(AGGREGATE_REALM_SAME_TYPE_NAME) .withSecurityDomain(AGGREGATE_REALM_SAME_TYPE_NAME) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .withSecurityDomain(AGGREGATE_REALM_DIFFERENT_TYPE_NAME) .build()); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_AUTHN_NAME, USER_FIRST_ATTRIBUTES, "Colours", "Red", "Orange")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_2_AUTHN_NAME, USER_SECOND_ATTRIBUTES, "Colours", "Yellow", "Green")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_AUTHN_NAME, USER_COMBINED_ATTRIBUTES, "Colours", "Blue", "Violet")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_AUTHN_NAME, USER_COMBINED_ATTRIBUTES, "Year", "1979")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_2_AUTHN_NAME, USER_COMBINED_ATTRIBUTES, "Colours", "Pink", "Turqoise")); configurableElements.add(new AggregateRealmUtil.CustomFSAttributes(FILESYSTEM_REALM_2_AUTHN_NAME, USER_COMBINED_ATTRIBUTES, "City", "San Francisco")); configurableElements.add(AggregateSecurityRealm.builder(AGGREGATE_ATTRIBUTES_NAME) .withAuthenticationRealm(PROPERTIES_REALM_AUTHN_NAME) .withAuthorizationRealms(FILESYSTEM_REALM_AUTHN_NAME, FILESYSTEM_REALM_2_AUTHN_NAME) .build()); configurableElements.add(SimpleSecurityDomain.builder() .withName(AGGREGATE_ATTRIBUTES_NAME) .withDefaultRealm(AGGREGATE_ATTRIBUTES_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(AGGREGATE_ATTRIBUTES_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); configurableElements.add(UndertowApplicationSecurityDomain.builder() .withName(AGGREGATE_ATTRIBUTES_NAME) .withSecurityDomain(AGGREGATE_ATTRIBUTES_NAME) .build()); return configurableElements.toArray(new ConfigurableElement[configurableElements.size()]); } } static class CustomFSAttributes implements ConfigurableElement { private final String realm; private final String identity; private final String attributeName; private final String[] values; CustomFSAttributes(String realm, String identity, String attributeName, String... values) { this.realm = realm; this.identity = identity; this.attributeName = attributeName; this.values = values; } @Override public String getName() { return String.format("Attribute '$s' for identity '%s' in realm '%s'", attributeName, identity, realm); } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine(String.format( "/subsystem=elytron/filesystem-realm=%s:add-identity-attribute(identity=%s, name=%s, value=[%s])", realm, identity, attributeName, String.join(",", values))); } public void remove(CLIWrapper cli) throws Exception { // No action required as the overall realm is removed - however this override is // required as ConfigurableElement.remove(CLIWrapper) throws an IllegalStateException. } } }
41,185
50.226368
168
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/RoleServlets.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import static org.wildfly.test.integration.elytron.realm.AggregateRealmWithTransformerTestCase.ROLE_1; import static org.wildfly.test.integration.elytron.realm.AggregateRealmWithTransformerTestCase.ROLE_2; import static org.wildfly.test.integration.elytron.realm.AggregateRealmWithTransformerTestCase.ROLE_3; import static org.wildfly.test.integration.elytron.realm.AggregateRealmWithTransformerTestCase.ROLE_4; import static org.wildfly.test.integration.elytron.realm.AggregateRealmWithTransformerTestCase.ROLE_5; import static org.wildfly.test.integration.elytron.realm.AggregateRealmWithTransformerTestCase.ROLE_6; /** * These servlets allows access to different roles. * These servlets are used in AggregateRealmWithTransformerTestCase. */ public class RoleServlets { @WebServlet(urlPatterns = { Role1Servlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { ROLE_1 })) public static class Role1Servlet extends GeneralRoleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/" + ROLE_1; } @WebServlet(urlPatterns = { Role2Servlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { ROLE_2 })) public static class Role2Servlet extends GeneralRoleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/" + ROLE_2; } @WebServlet(urlPatterns = { Role3Servlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { ROLE_3 })) public static class Role3Servlet extends GeneralRoleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/" + ROLE_3; } @WebServlet(urlPatterns = { Role4Servlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { ROLE_4 })) public static class Role4Servlet extends GeneralRoleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/" + ROLE_4; } @WebServlet(urlPatterns = { Role5Servlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { ROLE_5 })) public static class Role5Servlet extends GeneralRoleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/" + ROLE_5; } @WebServlet(urlPatterns = { Role6Servlet.SERVLET_PATH }) @ServletSecurity(@HttpConstraint(rolesAllowed = { ROLE_6 })) public static class Role6Servlet extends GeneralRoleServlet { /** The serialVersionUID */ private static final long serialVersionUID = 1L; /** The default servlet path (used in {@link WebServlet} annotation). */ public static final String SERVLET_PATH = "/" + ROLE_6; } public abstract static class GeneralRoleServlet extends HttpServlet { /** Writes plain-text ok response. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); final PrintWriter writer = resp.getWriter(); writer.write("ok"); writer.close(); } } }
4,875
42.150442
117
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/realm/LdapRealmFollowReferralsTestCase.java
/* * Copyright (c) 2022 The original author or authors * * All rights reserved. This program and the accompanying materials * are made available under the terms of Apache License v2.0 which * accompanies this distribution. * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.wildfly.test.integration.elytron.realm; import java.net.URL; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.junit.runner.RunWith; /** * <p>Configures referral mode to follow and executes the smoke tests.</p> * * @author rmartinc */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AbstractLdapRealmTest.LDAPServerSetupTask.class, LdapRealmFollowReferralsTestCase.SetupTask.class}) public class LdapRealmFollowReferralsTestCase extends AbstractLdapRealmTest { @Override public void testReferralUser(@ArquillianResource URL webAppURL) throws Exception { // the referral user should be found with the proper role as referrals are followed testAssignedRoles(webAppURL, USER_REFERRAL, CORRECT_PASSWORD, "ReferralRole"); } /** * SetupTask with referral mode to follow. */ static class SetupTask extends AbstractLdapRealmTest.SetupTask { @Override public String getReferralMode() { return "follow"; } } }
1,861
34.132075
113
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/ConstantRoleMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.PROPERTIES_REALM_NAME; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.addSecurityDomainWithRoleMapper; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.PropertiesRealm; /** * Test case for Elytron Constant Role Mapper. * * Given: Authentication to secured application is backed by Elytron Properties Realm. <br> * * @author olukas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ConstantRoleMapperTestCase.ServerSetup.class}) public class ConstantRoleMapperTestCase extends AbstractRoleMapperTest { private static final String ONE_ROLE_MAPPER = "one-role-contant-role-mapper"; private static final String TWO_ROLES_MAPPER = "two-roles-contant-role-mapper"; private static final String USER_WITHOUT_ROLES = "userWithoutRoles"; private static final String USER_WITH_ROLE1 = "userWithRole1"; private static final String USER_WITH_ROLE2 = "userWithRole2"; private static final String USER_WITH_TWO_ROLES = "userWithTwoRoles"; private static final String USER_WITH_THREE_ROLES = "userWithThreeRoles"; private static final String PASSWORD = "password"; @Override protected String[] allTestedRoles() { return new String[]{ROLE1, ROLE2, ROLE3}; } @Deployment(name = ONE_ROLE_MAPPER) public static WebArchive deploymentOneRole() { return createDeploymentForPrintingRoles(ONE_ROLE_MAPPER); } @Deployment(name = TWO_ROLES_MAPPER) public static WebArchive deploymentTwoRoles() { return createDeploymentForPrintingRoles(TWO_ROLES_MAPPER); } /** * Given: Constant Role Mapper which maps Role1 is added to configuration <br> * and roles property file maps no role for the user. <br> * When the user is authenticated <br> * then just role Role1 should be assigned to user. */ @Test @OperateOnDeployment(ONE_ROLE_MAPPER) public void testOneRoleMapper_userWithoutRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITHOUT_ROLES, PASSWORD, ROLE1); } /** * Given: Constant Role Mapper which maps Role1 is added to configuration.<br> * and roles property file maps role Role1 for the user. <br> * When the user is authenticated <br> * then just role Role1 should be assigned to the user. */ @Test @OperateOnDeployment(ONE_ROLE_MAPPER) public void testOneRoleMapper_userWithSameRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE1, PASSWORD, ROLE1); } /** * Given: Constant Role Mapper which maps Role1 is added to configuration.<br> * and roles property file maps role Role2 for the user. <br> * When the user is authenticated <br> * then just role Role1 should be assigned to the user. */ @Test @OperateOnDeployment(ONE_ROLE_MAPPER) public void testOneRoleMapper_userWithDifferentRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE2, PASSWORD, ROLE1); } /** * Given: Constant Role Mapper which maps Role1 is added to configuration.<br> * and roles property file maps roles Role1 and Role2 for the user. <br> * When the user is authenticated <br> * then just role Role1 should be assigned to the user. */ @Test @OperateOnDeployment(ONE_ROLE_MAPPER) public void testOneRoleMapper_userWithMoreRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_TWO_ROLES, PASSWORD, ROLE1); } /** * Given: Constant Role Mapper which maps Role1 and Role2 is added to configuration.<br> * and roles property file maps role Role1 for the user. <br> * When the user is authenticated <br> * then just roles Role1 and Role2 should be assigned to the user. */ @Test @OperateOnDeployment(TWO_ROLES_MAPPER) public void testTwoRolesMapper_userWithLessRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE1, PASSWORD, ROLE1, ROLE2); } /** * Given: Constant Role Mapper which maps Role1 and Role2 is added to configuration.<br> * and roles property file maps roles Role1 and Role3 for the user. <br> * When the user is authenticated <br> * then just roles Role1 and Role2 should be assigned to the user. */ @Test @OperateOnDeployment(TWO_ROLES_MAPPER) public void testTwoRolesMapper_userWithOneSameAndOneDifferentRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_TWO_ROLES, PASSWORD, ROLE1, ROLE2); } /** * Given: Constant Role Mapper which maps Role1 and Role2 is added to configuration.<br> * and roles property file maps roles Role1, Role2 and Role3 for the user. <br> * When the user is authenticated <br> * then just roles Role1 and Role2 should be assigned to the user. */ @Test @OperateOnDeployment(TWO_ROLES_MAPPER) public void testTwoRolesMapper_userWithMoreRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_THREE_ROLES, PASSWORD, ROLE1, ROLE2); } public static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); elements.add(new ConstantRoleMappers( String.format("%s:add(roles=[%s])", ONE_ROLE_MAPPER, ROLE1), String.format("%s:add(roles=[%s,%s])", TWO_ROLES_MAPPER, ROLE1, ROLE2) )); elements.add(PropertiesRealm.builder().withName(PROPERTIES_REALM_NAME) .withUser(USER_WITHOUT_ROLES, PASSWORD) .withUser(USER_WITH_ROLE1, PASSWORD, ROLE1) .withUser(USER_WITH_ROLE2, PASSWORD, ROLE2) .withUser(USER_WITH_TWO_ROLES, PASSWORD, ROLE1, ROLE3) .withUser(USER_WITH_THREE_ROLES, PASSWORD, ROLE1, ROLE2, ROLE3) .build()); addSecurityDomainWithRoleMapper(elements, ONE_ROLE_MAPPER); addSecurityDomainWithRoleMapper(elements, TWO_ROLES_MAPPER); return elements.toArray(new ConfigurableElement[elements.size()]); } public static class ConstantRoleMappers implements ConfigurableElement { private final String[] dynamicConstants; public ConstantRoleMappers(String... dynamicConstants) { this.dynamicConstants = dynamicConstants; } @Override public void create(CLIWrapper cli) throws Exception { for (String con : dynamicConstants) { cli.sendLine("/subsystem=elytron/constant-role-mapper=" + con); } } @Override public void remove(CLIWrapper cli) throws Exception { for (String con : dynamicConstants) { int opIdx = con.indexOf(':'); String newCon = con.substring(0, opIdx + 1) + "remove()"; cli.sendLine("/subsystem=elytron/constant-role-mapper=" + newCon); } } @Override public String getName() { return "constant-role-mapper"; } } } }
9,384
41.466063
123
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/RoleMapperSetupUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.util.List; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.UndertowDomainMapper; /** * * @author olukas */ class RoleMapperSetupUtils { static final String PROPERTIES_REALM_NAME = "RoleMapperPropertiesRealm"; private RoleMapperSetupUtils() { } static void addSecurityDomainWithRoleMapper(List<ConfigurableElement> elements, String roleMapperName) { elements.add(SimpleSecurityDomain.builder().withName(roleMapperName) .withRoleMapper(roleMapperName) .withDefaultRealm(PROPERTIES_REALM_NAME) .withPermissionMapper("default-permission-mapper") .withRealms(SimpleSecurityDomain.SecurityDomainRealm.builder() .withRealm(PROPERTIES_REALM_NAME) .withRoleDecoder("groups-to-roles") .build()) .build()); elements.add(UndertowDomainMapper.builder() .withName(roleMapperName) .withApplicationDomains(roleMapperName) .build()); } }
2,307
39.491228
108
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/LogicalRoleMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE1; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE2; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE3; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.PROPERTIES_REALM_NAME; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.addSecurityDomainWithRoleMapper; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.PropertiesRealm; /** * Test case for Elytron Logical Role Mapper. * * Given: Authentication to secured application is backed by Elytron Properties Realm. * * @author olukas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({LogicalRoleMapperTestCase.ServerSetup.class}) public class LogicalRoleMapperTestCase extends AbstractRoleMapperTest { private static final String AND_SOME_SAME_ROLES = "and-some-same-roles"; private static final String AND_EMPTY_ROLE = "and-empty-role"; private static final String AND_DIFFERENT_ROLES = "and-different-roles"; private static final String AND_LEFT_IS_MISSING_ROLES = "and-left-is-missing"; private static final String AND_RIGHT_IS_MISSING_ROLES = "and-right-is-missing"; private static final String OR_SOME_SAME_ROLES = "or-some-same-roles"; private static final String OR_EMPTY_ROLE = "or-empty-role"; private static final String OR_DIFFERENT_ROLES = "or-different-roles"; private static final String OR_LEFT_IS_MISSING_ROLES = "or-left-is-missing"; private static final String OR_RIGHT_IS_MISSING_ROLES = "or-right-is-missing"; private static final String MINUS_SOME_SAME_ROLES = "minus-some-same-roles"; private static final String MINUS_EMPTY_ROLE_LEFT_ROLES = "minus-empty-role-left"; private static final String MINUS_EMPTY_ROLE_RIGHT = "minus-empty-role-right"; private static final String MINUS_DIFFERENT_ROLES = "minus-different-roles"; private static final String MINUS_LEFT_IS_MISSING_ROLES = "minus-left-is-missing"; private static final String MINUS_RIGHT_IS_MISSING_ROLES = "minus-right-is-missing"; private static final String XOR_SOME_SAME_ROLES = "xor-some-same-roles"; private static final String XOR_EMPTY_ROLE = "xor-empty-role"; private static final String XOR_DIFFERENT_ROLES = "xor-different-roles"; private static final String XOR_LEFT_IS_MISSING_ROLES = "xor-left-is-missing"; private static final String XOR_RIGHT_IS_MISSING_ROLES = "xor-right-is-missing"; private static final String USER = "user"; private static final String USER_WITH_ROLE_2_3_4 = "user-with-role-2-3-4"; private static final String PASSWORD = "password"; @Override protected String[] allTestedRoles() { return new String[]{ROLE1, ROLE2, ROLE3, ROLE4}; } @Deployment(name = AND_SOME_SAME_ROLES) public static WebArchive deploymentAndSomeSameRoles() { return createDeploymentForPrintingRoles(AND_SOME_SAME_ROLES); } @Deployment(name = AND_EMPTY_ROLE) public static WebArchive deploymentAndEmptyRole() { return createDeploymentForPrintingRoles(AND_EMPTY_ROLE); } @Deployment(name = AND_DIFFERENT_ROLES) public static WebArchive deploymentAndDifferentRoles() { return createDeploymentForPrintingRoles(AND_DIFFERENT_ROLES); } @Deployment(name = AND_LEFT_IS_MISSING_ROLES) public static WebArchive deploymentAndLeftIsMissing() { return createDeploymentForPrintingRoles(AND_LEFT_IS_MISSING_ROLES); } @Deployment(name = AND_RIGHT_IS_MISSING_ROLES) public static WebArchive deploymentAndRightIsMissing() { return createDeploymentForPrintingRoles(AND_RIGHT_IS_MISSING_ROLES); } @Deployment(name = OR_SOME_SAME_ROLES) public static WebArchive deploymentOrSomeSameRoles() { return createDeploymentForPrintingRoles(OR_SOME_SAME_ROLES); } @Deployment(name = OR_EMPTY_ROLE) public static WebArchive deploymentOrEmptyRole() { return createDeploymentForPrintingRoles(OR_EMPTY_ROLE); } @Deployment(name = OR_DIFFERENT_ROLES) public static WebArchive deploymentOrDifferentRoles() { return createDeploymentForPrintingRoles(OR_DIFFERENT_ROLES); } @Deployment(name = OR_LEFT_IS_MISSING_ROLES) public static WebArchive deploymentOrLeftIsMissing() { return createDeploymentForPrintingRoles(OR_LEFT_IS_MISSING_ROLES); } @Deployment(name = OR_RIGHT_IS_MISSING_ROLES) public static WebArchive deploymentOrRightIsMissing() { return createDeploymentForPrintingRoles(OR_RIGHT_IS_MISSING_ROLES); } @Deployment(name = MINUS_SOME_SAME_ROLES) public static WebArchive deploymentMinusSomeSameRoles() { return createDeploymentForPrintingRoles(MINUS_SOME_SAME_ROLES); } @Deployment(name = MINUS_EMPTY_ROLE_LEFT_ROLES) public static WebArchive deploymentMinusEmptyRoleLeft() { return createDeploymentForPrintingRoles(MINUS_EMPTY_ROLE_LEFT_ROLES); } @Deployment(name = MINUS_EMPTY_ROLE_RIGHT) public static WebArchive deploymentMinusEmptyRoleRight() { return createDeploymentForPrintingRoles(MINUS_EMPTY_ROLE_RIGHT); } @Deployment(name = MINUS_DIFFERENT_ROLES) public static WebArchive deploymentMinusDifferentRoles() { return createDeploymentForPrintingRoles(MINUS_DIFFERENT_ROLES); } @Deployment(name = MINUS_LEFT_IS_MISSING_ROLES) public static WebArchive deploymentMinusLeftIsMissing() { return createDeploymentForPrintingRoles(MINUS_LEFT_IS_MISSING_ROLES); } @Deployment(name = MINUS_RIGHT_IS_MISSING_ROLES) public static WebArchive deploymentMinusRightIsMissing() { return createDeploymentForPrintingRoles(MINUS_RIGHT_IS_MISSING_ROLES); } @Deployment(name = XOR_SOME_SAME_ROLES) public static WebArchive deploymentXorSomeSameRoles() { return createDeploymentForPrintingRoles(XOR_SOME_SAME_ROLES); } @Deployment(name = XOR_EMPTY_ROLE) public static WebArchive deploymentXorEmptyRole() { return createDeploymentForPrintingRoles(XOR_EMPTY_ROLE); } @Deployment(name = XOR_DIFFERENT_ROLES) public static WebArchive deploymentXorDifferentRoles() { return createDeploymentForPrintingRoles(XOR_DIFFERENT_ROLES); } @Deployment(name = XOR_LEFT_IS_MISSING_ROLES) public static WebArchive deploymentXorLeftIsMissing() { return createDeploymentForPrintingRoles(XOR_LEFT_IS_MISSING_ROLES); } @Deployment(name = XOR_RIGHT_IS_MISSING_ROLES) public static WebArchive deploymentXorRightIsMissing() { return createDeploymentForPrintingRoles(XOR_RIGHT_IS_MISSING_ROLES); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=AND' <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then just roles Role2 and Role3 should be assigned to the user. <br> */ @Test @OperateOnDeployment(AND_SOME_SAME_ROLES) public void testAnd_someSameRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE2, ROLE3); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=AND' <br> * and attribute left maps no roles <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then no roles should be assigned to the user. <br> */ @Test @OperateOnDeployment(AND_EMPTY_ROLE) public void testAnd_emptyRole(@ArquillianResource URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER, PASSWORD); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=AND' <br> * and attribute left maps roles Role1 and Role2 <br> * and attribute right maps role Role3. <br> * When the user is authenticated <br> * then no roles should be assigned to the user. <br> */ @Test @OperateOnDeployment(AND_DIFFERENT_ROLES) public void testAnd_differentRoles(@ArquillianResource URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER, PASSWORD); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=AND' <br> * and attribute left is missing <br> * and attribute right maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just roles Role2 and Role3 should be assigned to the user (which means that left side of operation has been taken * from user identity). <br> */ @Test @OperateOnDeployment(AND_LEFT_IS_MISSING_ROLES) public void testAnd_leftIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE2, ROLE3); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=AND' <br> * and attribute right is missing <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just roles Role2 and Role3 should be assigned to the user (which means that right side of operation has been taken * from user identity). <br> */ @Test @OperateOnDeployment(AND_RIGHT_IS_MISSING_ROLES) public void testAnd_rightIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE2, ROLE3); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=OR' <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then just roles Role1, Role2, Role3 and Role4 should be assigned to the user. <br> */ @Test @OperateOnDeployment(OR_SOME_SAME_ROLES) public void testOr_someSameRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1, ROLE2, ROLE3, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=OR' <br> * and attribute left maps no roles <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then just roles Role2, Role3 and Role4 should be assigned to the user. <br> */ @Test @OperateOnDeployment(OR_EMPTY_ROLE) public void testOr_emptyRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE2, ROLE3, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=OR' <br> * and attribute left maps roles Role1 and Role2 <br> * and attribute right maps role Role3. <br> * When the user is authenticated <br> * then just roles Role1, Role2 and Role3 should be assigned to the user. <br> */ @Test @OperateOnDeployment(OR_DIFFERENT_ROLES) public void testOr_differentRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1, ROLE2, ROLE3); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=OR' <br> * and attribute left is missing <br> * and attribute right maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just roles Role1, Role2, Role3 and Role4 should be assigned to the user (which means that left side of operation has * been taken from user identity). <br> */ @Test @OperateOnDeployment(OR_LEFT_IS_MISSING_ROLES) public void testOr_leftIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE1, ROLE2, ROLE3, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=OR' <br> * and attribute right is missing <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just roles Role1, Role2, Role3 and Role4 should be assigned to the user (which means that right side of operation * has been taken from user identity). <br> */ @Test @OperateOnDeployment(OR_RIGHT_IS_MISSING_ROLES) public void testOr_rightIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE1, ROLE2, ROLE3, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=MINUS' <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then just role Role1 should be assigned to the user. <br> */ @Test @OperateOnDeployment(MINUS_SOME_SAME_ROLES) public void testMinus_someSameRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=MINUS' <br> * and attribute left maps no roles <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then no roles should be assigned to the user. <br> */ @Test @OperateOnDeployment(MINUS_EMPTY_ROLE_LEFT_ROLES) public void testMinus_emptyRoleLeft(@ArquillianResource URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER, PASSWORD); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=MINUS' <br> * and attribute left maps roles Role2, Role3 and Role4 <br> * and attribute right maps no roles. <br> * When the user is authenticated <br> * then just role Role2, Role3 and Role4 should be assigned to the user. <br> */ @Test @OperateOnDeployment(MINUS_EMPTY_ROLE_RIGHT) public void testMinus_emptyRoleRight(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE2, ROLE3, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=MINUS' <br> * and attribute left maps roles Role1 and Role2 <br> * and attribute right maps role Role3. <br> * When the user is authenticated <br> * then just role Role1 and Role2 should be assigned to the user. <br> */ @Test @OperateOnDeployment(MINUS_DIFFERENT_ROLES) public void testMinus_differentRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1, ROLE2); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=MINUS' <br> * and attribute left is missing <br> * and attribute right maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just role Role4 should be assigned to the user (which means that left side of operation has been taken from user * identity). <br> */ @Test @OperateOnDeployment(MINUS_LEFT_IS_MISSING_ROLES) public void testMinus_leftIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=MINUS' <br> * and attribute right is missing <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just role Role1 should be assigned to the user (which means that right side of operation has been taken from user * identity). <br> */ @Test @OperateOnDeployment(MINUS_RIGHT_IS_MISSING_ROLES) public void testMinus_rightIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE1); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=XOR' <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then just roles Role1 and Role4 should be assigned to the user. <br> */ @Test @OperateOnDeployment(XOR_SOME_SAME_ROLES) public void testXor_someSameRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=XOR' <br> * and attribute left maps no roles <br> * and attribute right maps roles Role2, Role3 and Role4. <br> * When the user is authenticated <br> * then just roles Role2, Role3 and Role4 should be assigned to the user. <br> */ @Test @OperateOnDeployment(XOR_EMPTY_ROLE) public void testXor_emptyRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE2, ROLE3, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=XOR' <br> * and attribute left maps roles Role1 and Role2 <br> * and attribute right maps role Role3. <br> * When the user is authenticated <br> * then just roles Role1, Role2 and Role3 should be assigned to the user. <br> */ @Test @OperateOnDeployment(XOR_DIFFERENT_ROLES) public void testXor_differentRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1, ROLE2, ROLE3); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=XOR' <br> * and attribute left is missing <br> * and attribute right maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just roles Role1 and Role4 should be assigned to the user (which means that left side of operation has been taken * from user identity). <br> */ @Test @OperateOnDeployment(XOR_LEFT_IS_MISSING_ROLES) public void testXor_leftIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE1, ROLE4); } /** * Given: Logical Role Mapper which has configured attribute 'logicalOperation=XOR' <br> * and attribute right is missing <br> * and attribute left maps roles Role1, Role2 and Role3 <br> * and roles property files map roles Role2, Role3 and Role4 for the user. <br> * When the user is authenticated <br> * then just roles Role1 and Role4 should be assigned to the user (which means that right side of operation has been taken * from user identity). <br> */ @Test @OperateOnDeployment(XOR_RIGHT_IS_MISSING_ROLES) public void testXor_rightIsMissing(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE_2_3_4, PASSWORD, ROLE1, ROLE4); } public static class ServerSetup extends AbstractElytronSetupTask { private static final String CONSTANT_ROLE_MAPPER_1_2_3 = "contant-role-mapper-1-2-3"; private static final String CONSTANT_ROLE_MAPPER_2_3_4 = "contant-role-mapper-2-3-4"; private static final String CONSTANT_ROLE_MAPPER_1_2 = "contant-role-mapper-1-2"; private static final String CONSTANT_ROLE_MAPPER_3 = "contant-role-mapper-3"; /** * There is no simple way how to map no role through any mapper. Empty role can be created as empty intersection in * another logical role mapper. This is dependent on correctly implemented AND in logical role mapper. */ private static final String EMPTY_ROLE_MAPPER_HELPER_1 = "empty-role-maper-helper-1"; private static final String EMPTY_ROLE_MAPPER_HELPER_2 = "empty-role-maper-helper-2"; private static final String EMPTY_ROLE_MAPPER = "empty-role-maper"; @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); elements.add(new ConstantRoleMapperTestCase.ServerSetup.ConstantRoleMappers( String.format("%s:add(roles=[%s,%s,%s])", CONSTANT_ROLE_MAPPER_1_2_3, ROLE1, ROLE2, ROLE3), String.format("%s:add(roles=[%s,%s,%s])", CONSTANT_ROLE_MAPPER_2_3_4, ROLE2, ROLE3, ROLE4), String.format("%s:add(roles=[%s,%s])", CONSTANT_ROLE_MAPPER_1_2, ROLE1, ROLE2), String.format("%s:add(roles=[%s])", CONSTANT_ROLE_MAPPER_3, ROLE3), String.format("%s:add(roles=[%s])", EMPTY_ROLE_MAPPER_HELPER_1, ROLE1), String.format("%s:add(roles=[%s])", EMPTY_ROLE_MAPPER_HELPER_2, ROLE2) )); elements.add(new LogicalRoleMappers( String.format("%s:add(left=%s,logical-operation=and,right=%s)", EMPTY_ROLE_MAPPER, EMPTY_ROLE_MAPPER_HELPER_1, EMPTY_ROLE_MAPPER_HELPER_2) )); elements.add(new LogicalRoleMappers( String.format("%s:add(left=%s,logical-operation=and,right=%s)", AND_SOME_SAME_ROLES, CONSTANT_ROLE_MAPPER_1_2_3, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=and,right=%s)", AND_EMPTY_ROLE, EMPTY_ROLE_MAPPER, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=and,right=%s)", AND_DIFFERENT_ROLES, CONSTANT_ROLE_MAPPER_1_2, CONSTANT_ROLE_MAPPER_3), String.format("%s:add(logical-operation=and,right=%s)", AND_LEFT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=and)", AND_RIGHT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=or,right=%s)", OR_SOME_SAME_ROLES, CONSTANT_ROLE_MAPPER_1_2_3, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=or,right=%s)", OR_EMPTY_ROLE, EMPTY_ROLE_MAPPER, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=or,right=%s)", OR_DIFFERENT_ROLES, CONSTANT_ROLE_MAPPER_1_2, CONSTANT_ROLE_MAPPER_3), String.format("%s:add(logical-operation=or,right=%s)", OR_LEFT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=or)", OR_RIGHT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=minus,right=%s)", MINUS_SOME_SAME_ROLES, CONSTANT_ROLE_MAPPER_1_2_3, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=minus,right=%s)", MINUS_EMPTY_ROLE_LEFT_ROLES, EMPTY_ROLE_MAPPER, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=minus,right=%s)", MINUS_EMPTY_ROLE_RIGHT, CONSTANT_ROLE_MAPPER_2_3_4, EMPTY_ROLE_MAPPER), String.format("%s:add(left=%s,logical-operation=minus,right=%s)", MINUS_DIFFERENT_ROLES, CONSTANT_ROLE_MAPPER_1_2, CONSTANT_ROLE_MAPPER_3), String.format("%s:add(logical-operation=minus,right=%s)", MINUS_LEFT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=minus)", MINUS_RIGHT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=xor,right=%s)", XOR_SOME_SAME_ROLES, CONSTANT_ROLE_MAPPER_1_2_3, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=xor,right=%s)", XOR_EMPTY_ROLE, EMPTY_ROLE_MAPPER, CONSTANT_ROLE_MAPPER_2_3_4), String.format("%s:add(left=%s,logical-operation=xor,right=%s)", XOR_DIFFERENT_ROLES, CONSTANT_ROLE_MAPPER_1_2, CONSTANT_ROLE_MAPPER_3), String.format("%s:add(logical-operation=xor,right=%s)", XOR_LEFT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3), String.format("%s:add(left=%s,logical-operation=xor)", XOR_RIGHT_IS_MISSING_ROLES, CONSTANT_ROLE_MAPPER_1_2_3) )); elements.add(PropertiesRealm.builder().withName(PROPERTIES_REALM_NAME) .withUser(USER, PASSWORD) .withUser(USER_WITH_ROLE_2_3_4, PASSWORD, ROLE2, ROLE3, ROLE4) .build()); addSecurityDomainWithRoleMapper(elements, AND_SOME_SAME_ROLES); addSecurityDomainWithRoleMapper(elements, AND_EMPTY_ROLE); addSecurityDomainWithRoleMapper(elements, AND_DIFFERENT_ROLES); addSecurityDomainWithRoleMapper(elements, AND_LEFT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, AND_RIGHT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, OR_SOME_SAME_ROLES); addSecurityDomainWithRoleMapper(elements, OR_EMPTY_ROLE); addSecurityDomainWithRoleMapper(elements, OR_DIFFERENT_ROLES); addSecurityDomainWithRoleMapper(elements, OR_LEFT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, OR_RIGHT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, MINUS_SOME_SAME_ROLES); addSecurityDomainWithRoleMapper(elements, MINUS_EMPTY_ROLE_LEFT_ROLES); addSecurityDomainWithRoleMapper(elements, MINUS_EMPTY_ROLE_RIGHT); addSecurityDomainWithRoleMapper(elements, MINUS_DIFFERENT_ROLES); addSecurityDomainWithRoleMapper(elements, MINUS_LEFT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, MINUS_RIGHT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, XOR_SOME_SAME_ROLES); addSecurityDomainWithRoleMapper(elements, XOR_EMPTY_ROLE); addSecurityDomainWithRoleMapper(elements, XOR_DIFFERENT_ROLES); addSecurityDomainWithRoleMapper(elements, XOR_LEFT_IS_MISSING_ROLES); addSecurityDomainWithRoleMapper(elements, XOR_RIGHT_IS_MISSING_ROLES); return elements.toArray(new ConfigurableElement[elements.size()]); } public static class LogicalRoleMappers implements ConfigurableElement { private final String[] dynamicLogicals; public LogicalRoleMappers(String... dynamicLogicals) { this.dynamicLogicals = dynamicLogicals; } @Override public void create(CLIWrapper cli) throws Exception { for (String log : dynamicLogicals) { cli.sendLine("/subsystem=elytron/logical-role-mapper=" + log); } } @Override public void remove(CLIWrapper cli) throws Exception { for (String log : dynamicLogicals) { int opIdx = log.indexOf(':'); String newLog = log.substring(0, opIdx + 1) + "remove()"; cli.sendLine("/subsystem=elytron/logical-role-mapper=" + newLog); } } @Override public String getName() { return "logical-role-mapper"; } } } }
30,838
48.660225
128
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/AggregateRoleMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE1; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE2; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.createDeploymentForPrintingRoles; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.PROPERTIES_REALM_NAME; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.addSecurityDomainWithRoleMapper; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.PropertiesRealm; /** * Test case for Elytron Aggregate Role Mapper. * * Given: Authentication to secured application is backed by Elytron Properties Realm <br> * and Properties Realm uses the Aggregate Role Mapper for mapping roles. * * @author olukas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AggregateRoleMapperTestCase.ServerSetup.class}) public class AggregateRoleMapperTestCase extends AbstractRoleMapperTest { private static final String AGGREGATE_MAPPER = "simple-aggregate-mapper"; private static final String USER = "user"; private static final String PASSWORD = "password"; private static final String ROLE_PREFIX1 = "1"; private static final String ROLE_PREFIX2 = "2"; private static final String ROLE1_WITH_CORRECT_PREFIX = ROLE_PREFIX2 + ROLE_PREFIX1 + ROLE1; private static final String ROLE1_WITH_WRONG_PREFIX = ROLE_PREFIX1 + ROLE_PREFIX2 + ROLE1; private static final String ROLE1_WITH_HALF_PREFIX = ROLE_PREFIX1 + ROLE1; private static final String ROLE2_WITH_CORRECT_PREFIX = ROLE_PREFIX2 + ROLE_PREFIX1 + ROLE2; private static final String ROLE2_WITH_WRONG_PREFIX = ROLE_PREFIX1 + ROLE_PREFIX2 + ROLE2; private static final String ROLE2_WITH_HALF_PREFIX = ROLE_PREFIX1 + ROLE2; @Override protected String[] allTestedRoles() { return new String[]{ROLE1, ROLE1_WITH_CORRECT_PREFIX, ROLE1_WITH_WRONG_PREFIX, ROLE1_WITH_HALF_PREFIX, ROLE2_WITH_CORRECT_PREFIX, ROLE2_WITH_WRONG_PREFIX, ROLE2_WITH_HALF_PREFIX}; } @Deployment(name = AGGREGATE_MAPPER) public static WebArchive deploymentAggregate() { return createDeploymentForPrintingRoles(AGGREGATE_MAPPER); } /** * Given: Add Prefix Role Mapper (1) with attribute prefix='1' is added to configuration <br> * and Add Prefix Role Mapper (2) with attribute prefix='2' is added to configuration <br> * and Aggregate Role Mapper uses mentioned Add Prefix Role Mappers in order 1, 2 <br> * and roles property file maps roles Role1 and Role2 for the user. <br> * When the user is authenticated <br> * then just roles 21Role1 and 21Role2 should be assigned to the user (which means that both role mappers have been called * and their order has been correct). */ @Test @OperateOnDeployment(AGGREGATE_MAPPER) public void testTwoMappers(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER, PASSWORD, ROLE1_WITH_CORRECT_PREFIX, ROLE2_WITH_CORRECT_PREFIX); } public static class ServerSetup extends AbstractElytronSetupTask { private static final String ADD_PREFIX_ROLE_MAPPER1 = "add-prefix-role-mapper1"; private static final String ADD_PREFIX_ROLE_MAPPER2 = "add-prefix-role-mapper2"; @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); elements.add(new AddPrefixRoleMapperTestCase.ServerSetup.AddPrefixRoleMappers( String.format("%s:add(prefix=%s)", ADD_PREFIX_ROLE_MAPPER1, ROLE_PREFIX1), String.format("%s:add(prefix=%s)", ADD_PREFIX_ROLE_MAPPER2, ROLE_PREFIX2) )); elements.add(new AggregateRoleMappers( String.format("%s:add(role-mappers=[%s,%s])", AGGREGATE_MAPPER, ADD_PREFIX_ROLE_MAPPER1, ADD_PREFIX_ROLE_MAPPER2) )); elements.add(PropertiesRealm.builder().withName(PROPERTIES_REALM_NAME) .withUser(USER, PASSWORD, ROLE1, ROLE2) .build()); addSecurityDomainWithRoleMapper(elements, AGGREGATE_MAPPER); return elements.toArray(new ConfigurableElement[elements.size()]); } public static class AggregateRoleMappers implements ConfigurableElement { private final String[] dynamicAggregates; public AggregateRoleMappers(String... dynamicAggregates) { this.dynamicAggregates = dynamicAggregates; } @Override public void create(CLIWrapper cli) throws Exception { for (String agg : dynamicAggregates) { cli.sendLine("/subsystem=elytron/aggregate-role-mapper=" + agg); } } @Override public void remove(CLIWrapper cli) throws Exception { for (String agg : dynamicAggregates) { int opIdx = agg.indexOf(':'); String newAgg = agg.substring(0, opIdx + 1) + "remove()"; cli.sendLine("/subsystem=elytron/aggregate-role-mapper=" + newAgg); } } @Override public String getName() { return "aggregate-role-mapper"; } } } }
7,247
45.165605
133
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/AbstractRoleMapperTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.security.auth.login.LoginException; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.integration.security.common.servlets.RolePrintingServlet; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import static org.junit.Assert.fail; /** * Abstract class for Role Mapper related test cases. * * @author olukas */ public abstract class AbstractRoleMapperTest { public static final String ROLE1 = "Role1"; public static final String ROLE2 = "Role2"; public static final String ROLE3 = "Role3"; public static final String ROLE4 = "Role4"; public static WebArchive createDeploymentForPrintingRoles(String securityDomainName) { final WebArchive war = ShrinkWrap.create(WebArchive.class, securityDomainName + ".war"); war.addClasses(RolePrintingServlet.class); war.addAsWebInfResource(AbstractRoleMapperTest.class.getPackage(), "role-mapper-web.xml", "web.xml"); war.addAsWebInfResource(Utils.getJBossWebXmlAsset(securityDomainName), "jboss-web.xml"); return war; } public void testAssignedRoles(URL webAppURL, String username, String password, String... assignedRoles) throws IOException, URISyntaxException, LoginException { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL); final String rolesResponse = Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_OK); final List<String> assignedRolesList = Arrays.asList(assignedRoles); for (String role : allTestedRoles()) { if (assignedRolesList.contains(role)) { assertInRole(rolesResponse, role); } else { assertNotInRole(rolesResponse, role); } } } public void assertNoRoleAssigned(URL webAppURL, String username, String password) throws Exception { final URL rolesPrintingURL = prepareRolesPrintingURL(webAppURL); Utils.makeCallWithBasicAuthn(rolesPrintingURL, username, password, SC_FORBIDDEN); } private URL prepareRolesPrintingURL(URL webAppURL) throws MalformedURLException { final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); for (final String role : allTestedRoles()) { qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role)); } String queryRoles = URLEncodedUtils.format(qparams, StandardCharsets.UTF_8); return new URL(webAppURL.toExternalForm() + RolePrintingServlet.SERVLET_PATH.substring(1) + "?" + queryRoles); } private void assertInRole(final String rolePrintResponse, String role) { if (!StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Missing role '" + role + "' assignment"); } } private void assertNotInRole(final String rolePrintResponse, String role) { if (StringUtils.contains(rolePrintResponse, "," + role + ",")) { fail("Unexpected role '" + role + "' assignment"); } } protected abstract String[] allTestedRoles(); }
4,813
41.982143
111
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/AddSuffixRoleMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE1; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE2; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.createDeploymentForPrintingRoles; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.PROPERTIES_REALM_NAME; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.addSecurityDomainWithRoleMapper; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.PropertiesRealm; /** * Test case for Elytron Add Suffix Role Mapper. * * Given: Authentication to secured application is backed by Elytron Properties Realm <br> * and Properties Realm uses the Add Suffix Role Mapper for mapping roles <br> * and the Add Suffix Role Mapper with attribute suffix='Suf' is added to configuration. * * @author olukas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AddSuffixRoleMapperTestCase.ServerSetup.class}) public class AddSuffixRoleMapperTestCase extends AbstractRoleMapperTest { private static final String ADD_SUFFIX_MAPPER = "simple-add-suffix-role-mapper"; private static final String ROLE_SUFFIX = "Suf"; private static final String USER_WITHOUT_ROLES = "userWithoutRoles"; private static final String USER_WITH_ROLE1 = "userWithRole1"; private static final String USER_WITH_TWO_ROLES = "userWithTwoRoles"; private static final String PASSWORD = "password"; private static final String ROLE1_WITH_SUFFIX = ROLE1 + ROLE_SUFFIX; private static final String ROLE2_WITH_SUFFIX = ROLE2 + ROLE_SUFFIX; @Override protected String[] allTestedRoles() { return new String[]{ROLE1, ROLE2, ROLE1_WITH_SUFFIX, ROLE2_WITH_SUFFIX}; } @Deployment(name = ADD_SUFFIX_MAPPER) public static WebArchive deploymentAddSuffix() { return createDeploymentForPrintingRoles(ADD_SUFFIX_MAPPER); } /** * Given: Roles property file maps no role for the user. <br> * When the user is authenticated <br> * then no role should be assigned to the user. <br> */ @Test @OperateOnDeployment(ADD_SUFFIX_MAPPER) public void testUserWithoutRoles(@ArquillianResource URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER_WITHOUT_ROLES, PASSWORD); } /** * Given: Roles property file maps role Role1 for the user. <br> * When the user is authenticated <br> * then just role Role1Suf should be assigned to the user. */ @Test @OperateOnDeployment(ADD_SUFFIX_MAPPER) public void testUserWithOneRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE1, PASSWORD, ROLE1_WITH_SUFFIX); } /** * Given: Roles property file maps roles Role1 and Role2 for the user. <br> * When the user is authenticated <br> * then just roles Role1Suf and Role2Suf should be assigned to the user. */ @Test @OperateOnDeployment(ADD_SUFFIX_MAPPER) public void testUserWithTwoRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_TWO_ROLES, PASSWORD, ROLE1_WITH_SUFFIX, ROLE2_WITH_SUFFIX); } public static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); elements.add(new AddSuffixRoleMappers( String.format("%s:add(suffix=%s)", ADD_SUFFIX_MAPPER, ROLE_SUFFIX) )); elements.add(PropertiesRealm.builder().withName(PROPERTIES_REALM_NAME) .withUser(USER_WITHOUT_ROLES, PASSWORD) .withUser(USER_WITH_ROLE1, PASSWORD, ROLE1) .withUser(USER_WITH_TWO_ROLES, PASSWORD, ROLE1, ROLE2) .build()); addSecurityDomainWithRoleMapper(elements, ADD_SUFFIX_MAPPER); return elements.toArray(new ConfigurableElement[elements.size()]); } public static class AddSuffixRoleMappers implements ConfigurableElement { private final String[] dynamicSuffixes; public AddSuffixRoleMappers(String... dynamicSuffixes) { this.dynamicSuffixes = dynamicSuffixes; } @Override public void create(CLIWrapper cli) throws Exception { for (String sfx : dynamicSuffixes) { cli.sendLine("/subsystem=elytron/add-suffix-role-mapper=" + sfx); } } @Override public void remove(CLIWrapper cli) throws Exception { for (String sfx : dynamicSuffixes) { int opIdx = sfx.indexOf(':'); String newSfx = sfx.substring(0, opIdx + 1) + "remove()"; cli.sendLine("/subsystem=elytron/add-suffix-role-mapper=" + newSfx); } } @Override public String getName() { return "add-suffix-role-mapper"; } } } }
7,027
40.585799
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/rolemappers/AddPrefixRoleMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.rolemappers; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE1; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.ROLE2; import static org.wildfly.test.integration.elytron.rolemappers.AbstractRoleMapperTest.createDeploymentForPrintingRoles; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.PROPERTIES_REALM_NAME; import static org.wildfly.test.integration.elytron.rolemappers.RoleMapperSetupUtils.addSecurityDomainWithRoleMapper; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.PropertiesRealm; /** * Test case for Elytron Add Prefix Role Mapper. * * Given: Authentication to secured application is backed by Elytron Properties Realm <br> * and Properties Realm uses the Add Prefix Role Mapper for mapping roles <br> * and the Add Prefix Role Mapper with attribute prefix='Pre' is added to configuration. * * @author olukas */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({AddPrefixRoleMapperTestCase.ServerSetup.class}) public class AddPrefixRoleMapperTestCase extends AbstractRoleMapperTest { private static final String ADD_PREFIX_MAPPER = "simple-add-prefix-role-mapper"; private static final String ROLE_PREFIX = "Pre"; private static final String USER_WITHOUT_ROLES = "userWithoutRoles"; private static final String USER_WITH_ROLE1 = "userWithRole1"; private static final String USER_WITH_TWO_ROLES = "userWithTwoRoles"; private static final String PASSWORD = "password"; private static final String ROLE1_WITH_PREFIX = ROLE_PREFIX + ROLE1; private static final String ROLE2_WITH_PREFIX = ROLE_PREFIX + ROLE2; @Override protected String[] allTestedRoles() { return new String[]{ROLE1, ROLE2, ROLE1_WITH_PREFIX, ROLE2_WITH_PREFIX}; } @Deployment(name = ADD_PREFIX_MAPPER) public static WebArchive deploymentAddPrefix() { return createDeploymentForPrintingRoles(ADD_PREFIX_MAPPER); } /** * Given: Roles property file maps no role for the user. <br> * When the user is authenticated <br> * then no role should be assigned to the user. <br> */ @Test @OperateOnDeployment(ADD_PREFIX_MAPPER) public void testUserWithoutRoles(@ArquillianResource URL webAppURL) throws Exception { assertNoRoleAssigned(webAppURL, USER_WITHOUT_ROLES, PASSWORD); } /** * Given: Roles property file maps role Role1 for the user. <br> * When the user is authenticated <br> * then just role PreRole1 should be assigned to the user. */ @Test @OperateOnDeployment(ADD_PREFIX_MAPPER) public void testUserWithOneRole(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_ROLE1, PASSWORD, ROLE1_WITH_PREFIX); } /** * Given: Roles property file maps roles Role1 and Role2 for the user. <br> * When the user is authenticated <br> * then just roles PreRole1 and PreRole2 should be assigned to the user. */ @Test @OperateOnDeployment(ADD_PREFIX_MAPPER) public void testUserWithTwoRoles(@ArquillianResource URL webAppURL) throws Exception { testAssignedRoles(webAppURL, USER_WITH_TWO_ROLES, PASSWORD, ROLE1_WITH_PREFIX, ROLE2_WITH_PREFIX); } public static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); elements.add(new AddPrefixRoleMappers( String.format("%s:add(prefix=%s)", ADD_PREFIX_MAPPER, ROLE_PREFIX) )); elements.add(PropertiesRealm.builder().withName(PROPERTIES_REALM_NAME) .withUser(USER_WITHOUT_ROLES, PASSWORD) .withUser(USER_WITH_ROLE1, PASSWORD, ROLE1) .withUser(USER_WITH_TWO_ROLES, PASSWORD, ROLE1, ROLE2) .build()); addSecurityDomainWithRoleMapper(elements, ADD_PREFIX_MAPPER); return elements.toArray(new ConfigurableElement[elements.size()]); } public static class AddPrefixRoleMappers implements ConfigurableElement { private final String[] dynamicPrefixes; public AddPrefixRoleMappers(String... dynamicPrefixes) { this.dynamicPrefixes = dynamicPrefixes; } @Override public void create(CLIWrapper cli) throws Exception { for (String pfx : dynamicPrefixes) { cli.sendLine("/subsystem=elytron/add-prefix-role-mapper=" + pfx); } } @Override public void remove(CLIWrapper cli) throws Exception { for (String pfx : dynamicPrefixes) { int opIdx = pfx.indexOf(':'); String newPfx = pfx.substring(0, opIdx + 1) + "remove()"; cli.sendLine("/subsystem=elytron/add-prefix-role-mapper=" + newPfx); } } @Override public String getName() { return "add-prefix-role-mapper"; } } } }
7,026
40.827381
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/WhoAmIServlet.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.concurrent.Callable; import jakarta.annotation.security.DeclareRoles; import jakarta.ejb.EJB; import jakarta.ejb.EJBException; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jboss.as.test.shared.integration.ejb.security.Util; /** * @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a> * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class WhoAmIServlet extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private Entry bean; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String username = req.getParameter("username"); String password = req.getParameter("password"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { Callable<Void> callable = () -> { writer.write(bean.whoAmI()); return null; }; Util.switchIdentity(username, password, callable); } catch (Exception e) { throw new IOException("Unexpected failure", e); } } else if ("doubleWhoAmI".equals(method)) { String[] response; try { if (username != null && password != null) { response = bean.doubleWhoAmI(username, password); } else { response = bean.doubleWhoAmI(); } } catch (EJBException e) { resp.setStatus(SC_FORBIDDEN); e.printStackTrace(new PrintWriter(writer)); return; } catch (Exception e) { throw new ServletException("Unexpected failure", e); } writer.write(response[0] + "," + response[1]); } else if ("doIHaveRole".equals(method)) { try { Callable<Void> callable = () -> { writer.write(String.valueOf(bean.doIHaveRole(role))); return null; }; Util.switchIdentity(username, password, callable); } catch (Exception e) { throw new IOException("Unexpected failure", e); } } else if ("doubleDoIHaveRole".equals(method)) { try { boolean[] response = null; if (username != null && password != null) { response = bean.doubleDoIHaveRole(role, username, password); } else { response = bean.doubleDoIHaveRole(role); } writer.write(String.valueOf(response[0]) + "," + String.valueOf(response[1])); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } }
4,838
38.991736
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/AuthenticationWithSourceAddressRoleDecoderMismatchTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import java.io.File; import java.io.IOException; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.categories.CommonCriteria; import org.jboss.ejb.client.RequestSendFailedException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test authentication with the use of a source address role decoder where the IP address of the remote * client does not match the address configured on the decoder. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ AuthenticationWithSourceAddressRoleDecoderMismatchTestCase.ElytronDomainSetupOverride.class, EjbElytronDomainSetup.class, ServletElytronDomainSetup.class }) @Category(CommonCriteria.class) public class AuthenticationWithSourceAddressRoleDecoderMismatchTestCase { private static final String APPLICATION_NAME = "authentication-with-source-address-role-decoder"; @ArquillianResource private ManagementClient mgmtClient; @Deployment public static JavaArchive createDeployment() throws IOException { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, APPLICATION_NAME + ".jar"); jar.addClasses(SecurityInformation.class, SecuredBean.class); return jar; } /* The Jakarta Enterprise Beans being used in this test class is secured using the "elytron-tests" security domain. This security domain is configured with: 1) a source-address-role-decoder that assigns the "admin" role if the IP address of the remote client is 999.999.999.999 2) a permission-mapper that assigns the "LoginPermission" if the identity has the "admin" role unless the principal is "user2" */ @Test public void testAuthenticationIPAddressMismatch() throws Exception { Properties ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user1", "password1"); SecurityInformation targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user2", "password2"); targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } } @Test public void testAuthenticationIPAddressMismatchWithSecurityRealmRole() throws Exception { final Properties ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "admin", "admin"); final SecurityInformation targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); Assert.assertEquals("admin", targetBean.getPrincipalName()); } @Test public void testAuthenticationInvalidCredentials() throws Exception { Properties ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user1", "badpassword"); SecurityInformation targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user2", "badpassword"); targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } } private static Properties createEjbClientConfiguration(String hostName, String user, String password) { final Properties pr = new Properties(); pr.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false"); pr.put("remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS", "JBOSS-LOCAL-USER"); pr.put("remote.connections", "default"); pr.put("remote.connection.default.host", hostName); pr.put("remote.connection.default.port", "8080"); pr.put("remote.connection.default.username", user); pr.put("remote.connection.default.password", password); return pr; } private static <T> T lookupEJB(Class<? extends T> beanImplClass, Class<T> remoteInterface, Properties ejbProperties) throws Exception { final Properties jndiProperties = new Properties(); jndiProperties.putAll(ejbProperties); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); return (T) context.lookup("ejb:/" + APPLICATION_NAME + "/" + beanImplClass.getSimpleName() + "!" + remoteInterface.getName()); } static class ElytronDomainSetupOverride extends ElytronDomainSetup { public ElytronDomainSetupOverride() { super(new File(AuthenticationWithSourceAddressRoleDecoderMismatchTestCase.class.getResource("users.properties").getFile()).getAbsolutePath(), new File(AuthenticationWithSourceAddressRoleDecoderMismatchTestCase.class.getResource("roles.properties").getFile()).getAbsolutePath(), "elytron-tests", "ipPermissionMapper", "999.999.999.999"); } } }
7,768
47.55625
171
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/Entry.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import jakarta.ejb.Local; /** * Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Local public interface Entry { /** * @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal() */ String whoAmI(); /** * Obtains the name of the Principal obtained from a call to EJBContext.getCallerPrincipal() * both for the bean called and also from a call to a second bean. * * @return An array containing the name from the local call first followed by the name from * the second call. */ String[] doubleWhoAmI(); /** * As doubleWhoAmI except the user is switched before the second call. * * @see this.doubleWhoAmI() * @param username - The username to use for the second call. * @param password - The password to use for the second call. * @return An array containing the name from the local call first followed by the name from * the second call. * @throws Exception - If there is an unexpected failure establishing the security context for * the second call. */ String[] doubleWhoAmI(String username, String password) throws Exception; /** * @param roleName - The role to check. * @return the response from EJBContext.isCallerInRole() with the supplied role name. */ boolean doIHaveRole(String roleName); /** * Calls EJBContext.isCallerInRole() with the supplied role name and then calls a second bean * which makes the same call. * * @param roleName - the role name to check. * @return the values from the isCallerInRole() calls, the EntryBean is first and the second bean * second. */ boolean[] doubleDoIHaveRole(String roleName); /** * As doubleDoIHaveRole except the user is switched before the second call. * * @see this.doubleDoIHaveRole(String) * @param roleName - The role to check. * @param username - The username to use for the second call. * @param password - The password to use for the second call. * @return @return the values from the isCallerInRole() calls, the EntryBean is first and the second bean * second. * @throws Exception - If their is an unexpected failure. */ boolean[] doubleDoIHaveRole(String roleName, String username, String password) throws Exception; }
3,562
38.153846
109
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/AuthenticationTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import static org.wildfly.test.integration.elytron.util.HttpUtil.get; import static java.util.concurrent.TimeUnit.SECONDS; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.SocketPermission; import java.net.URL; import java.security.Principal; import java.util.concurrent.Callable; import jakarta.ejb.EJB; import javax.security.auth.AuthPermission; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.categories.CommonCriteria; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.integration.ejb.security.Util; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.integration.elytron.ejb.authentication.EntryBean; import org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean; import org.wildfly.test.integration.elytron.util.HttpUtil; import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test case to hold the authentication scenarios, these range from calling a servlet which calls a bean to calling a bean which * calls another bean to calling a bean which re-authenticated before calling another bean. * * @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a> * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> * * NOTE: References in this file to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted. */ @RunWith(Arquillian.class) @ServerSetup({ AuthenticationTestCase.ElytronDomainSetupOverride.class, EjbElytronDomainSetup.class, ServletElytronDomainSetup.class }) @Category(CommonCriteria.class) public class AuthenticationTestCase { /* * Authentication Scenarios * * Client -> Bean * Client -> Bean -> Bean * Client -> Bean (Re-auth) -> Bean * Client -> Servlet -> Bean * Client -> Servlet (Re-auth) -> Bean * Client -> Servlet -> Bean -> Bean * Client -> Servlet -> Bean (Re Auth) -> Bean */ @ArquillianResource private URL url; @Deployment public static Archive<?> deployment() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = AuthenticationTestCase.class.getPackage(); // using JavaArchive doesn't work, because of a bug in Arquillian, it only deploys wars properly final WebArchive war = ShrinkWrap.create(WebArchive.class, "ejb3security.war") .addPackage(WhoAmIBean.class.getPackage()).addPackage(EntryBean.class.getPackage()) .addClass(WhoAmI.class).addClass(Util.class).addClass(Entry.class).addClass(HttpUtil.class) .addClasses(WhoAmIServlet.class, AuthenticationTestCase.class) .addClasses(ElytronDomainSetup.class, EjbElytronDomainSetup.class, ServletElytronDomainSetup.class) .addAsResource(currentPackage, "users.properties", "users.properties") .addAsResource(currentPackage, "roles.properties", "roles.properties") .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml") .addAsWebInfResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsManifestResource(new StringAsset("Manifest-Version: 1.0\nDependencies: org.jboss.as.controller-client,org.jboss.dmr\n"), "MANIFEST.MF") .addAsManifestResource(createPermissionsXmlAsset( // login module needs to modify principal to commit logging in new AuthPermission("modifyPrincipals"), // AuthenticationTestCase#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // AuthenticationTestCase#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // TestSuiteEnvironment reads system properties new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); war.addPackage(CommonCriteria.class.getPackage()); return war; } @EJB(mappedName = "java:global/ejb3security/WhoAmIBean!org.wildfly.test.integration.elytron.ejb.WhoAmI") private WhoAmI whoAmIBean; @EJB(mappedName = "java:global/ejb3security/EntryBean!org.wildfly.test.integration.elytron.ejb.Entry") private Entry entryBean; @Test public void testAuthentication() throws Exception { final Callable<Void> callable = () -> { String response = entryBean.whoAmI(); assertEquals("user1", response); return null; }; Util.switchIdentity("user1", "password1", callable); } @Test public void testAuthentication_BadPwd() throws Exception { Util.switchIdentity("user1", "wrong_password", () -> entryBean.whoAmI(), true); } @Test public void testAuthentication_TwoBeans() throws Exception { final Callable<Void> callable = () -> { String[] response = entryBean.doubleWhoAmI(); assertEquals("user1", response[0]); assertEquals("user1", response[1]); return null; }; Util.switchIdentity("user1", "password1", callable); } @Test public void testAuthentication_TwoBeans_ReAuth() throws Exception { final Callable<Void> callable = () -> { String[] response = entryBean.doubleWhoAmI("user2", "password2"); assertEquals("user1", response[0]); assertEquals("user2", response[1]); return null; }; Util.switchIdentity("user1", "password1", callable); } // TODO - Similar test with first bean @RunAs - does it make sense to also manually switch? @Test public void testAuthentication_TwoBeans_ReAuth_BadPwd() throws Exception { Util.switchIdentity("user1", "password1", () -> entryBean.doubleWhoAmI("user2", "wrong_password"), true); } @Test public void testAuthenticatedCall() throws Exception { // TODO: this is not spec final Callable<Void> callable = () -> { try { final Principal principal = whoAmIBean.getCallerPrincipal(); assertNotNull("EJB 3.1 FR 17.6.5 The container must never return a null from the getCallerPrincipal method.", principal); assertEquals("user1", principal.getName()); } catch (RuntimeException e) { e.printStackTrace(); fail("EJB 3.1 FR 17.6.5 The EJB container must provide the caller’s security context information during the execution of a business method (" + e.getMessage() + ")"); } return null; }; Util.switchIdentitySCF("user1", "password1", callable); } @Test public void testUnauthenticated() throws Exception { try { final Principal principal = whoAmIBean.getCallerPrincipal(); assertNotNull("EJB 3.1 FR 17.6.5 The container must never return a null from the getCallerPrincipal method.", principal); // TODO: where is 'anonymous' configured? assertEquals("anonymous", principal.getName()); } catch (RuntimeException e) { e.printStackTrace(); fail("EJB 3.1 FR 17.6.5 The EJB container must provide the caller’s security context information during the execution of a business method (" + e.getMessage() + ")"); } } @Test public void testAuthentication_ViaServlet() throws Exception { final String result = getWhoAmI("?method=whoAmI"); assertEquals("user1", result); } @Test public void testAuthentication_ReAuth_ViaServlet() throws Exception { final String result = getWhoAmI("?method=whoAmI&username=user2&password=password2"); assertEquals("user2", result); } @Test public void testAuthentication_TwoBeans_ViaServlet() throws Exception { final String result = getWhoAmI("?method=doubleWhoAmI"); assertEquals("user1,user1", result); } @Test public void testAuthentication_TwoBeans_ReAuth_ViaServlet() throws Exception { final String result = getWhoAmI("?method=doubleWhoAmI&username=user2&password=password2"); assertEquals("user1,user2", result); } @Test @RunAsClient public void testAuthentication_TwoBeans_ReAuth__BadPwd_ViaServlet() throws Exception { try { getWhoAmI("?method=doubleWhoAmI&username=user2&password=bad_password"); fail("Expected IOException"); } catch (IOException e) { final String message = e.getMessage(); assertTrue("Response should contain 'ELY01151: Evidence Verification Failed'", message.contains("ELY01151:")); assertTrue("Response should contain 'jakarta.ejb.EJBException' or 'jakarta.ejb.EJBException'", message.contains("jakarta.ejb.EJBException") || message.contains("jakarta.ejb.EJBException")); } } /* * isCallerInRole Scenarios */ @Test public void testICIRSingle() throws Exception { final Callable<Void> callable = () -> { assertTrue(entryBean.doIHaveRole("Users")); assertTrue(entryBean.doIHaveRole("Role1")); assertFalse(entryBean.doIHaveRole("Role2")); return null; }; Util.switchIdentity("user1", "password1", callable); } @Test public void testICIR_TwoBeans() throws Exception { final Callable<Void> callable = () -> { boolean[] response; response = entryBean.doubleDoIHaveRole("Users"); assertTrue(response[0]); assertTrue(response[1]); response = entryBean.doubleDoIHaveRole("Role1"); assertTrue(response[0]); assertTrue(response[1]); response = entryBean.doubleDoIHaveRole("Role2"); assertFalse(response[0]); assertFalse(response[1]); return null; }; Util.switchIdentity("user1", "password1", callable); } @Test public void testICIR_TwoBeans_ReAuth() throws Exception { final Callable<Void> callable = () -> { boolean[] response; response = entryBean.doubleDoIHaveRole("Users", "user2", "password2"); assertTrue(response[0]); assertTrue(response[1]); response = entryBean.doubleDoIHaveRole("Role1", "user2", "password2"); assertTrue(response[0]); assertFalse(response[1]); response = entryBean.doubleDoIHaveRole("Role2", "user2", "password2"); assertFalse(response[0]); assertTrue(response[1]); return null; }; Util.switchIdentity("user1", "password1", callable); } private String getWhoAmI(String queryString) throws Exception { return get(url + "whoAmI" + queryString, "user1", "password1", 10, SECONDS); } @Test public void testICIR_ViaServlet() throws Exception { String result = getWhoAmI("?method=doIHaveRole&role=Users"); assertEquals("true", result); result = getWhoAmI("?method=doIHaveRole&role=Role1"); assertEquals("true", result); result = getWhoAmI("?method=doIHaveRole&role=Role2"); assertEquals("false", result); } @Test public void testICIR_ReAuth_ViaServlet() throws Exception { String result = getWhoAmI("?method=doIHaveRole&role=Users&username=user2&password=password2"); assertEquals("true", result); result = getWhoAmI("?method=doIHaveRole&role=Role1&username=user2&password=password2"); assertEquals("false", result); result = getWhoAmI("?method=doIHaveRole&role=Role2&username=user2&password=password2"); assertEquals("true", result); } @Test public void testICIR_TwoBeans_ViaServlet() throws Exception { String result = getWhoAmI("?method=doubleDoIHaveRole&role=Users"); assertEquals("true,true", result); result = getWhoAmI("?method=doubleDoIHaveRole&role=Role1"); assertEquals("true,true", result); result = getWhoAmI("?method=doubleDoIHaveRole&role=Role2"); assertEquals("false,false", result); } @Test public void testICIR_TwoBeans_ReAuth_ViaServlet() throws Exception { String result = getWhoAmI("?method=doubleDoIHaveRole&role=Users&username=user2&password=password2"); assertEquals("true,true", result); result = getWhoAmI("?method=doubleDoIHaveRole&role=Role1&username=user2&password=password2"); assertEquals("true,false", result); result = getWhoAmI("?method=doubleDoIHaveRole&role=Role2&username=user2&password=password2"); assertEquals("false,true", result); } /* * isCallerInRole Scenarios with @RunAs Defined * * EJB 3.1 FR 17.2.5.2 isCallerInRole tests the principal that represents the caller of the enterprise bean, not the * principal that corresponds to the run-as security identity for the bean. */ // 17.2.5 - Programatic Access to Caller's Security Context // Include tests for methods not implemented to pick up if later they are implemented. // 17.2.5.1 - Use of getCallerPrincipal // 17.6.5 - Security Methods on EJBContext // 17.2.5.2 - Use of isCallerInRole // 17.2.5.3 - Declaration of Security Roles Referenced from the Bean's Code // 17.3.1 - Security Roles // 17.3.2.1 - Specification of Method Permissions with Metadata Annotation // 17.3.2.2 - Specification of Method Permissions in the Deployment Descriptor // 17.3.2.3 - Unspecified Method Permission // 17.3.3 - Linking Security Role References to Security Roles // 17.3.4 - Specification on Security Identities in the Deployment Descriptor // (Include permutations for overrides esp where deployment descriptor removes access) // 17.3.4.1 - Run-as // 17.5 EJB Client Responsibilities // A transactional client can not change principal association within transaction. // A session bean client must not change the principal association for the duration of the communication. // If transactional requests within a single transaction arrive from multiple clients all must be associated // with the same security context. // 17.6.3 - Security Mechanisms // 17.6.4 - Passing Principals on EJB Calls // 17.6.6 - Secure Access to Resource Managers // 17.6.7 - Principal Mapping // 17.6.9 - Runtime Security Enforcement // 17.6.10 - Audit Trail static class ElytronDomainSetupOverride extends ElytronDomainSetup { public ElytronDomainSetupOverride() { super(new File(AuthenticationTestCase.class.getResource("users.properties").getFile()).getAbsolutePath(), new File(AuthenticationTestCase.class.getResource("roles.properties").getFile()).getAbsolutePath()); } } }
17,407
43.750643
157
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/DefaultElytronEjbSecurityDomainTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.io.File; import java.security.Principal; import java.util.concurrent.Callable; import jakarta.ejb.EJB; import javax.naming.Context; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.shared.integration.ejb.security.Util; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.integration.elytron.ejb.authentication.EntryBean; import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; /** * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2018 Red Hat, Inc. * Test case on a deployment containing a secured Jakarta Enterprise Beans with non-default security domain and an unsecured one. * Test passes if deployment is successful and functional. */ @RunWith(Arquillian.class) @ServerSetup({ DefaultElytronEjbSecurityDomainTestCase.ElytronDomainSetupTestCaseOverride.class, EjbElytronDomainSetup.class }) public class DefaultElytronEjbSecurityDomainTestCase { @ArquillianResource private Context ctx; @EJB(mappedName = "java:global/ejb3security/WhoAmIBean!org.wildfly.test.integration.elytron.ejb.WhoAmI") private WhoAmI securedBean; @Deployment public static JavaArchive createDeployment() { final Package currentPackage = DefaultElytronEjbSecurityDomainTestCase.class.getPackage(); return ShrinkWrap.create(JavaArchive.class, "ejb-security-domain-test.jar") .addPackage(DefaultElytronEjbSecurityDomainTestCase.class.getPackage()) .addPackage(EjbUnsecuredBean.class.getPackage()) .addPackage(org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean.class.getPackage()) .addPackage(EntryBean.class.getPackage()) .addClass(Util.class) .addClass(WhoAmI.class) .addClass(org.jboss.as.controller.operations.common.Util.class) .addClasses(ElytronDomainSetup.class, EjbElytronDomainSetup.class) .addAsResource(currentPackage, "users.properties", "users.properties") .addAsResource(currentPackage, "roles.properties", "roles.properties") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsManifestResource(createPermissionsXmlAsset(new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate")), "permissions.xml"); } @Test public void testSecurityOnTwoBeansInAbsenceOfExplicitSecurityDomain() throws Exception { final EjbUnsecuredBean unsecuredBean = InitialContext .doLookup("java:module/" + EjbUnsecuredBean.class.getSimpleName()); final String echoResult = unsecuredBean.echo("unsecuredBeanEcho"); assertEquals("unsecuredBeanEcho", echoResult); final Callable<Void> callable = () -> { try { final Principal principal = securedBean.getCallerPrincipal(); assertNotNull("EJB must never return a null from the getCallerPrincipal method.", principal); assertEquals("user1", principal.getName()); } catch (RuntimeException e) { fail("EJB must provide the caller’s security context information during the execution of a business method (" + e.getMessage() + ")"); } return null; }; Util.switchIdentitySCF("user1", "password1", callable); } public static class ElytronDomainSetupTestCaseOverride extends ElytronDomainSetup { public ElytronDomainSetupTestCaseOverride() { super(new File(AuthenticationTestCase.class.getResource("users.properties").getFile()).getAbsolutePath(), new File(AuthenticationTestCase.class.getResource("roles.properties").getFile()).getAbsolutePath()); } } }
5,541
47.191304
168
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/RolePropagationTestImpl.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.Stateless; /** * EJB that will be called to demonstrate that roles have been configured properly even without specifying security domain explicitly. */ @Stateless public class RolePropagationTestImpl implements RolePropagationTest { @Override @RolesAllowed("TEST") public String testRunAsWithoutSecDomainSpecified() { return "access allowed"; } }
1,517
37.923077
134
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/RolePropagationWithoutExplicitSecDomainElytronTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class RolePropagationWithoutExplicitSecDomainElytronTest { private static final String BEAN_DEPLOYMENT = "PostConstructStartupSingletonBeanDeployment"; @ArquillianResource private Deployer deployer; @Deployment(name = BEAN_DEPLOYMENT, managed = false) public static WebArchive createDeployment() { final WebArchive war = ShrinkWrap.create(WebArchive.class, "PostConstructStartupSingletonBeanDeployment" + ".war"); war.addClasses(RolePropagationTestSecuredBean.class); war.addClasses(RolePropagationTest.class); war.addClasses(RolePropagationTestImpl.class); return war; } @Test @RunAsClient public void testStartupSingletonSecuredBeanRolePropagation() { try { deployer.deploy(BEAN_DEPLOYMENT); } catch (Exception ex) { Assert.fail("Deployment should not fail because TEST role should have been propagated from RunAs annotation."); } finally { deployer.undeploy(BEAN_DEPLOYMENT); } } }
2,599
39.625
123
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/RolePropagationTest.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; public interface RolePropagationTest { String testRunAsWithoutSecDomainSpecified(); }
1,164
42.148148
70
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/IdentityPropagationTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import static java.util.concurrent.TimeUnit.SECONDS; import static org.jboss.as.cli.Util.REMOVE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.operations.common.Util.createAddOperation; import static org.jboss.as.controller.operations.common.Util.getUndefineAttributeOperation; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.wildfly.test.integration.elytron.util.HttpUtil.get; import java.io.File; import java.net.SocketPermission; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase; import org.jboss.as.test.integration.management.util.ModelUtil; import org.jboss.as.test.shared.ServerReload; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.as.test.shared.integration.ejb.security.Util; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean; import org.wildfly.test.integration.elytron.ejb.propagation.local.ComplexServletLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.EntryBeanLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.EntryLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.ManagementBeanLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.ServletOnlyLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.SimpleServletLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.WhoAmIBeanLocal; import org.wildfly.test.integration.elytron.ejb.propagation.local.WhoAmILocal; import org.wildfly.test.integration.elytron.ejb.propagation.remote.ComplexServletRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.EntryBeanRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.EntryRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.ManagementBeanRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.ServletOnlyRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.SimpleServletRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.WhoAmIBeanRemote; import org.wildfly.test.integration.elytron.ejb.propagation.remote.WhoAmIRemote; import org.wildfly.test.integration.elytron.util.HttpUtil; import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test class to hold the identity propagation scenarios involving different security domains. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> * * NOTE: References in this file to Enterprise JavaBeans (EJB) refer to the Jakarta Enterprise Beans unless otherwise noted. */ @RunWith(Arquillian.class) @ServerSetup({ IdentityPropagationTestCase.ServletDomainSetupOverride.class, IdentityPropagationTestCase.EJBDomainSetupOverride.class, IdentityPropagationTestCase.PropagationSetup.class, ServletElytronDomainSetup.class}) public class IdentityPropagationTestCase { private static final String SERVLET_SECURITY_DOMAIN_NAME = "elytron-tests"; private static final String EJB_SECURITY_DOMAIN_NAME = "ejb-domain"; private static final String SINGLE_DEPLOYMENT_LOCAL = "single-deployment-local"; private static final String EAR_DEPLOYMENT_WITH_EJB_LOCAL = "ear-ejb-deployment-local"; private static final String EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL = "ear-servlet-ejb-deployment-local"; private static final String SINGLE_DEPLOYMENT_REMOTE = "single-deployment-remote"; private static final String EAR_DEPLOYMENT_WITH_EJB_REMOTE = "ear-ejb-deployment-remote"; private static final String EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE = "ear-servlet-ejb-deployment-remote"; private static final String EAR_DEPLOYMENT_WITH_SERVLET_REMOTE = "ear-servlet-remote"; private static final String EAR_DEPLOYMENT_WITH_SERVLET_LOCAL = "ear-servlet-local"; @ArquillianResource private URL url; @Deployment(name= EAR_DEPLOYMENT_WITH_EJB_LOCAL, order = 1) public static Archive<?> ejbDeploymentLocal() { final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_EJB_LOCAL + "-ejb.jar") .addClass(WhoAmIBeanLocal.class).addClass(EntryBeanLocal.class) .addClass(WhoAmILocal.class).addClass(EntryLocal.class) .addClass(WhoAmIBean.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_EJB_LOCAL + ".ear"); ear.addAsModule(jar); return ear; } @Deployment(name= EAR_DEPLOYMENT_WITH_EJB_REMOTE, order = 2) public static Archive<?> ejbDeploymentRemote() { final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_EJB_REMOTE + "-ejb.jar") .addClass(WhoAmIBeanRemote.class).addClass(EntryBeanRemote.class) .addClass(WhoAmIRemote.class).addClass(EntryRemote.class) .addClass(WhoAmIBean.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_EJB_REMOTE + ".ear"); ear.addAsModule(jar); return ear; } @Deployment(name= SINGLE_DEPLOYMENT_LOCAL, order = 3) public static Archive<?> singleDeploymentLocal() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final WebArchive war = ShrinkWrap.create(WebArchive.class, SINGLE_DEPLOYMENT_LOCAL + "-web.war") .addClass(HttpUtil.class) .addClasses(SimpleServletLocal.class, IdentityPropagationTestCase.class) .addClass(Util.class) .addClasses(ServletDomainSetupOverride.class, EJBDomainSetupOverride.class, PropagationSetup.class, PropagationSetup.class, ServletElytronDomainSetup.class, ElytronDomainSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class) .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SINGLE_DEPLOYMENT_LOCAL + "-ejb.jar") .addClass(WhoAmIBeanLocal.class).addClass(EntryBeanLocal.class) .addClass(WhoAmILocal.class).addClass(EntryLocal.class) .addClass(WhoAmIBean.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, SINGLE_DEPLOYMENT_LOCAL + ".ear"); ear.addAsModule(war); ear.addAsModule(jar); ear.addAsManifestResource(createPermissionsXmlAsset( // HttpUtil#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // HttpUtil#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); return ear; } @Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL, order = 4) public static Archive<?> servletAndEJBDeploymentLocal() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + "-web.war") .addClass(HttpUtil.class) .addClasses(ComplexServletLocal.class, IdentityPropagationTestCase.class) .addClasses(ServletDomainSetupOverride.class, EJBDomainSetupOverride.class, PropagationSetup.class, PropagationSetup.class, ServletElytronDomainSetup.class, ElytronDomainSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class) .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + "-ejb.jar") .addClass(ManagementBeanLocal.class) .addClass(Util.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + "-ejb.jar"), "MANIFEST.MF"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL + ".ear"); ear.addAsModule(war); ear.addAsModule(jar); ear.addAsManifestResource(createPermissionsXmlAsset( // HttpUtil#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // HttpUtil#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); return ear; } @Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_REMOTE, order = 5) public static Archive<?> servletOnlyRemote() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + "-web.war") .addClass(HttpUtil.class) .addClasses(ServletOnlyRemote.class, IdentityPropagationTestCase.class) .addClasses(ServletDomainSetupOverride.class, EJBDomainSetupOverride.class, PropagationSetup.class, PropagationSetup.class, ServletElytronDomainSetup.class, ElytronDomainSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class) .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + "-ejb.jar") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + "-ejb.jar"), "MANIFEST.MF"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_REMOTE + ".ear"); ear.addAsModule(war); ear.addAsModule(jar); ear.addAsManifestResource(createPermissionsXmlAsset( // HttpUtil#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // HttpUtil#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); return ear; } @Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_LOCAL, order = 6) public static Archive<?> servletOnlyLocal() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + "-web.war") .addClass(HttpUtil.class) .addClasses(ServletOnlyLocal.class, IdentityPropagationTestCase.class) .addClasses(ServletDomainSetupOverride.class, EJBDomainSetupOverride.class, PropagationSetup.class, PropagationSetup.class, ServletElytronDomainSetup.class, ElytronDomainSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class) .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + "-ejb.jar") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_LOCAL + "-ejb.jar"), "MANIFEST.MF"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_LOCAL + ".ear"); ear.addAsModule(war); ear.addAsModule(jar); ear.addAsManifestResource(createPermissionsXmlAsset( // HttpUtil#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // HttpUtil#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); return ear; } @Deployment(name= SINGLE_DEPLOYMENT_REMOTE, order = 7) public static Archive<?> singleDeploymentRemote() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final WebArchive war = ShrinkWrap.create(WebArchive.class, SINGLE_DEPLOYMENT_REMOTE + "-web.war") .addClass(HttpUtil.class) .addClasses(SimpleServletRemote.class, IdentityPropagationTestCase.class) .addClass(Util.class) .addClasses(ServletDomainSetupOverride.class, EJBDomainSetupOverride.class, PropagationSetup.class, PropagationSetup.class, ServletElytronDomainSetup.class, ElytronDomainSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class) .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, SINGLE_DEPLOYMENT_REMOTE + "-ejb.jar") .addClass(WhoAmIBeanRemote.class).addClass(EntryBeanRemote.class) .addClass(WhoAmIRemote.class).addClass(EntryRemote.class) .addClass(WhoAmIBean.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, SINGLE_DEPLOYMENT_REMOTE + ".ear"); ear.addAsModule(war); ear.addAsModule(jar); ear.addAsManifestResource(createPermissionsXmlAsset( // HttpUtil#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // HttpUtil#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); return ear; } @Deployment(name= EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE, order = 8) public static Archive<?> servletAndEJBDeploymentRemote() { final String SERVER_HOST_PORT = TestSuiteEnvironment.getHttpAddress() + ":" + TestSuiteEnvironment.getHttpPort(); final Package currentPackage = IdentityPropagationTestCase.class.getPackage(); final WebArchive war = ShrinkWrap.create(WebArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + "-web.war") .addClass(HttpUtil.class) .addClasses(ComplexServletRemote.class, IdentityPropagationTestCase.class) .addClasses(ServletDomainSetupOverride.class, EJBDomainSetupOverride.class, PropagationSetup.class, PropagationSetup.class, ServletElytronDomainSetup.class, ElytronDomainSetup.class, AbstractMgmtTestBase.class, EjbElytronDomainSetup.class) .addAsWebInfResource(currentPackage, "web.xml", "web.xml") .addAsWebInfResource(currentPackage, "jboss-web.xml", "jboss-web.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + "-ejb.jar") .addClass(ManagementBeanRemote.class) .addClass(Util.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource(currentPackage, "jboss-ejb3.xml", "jboss-ejb3.xml") .addAsManifestResource(new StringAsset("Dependencies: deployment." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + ".ear" + "." + EAR_DEPLOYMENT_WITH_EJB_REMOTE + "-ejb.jar"), "MANIFEST.MF"); final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE + ".ear"); ear.addAsModule(war); ear.addAsModule(jar); ear.addAsManifestResource(createPermissionsXmlAsset( // HttpUtil#execute calls ExecutorService#shutdownNow new RuntimePermission("modifyThread"), // HttpUtil#execute calls sun.net.www.http.HttpClient#openServer under the hood new SocketPermission(SERVER_HOST_PORT, "connect,resolve"), // Util#switchIdentity calls SecurityDomain#getCurrent and SecurityDomain#authenticate new ElytronPermission("getSecurityDomain"), new ElytronPermission("authenticate") ), "permissions.xml"); return ear; } /** * Servlet -> EJB propagation scenarios involving different security domains within a single deployment. */ /** * The EAR used in this test case contains: * - a servlet within a WAR * - a local EJB within a JAR * * The servlet attempts to invoke the local EJB. */ @Test @OperateOnDeployment(SINGLE_DEPLOYMENT_LOCAL) public void testServletToEjbSingleDeploymentLocal() throws Exception { testServletToEjbInvocation(); } /** * The EAR used in this test case contains: * - a servlet within a WAR * - a remote EJB within a JAR * * The servlet attempts to invoke the remote EJB. */ @Test @OperateOnDeployment(SINGLE_DEPLOYMENT_REMOTE) public void testServletToEjbSingleDeploymentRemote() throws Exception { testServletToEjbInvocation(); } private void testServletToEjbInvocation() throws Exception { String result = getWhoAmI("?method=whoAmI"); assertEquals("user1", result); result = getWhoAmI("?method=doIHaveRole&role=Managers"); assertEquals("true", result); } /** * The EAR used in this test case contains: * - a servlet within a WAR * - an EJB within a JAR * * The wrong password is used to access the servlet. */ @Test @OperateOnDeployment(SINGLE_DEPLOYMENT_REMOTE) public void testWrongPasswordSingleDeployment() throws Exception { testWrongPassword(); } /** * The EAR used in this test case contains: * - a servlet within a WAR * - a remote EJB within a JAR * * The servlet uses programmatic authentication to switch the identity and invokes the remote EJB * under this new identity. */ @Test @OperateOnDeployment(SINGLE_DEPLOYMENT_REMOTE) public void testServletToEjbSingleDeploymentProgrammaticAuthRemote() throws Exception { testServletToEjbSingleDeploymentProgrammaticAuth(); } /** * The EAR used in this test case contains: * - a servlet within a WAR * - a local EJB within a JAR * * The servlet uses programmatic authentication to switch the identity and invokes the local EJB * under this new identity. */ @Test @OperateOnDeployment(SINGLE_DEPLOYMENT_LOCAL) public void testServletToEjbSingleDeploymentProgrammaticAuthLocal() throws Exception { testServletToEjbSingleDeploymentProgrammaticAuth(); } private void testServletToEjbSingleDeploymentProgrammaticAuth() throws Exception { String result = getWhoAmI("?method=switchWhoAmI&username=user2&password=password2&role=Managers2"); assertEquals("user2,true", result); } private void testWrongPassword() throws Exception { try { getWhoAmIWrongPassword("?method=whoAmI"); } catch (Exception e) { assertTrue(e.getMessage().contains("Unauthorized")); } } /** * Servlet -> EJB -> EJB propagation scenarios involving different security domains across deployments. */ /** * Two EARs are used in this test case. * EAR #1 contains: * - a servlet within a WAR * - an EJB within a JAR * * EAR #2 contains: * - a local EJB within a JAR * * The servlet invokes the EJB from EAR #1 and that EJB attempts to invoke the local EJB in EAR #2. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL) public void testEarToEarLocal() throws Exception { testServletToEjbToEjbInvocation(); } /** * Two EARs are used in this test case. * EAR #1 contains: * - a servlet within a WAR * - an EJB within a JAR * * EAR #2 contains: * - a remote EJB within a JAR * * The servlet invokes the EJB from EAR #1 and that EJB attempts to invoke the remote EJB in EAR #2. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE) public void testEarToEarRemote() throws Exception { testServletToEjbToEjbInvocation(); } private void testServletToEjbToEjbInvocation() throws Exception { String result = getWhoAmI("?method=whoAmI"); assertEquals("user1", result); result = getWhoAmI("?method=invokeEntryDoIHaveRole&role=Managers"); assertEquals("true", result); } /** * The servlet from EAR #1 is accessed using the wrong password. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE) public void testWrongPasswordEarToEar() throws Exception { testWrongPassword(); } /** * Two EARs are used in this test case. * EAR #1 contains: * - a servlet within a WAR * * EAR #2 contains: * - a remote EJB within a JAR * * The servlet invokes the remote EJB from EAR #2. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_REMOTE) public void testServletToEjbEarToEarRemote() throws Exception { testServletToEjbInvocation(); } /** * Two EARs are used in this test case. * EAR #1 contains: * - a servlet within a WAR * * EAR #2 contains: * - a local EJB within a JAR * * The servlet invokes the local EJB from EAR #2. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_LOCAL) public void testServletToEjbEarToEarLocal() throws Exception { testServletToEjbInvocation(); } /** * Two EARs are used in this test case. * EAR #1 contains: * - a servlet within a WAR * - an EJB within a JAR * * EAR #2 contains: * - a remote EJB within a JAR * * The servlet invokes the EJB from EAR #1. That EJB then uses programmatic authentication to switch * the identity and then invokes the remote EJB from EAR #2 under this new identity. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_REMOTE) public void testEarToEarProgrammaticAuthRemote() throws Exception { testEarToEarProgrammaticAuth(); } /** * Two EARs are used in this test case. * EAR #1 contains: * - a servlet within a WAR * - an EJB within a JAR * * EAR #2 contains: * - a local EJB within a JAR * * The servlet invokes the EJB from EAR #1. That EJB then uses programmatic authentication to switch * the identity and then invokes the local EJB from EAR #2 under this new identity. */ @Test @OperateOnDeployment(EAR_DEPLOYMENT_WITH_SERVLET_AND_EJB_LOCAL) public void testEarToEarProgrammaticAuthLocal() throws Exception { testEarToEarProgrammaticAuth(); } private void testEarToEarProgrammaticAuth() throws Exception { String result = getWhoAmI("?method=switchThenInvokeEntryDoIHaveRole&username=user2&password=password2&role=Managers2"); assertEquals("user2,true", result); } private String getWhoAmI(String queryString) throws Exception { return get(url + "whoAmI" + queryString, "user1", "password1", 10, SECONDS); } private String getWhoAmIWrongPassword(String queryString) throws Exception { return get(url + "whoAmI" + queryString, "user1", "wrongpassword", 10, SECONDS); } static class ServletDomainSetupOverride extends ElytronDomainSetup { public ServletDomainSetupOverride() { super(new File(IdentityPropagationTestCase.class.getResource("users.properties").getFile()).getAbsolutePath(), new File(IdentityPropagationTestCase.class.getResource("roles.properties").getFile()).getAbsolutePath(), SERVLET_SECURITY_DOMAIN_NAME); } } static class EJBDomainSetupOverride extends ElytronDomainSetup { public EJBDomainSetupOverride() { super(new File(IdentityPropagationTestCase.class.getResource("ejbusers.properties").getFile()).getAbsolutePath(), new File(IdentityPropagationTestCase.class.getResource("ejbroles.properties").getFile()).getAbsolutePath(), EJB_SECURITY_DOMAIN_NAME); } } static class PropagationSetup extends AbstractMgmtTestBase implements ServerSetupTask { private ManagementClient managementClient; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { this.managementClient = managementClient; final List<ModelNode> updates = new ArrayList<ModelNode>(); updates.add(getAddEjbApplicationSecurityDomainOp(EJB_SECURITY_DOMAIN_NAME, EJB_SECURITY_DOMAIN_NAME)); updates.add(getAddEjbApplicationSecurityDomainOp(SERVLET_SECURITY_DOMAIN_NAME, SERVLET_SECURITY_DOMAIN_NAME)); // /subsystem=elytron/security-domain=elytron-tests:write-attribute(name=outflow-security-domains, value=["ejb-domain"]) ModelNode op = new ModelNode(); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(OP_ADDR).add(SUBSYSTEM, "elytron"); op.get(OP_ADDR).add("security-domain", SERVLET_SECURITY_DOMAIN_NAME); op.get("name").set("outflow-security-domains"); ModelNode outflowDomains = new ModelNode(); outflowDomains.add(EJB_SECURITY_DOMAIN_NAME); op.get("value").set(outflowDomains); updates.add(op); // /subsystem=elytron/security-domain=ejb-domain:write-attribute(name=trusted-security-domains, value=["elytron-tests"]) op = new ModelNode(); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(OP_ADDR).add(SUBSYSTEM, "elytron"); op.get(OP_ADDR).add("security-domain", EJB_SECURITY_DOMAIN_NAME); op.get("name").set("trusted-security-domains"); ModelNode trustedDomains = new ModelNode(); trustedDomains.add(SERVLET_SECURITY_DOMAIN_NAME); op.get("value").set(trustedDomains); updates.add(op); executeOperations(updates); ServerReload.executeReloadAndWaitForCompletion(managementClient, 50000); } @Override public void tearDown(final ManagementClient managementClient, final String containerId) throws Exception { final List<ModelNode> updates = new ArrayList<>(); updates.add(getUndefineAttributeOperation(PathAddress.pathAddress("subsystem", "elytron").append("security-domain", SERVLET_SECURITY_DOMAIN_NAME), "outflow-security-domains")); updates.add(getUndefineAttributeOperation(PathAddress.pathAddress("subsystem", "elytron").append("security-domain", EJB_SECURITY_DOMAIN_NAME), "trusted-security-domains")); ModelNode op = ModelUtil.createOpNode( "subsystem=ejb3/application-security-domain=" + EJB_SECURITY_DOMAIN_NAME, REMOVE); updates.add(op); op = ModelUtil.createOpNode( "subsystem=ejb3/application-security-domain=" + SERVLET_SECURITY_DOMAIN_NAME, REMOVE); updates.add(op); executeOperations(updates); ServerReload.executeReloadAndWaitForCompletion(managementClient, 50000); } @Override protected ModelControllerClient getModelControllerClient() { return managementClient.getControllerClient(); } private static PathAddress getEjbApplicationSecurityDomainAddress(String ejbDomainName) { return PathAddress.pathAddress() .append(SUBSYSTEM, "ejb3") .append("application-security-domain", ejbDomainName); } private static ModelNode getAddEjbApplicationSecurityDomainOp(String ejbDomainName, String securityDomainName) { ModelNode op = createAddOperation(getEjbApplicationSecurityDomainAddress(ejbDomainName)); op.get("security-domain").set(securityDomainName); return op; } } }
35,109
51.876506
220
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/SecuredBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import jakarta.annotation.Resource; import jakarta.annotation.security.RolesAllowed; import jakarta.ejb.EJBContext; import jakarta.ejb.Remote; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; /** * Simple Jakarta Enterprise Beans to return information about the current Principal. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Stateless @Remote(SecurityInformation.class) @SecurityDomain("elytron-tests") @RolesAllowed("Users") public class SecuredBean implements SecurityInformation { @Resource private EJBContext context; @Override public String getPrincipalName() { return context.getCallerPrincipal().getName(); } }
1,796
33.557692
85
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/AuthenticationWithSourceAddressRoleDecoderMatchTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.categories.CommonCriteria; import org.jboss.as.test.shared.TestSuiteEnvironment; import org.jboss.ejb.client.RequestSendFailedException; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.wildfly.test.security.common.elytron.EjbElytronDomainSetup; import org.wildfly.test.security.common.elytron.ElytronDomainSetup; import org.wildfly.test.security.common.elytron.ServletElytronDomainSetup; /** * Test authentication with the use of a source address role decoder where the IP address of the remote * client matches the address configured on the decoder. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ AuthenticationWithSourceAddressRoleDecoderMatchTestCase.ElytronDomainSetupOverride.class, EjbElytronDomainSetup.class, ServletElytronDomainSetup.class }) @Category(CommonCriteria.class) public class AuthenticationWithSourceAddressRoleDecoderMatchTestCase { private static final String APPLICATION_NAME = "authentication-with-source-address-role-decoder"; @ArquillianResource private ManagementClient mgmtClient; @Deployment public static JavaArchive createDeployment() throws IOException { final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, APPLICATION_NAME + ".jar"); jar.addClasses(SecurityInformation.class, SecuredBean.class); return jar; } /* The EJB being used in this test class is secured using the "elytron-tests" security domain. This security domain is configured with: 1) a source-address-role-decoder that assigns the "admin" role if the IP address of the remote client is TestSuiteEnvironment.getServerAddress() 2) a permission-mapper that assigns the "LoginPermission" if the identity has the "admin" role unless the principal is "user2" */ private static String getIPAddress() throws IllegalStateException { try { return InetAddress.getByName(TestSuiteEnvironment.getServerAddress()).getHostAddress(); } catch (UnknownHostException e) { throw new IllegalStateException(e); } } @Test public void testAuthenticationIPAddressAndPermissionMapperMatch() throws Exception { Properties ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user1", "password1"); SecurityInformation targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); assertEquals("user1", targetBean.getPrincipalName()); ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "admin", "admin"); targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); assertEquals("admin", targetBean.getPrincipalName()); } @Test public void testAuthenticationIPAddressMatchAndPermissionMapperMismatch() throws Exception { final Properties ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user2", "password2"); final SecurityInformation targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } } @Test public void testAuthenticationInvalidCredentials() throws Exception { Properties ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user1", "badpassword"); SecurityInformation targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } ejbClientConfiguration = createEjbClientConfiguration(Utils.getHost(mgmtClient), "user2", "badpassword"); targetBean = lookupEJB(SecuredBean.class, SecurityInformation.class, ejbClientConfiguration); try { targetBean.getPrincipalName(); Assert.fail("Expected RequestSendFailedException not thrown"); } catch (RequestSendFailedException expected) { } } private static Properties createEjbClientConfiguration(String hostName, String user, String password) { final Properties pr = new Properties(); pr.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false"); pr.put("remote.connection.default.connect.options.org.xnio.Options.SASL_DISALLOWED_MECHANISMS", "JBOSS-LOCAL-USER"); pr.put("remote.connections", "default"); pr.put("remote.connection.default.host", hostName); pr.put("remote.connection.default.port", "8080"); pr.put("remote.connection.default.username", user); pr.put("remote.connection.default.password", password); return pr; } private static <T> T lookupEJB(Class<? extends T> beanImplClass, Class<T> remoteInterface, Properties ejbProperties) throws Exception { final Properties jndiProperties = new Properties(); jndiProperties.putAll(ejbProperties); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); return (T) context.lookup("ejb:/" + APPLICATION_NAME + "/" + beanImplClass.getSimpleName() + "!" + remoteInterface.getName()); } static class ElytronDomainSetupOverride extends ElytronDomainSetup { public ElytronDomainSetupOverride() { super(new File(AuthenticationWithSourceAddressRoleDecoderMatchTestCase.class.getResource("users.properties").getFile()).getAbsolutePath(), new File(AuthenticationWithSourceAddressRoleDecoderMatchTestCase.class.getResource("roles.properties").getFile()).getAbsolutePath(), "elytron-tests", "ipPermissionMapper", getIPAddress()); } } }
8,088
46.304094
168
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/EjbUnsecuredBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import jakarta.ejb.Stateless; /** * A simple unsecured stateless bean with simple echo method * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2018 Red Hat, Inc. */ @Stateless public class EjbUnsecuredBean { public String echo(String msg) { return msg; } }
1,379
34.384615
93
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/RolePropagationTestSecuredBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import org.junit.Assert; import jakarta.annotation.PostConstruct; import jakarta.annotation.security.RunAs; import jakarta.ejb.Startup; import jakarta.inject.Inject; import jakarta.ejb.Singleton; /** * EJB that uses RunAs and PostConstruct annotation to successfully call another secured bean without specifying security domain explicitly. */ @Singleton @Startup @RunAs("TEST") public class RolePropagationTestSecuredBean { @Inject private RolePropagationTest rolePropagationTest; @PostConstruct protected void callSecuredBeanWithTESTRole() { Assert.assertEquals(rolePropagationTest.testRunAsWithoutSecDomainSpecified(), "access allowed"); } }
1,753
34.795918
140
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/WhoAmI.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; import java.security.Principal; import jakarta.ejb.Local; /** * The local interface to the simple WhoAmI bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Local public interface WhoAmI { /** * @return the caller principal obtained from the EJBContext. */ Principal getCallerPrincipal(); /** * @param roleName - The role to check. * @return The result of calling EJBContext.isCallerInRole() with the supplied role name. */ boolean doIHaveRole(String roleName); }
1,626
33.617021
93
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/SecurityInformation.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb; public interface SecurityInformation { String getPrincipalName(); }
1,149
37.333333
70
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/ServletOnlyRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import java.io.IOException; import java.io.Writer; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.annotation.security.DeclareRoles; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class ServletOnlyRemote extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { EntryRemote bean = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.ejb.propagation.remote.EntryRemote"); writer.write(bean.whoAmI()); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("doIHaveRole".equals(method)) { try { EntryRemote bean = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.ejb.propagation.remote.EntryRemote"); writer.write(String.valueOf(bean.doIHaveRole(role))); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } public static <T> T lookup(Class<T> clazz, String jndiName) { Object bean = lookup(jndiName); return clazz.cast(bean); } private static Object lookup(String jndiName) { Context context = null; try { context = new InitialContext(); return context.lookup(jndiName); } catch (NamingException ex) { throw new IllegalStateException(ex); } finally { try { context.close(); } catch (NamingException ex) { throw new IllegalStateException(ex); } } } }
3,954
39.773196
220
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/EntryBeanRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @Stateless @SecurityDomain("ejb-domain") public class EntryBeanRemote implements EntryRemote { @EJB private WhoAmIRemote whoAmIBean; @Resource private SessionContext context; public String whoAmI() { return context.getCallerPrincipal().getName(); } public boolean doIHaveRole(String roleName) { return context.isCallerInRole(roleName); } }
1,794
31.053571
70
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/SimpleServletRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity; import java.io.IOException; import java.io.Writer; import java.util.concurrent.Callable; import jakarta.annotation.security.DeclareRoles; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class SimpleServletRemote extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private EntryRemote bean; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String username = req.getParameter("username"); String password = req.getParameter("password"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { writer.write(bean.whoAmI()); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("switchWhoAmI".equals(method)) { final Callable<String[]> callable = () -> { String remoteWho = bean.whoAmI(); boolean hasRole = bean.doIHaveRole(role); return new String[]{remoteWho, String.valueOf(hasRole)}; }; try { String[] result = switchIdentity(username, password, callable); writer.write(result[0] + "," + result[1]); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("doIHaveRole".equals(method)) { try { writer.write(String.valueOf(bean.doIHaveRole(role))); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } }
3,668
39.318681
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/ManagementBeanRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity; import java.util.concurrent.Callable; import jakarta.annotation.Resource; import jakarta.annotation.security.PermitAll; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.ejb3.annotation.SecurityDomain; /** * A simple EJB that can be called to obtain the current caller principal and to check the role membership for * that principal. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Stateless @SecurityDomain("elytron-tests") public class ManagementBeanRemote { @Resource private SessionContext context; @PermitAll public String whoAmI() { return context.getCallerPrincipal().getName(); } @PermitAll public boolean invokeEntryDoIHaveRole(String role) { EntryRemote entry = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.ejb.propagation.remote.EntryRemote"); return entry.doIHaveRole(role); } @PermitAll public String[] switchThenInvokeEntryDoIHaveRole(String username, String password, String role) { EntryRemote entry = lookup(EntryRemote.class, "java:global/ear-ejb-deployment-remote/ear-ejb-deployment-remote-ejb/EntryBeanRemote!org.wildfly.test.integration.elytron.ejb.propagation.remote.EntryRemote"); final Callable<String[]> callable = () -> { String remoteWho = entry.whoAmI(); boolean hasRole = entry.doIHaveRole(role); return new String[] { remoteWho, String.valueOf(hasRole) }; }; try { return switchIdentity(username, password, callable); } catch (Exception e) { throw new IllegalStateException(e); } } public static <T> T lookup(Class<T> clazz, String jndiName) { Object bean = lookup(jndiName); return clazz.cast(bean); } private static Object lookup(String jndiName) { Context context = null; try { context = new InitialContext(); return context.lookup(jndiName); } catch (NamingException ex) { throw new IllegalStateException(ex); } finally { try { context.close(); } catch (NamingException ex) { throw new IllegalStateException(ex); } } } }
3,674
36.5
213
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/WhoAmIRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import java.security.Principal; import jakarta.ejb.Remote; /** * The local interface to the simple WhoAmI bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Remote public interface WhoAmIRemote { /** * @return the caller principal obtained from the EJBContext. */ Principal getCallerPrincipal(); /** * @param roleName - The role to check. * @return The result of calling EJBContext.isCallerInRole() with the supplied role name. */ boolean doIHaveRole(String roleName); }
1,653
34.191489
93
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/WhoAmIBeanRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @Stateless @SecurityDomain("ejb-domain") public class WhoAmIBeanRemote extends org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean implements WhoAmIRemote { }
1,469
38.72973
120
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/EntryRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import jakarta.ejb.Remote; /** * Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Remote public interface EntryRemote { /** * @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal() */ String whoAmI(); /** * @param roleName - The role to check. * @return the response from EJBContext.isCallerInRole() with the supplied role name. */ boolean doIHaveRole(String roleName); }
1,681
35.565217
98
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/remote/ComplexServletRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.remote; import java.io.IOException; import java.io.Writer; import jakarta.annotation.security.DeclareRoles; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class ComplexServletRemote extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private ManagementBeanRemote bean; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String username = req.getParameter("username"); String password = req.getParameter("password"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { writer.write(bean.whoAmI()); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("invokeEntryDoIHaveRole".equals(method)) { try { writer.write(String.valueOf(bean.invokeEntryDoIHaveRole(role))); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("switchThenInvokeEntryDoIHaveRole".equals(method)) { try { String[] result = bean.switchThenInvokeEntryDoIHaveRole(username, password, role); writer.write(result[0] + "," + result[1]); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } }
3,365
38.6
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/SimpleServletLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity; import java.io.IOException; import java.io.Writer; import java.util.concurrent.Callable; import jakarta.annotation.security.DeclareRoles; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class SimpleServletLocal extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private EntryLocal bean; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String username = req.getParameter("username"); String password = req.getParameter("password"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { writer.write(bean.whoAmI()); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("switchWhoAmI".equals(method)) { final Callable<String[]> callable = () -> { String localWho = bean.whoAmI(); boolean hasRole = bean.doIHaveRole(role); return new String[]{localWho, String.valueOf(hasRole)}; }; try { String[] result = switchIdentity(username, password, callable); writer.write(result[0] + "," + result[1]); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("doIHaveRole".equals(method)) { try { writer.write(String.valueOf(bean.doIHaveRole(role))); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } }
3,663
38.826087
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/WhoAmILocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import java.security.Principal; import jakarta.ejb.Local; /** * The local interface to the simple WhoAmI bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Local public interface WhoAmILocal { /** * @return the caller principal obtained from the EJBContext. */ Principal getCallerPrincipal(); /** * @param roleName - The role to check. * @return The result of calling EJBContext.isCallerInRole() with the supplied role name. */ boolean doIHaveRole(String roleName); }
1,649
34.106383
93
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/ServletOnlyLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import java.io.IOException; import java.io.Writer; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.annotation.security.DeclareRoles; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class ServletOnlyLocal extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { EntryLocal bean = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.ejb.propagation.local.EntryLocal"); writer.write(bean.whoAmI()); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("doIHaveRole".equals(method)) { try { EntryLocal bean = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.ejb.propagation.local.EntryLocal"); writer.write(String.valueOf(bean.doIHaveRole(role))); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } public static <T> T lookup(Class<T> clazz, String jndiName) { Object bean = lookup(jndiName); return clazz.cast(bean); } private static Object lookup(String jndiName) { Context context = null; try { context = new InitialContext(); return context.lookup(jndiName); } catch (NamingException ex) { throw new IllegalStateException(ex); } finally { try { context.close(); } catch (NamingException ex) { throw new IllegalStateException(ex); } } } }
3,938
39.608247
213
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/ManagementBeanLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import static org.jboss.as.test.shared.integration.ejb.security.Util.switchIdentity; import java.util.concurrent.Callable; import jakarta.annotation.Resource; import jakarta.annotation.security.PermitAll; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.ejb3.annotation.SecurityDomain; /** * A simple EJB that can be called to obtain the current caller principal and to check the role membership for * that principal. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Stateless @SecurityDomain("elytron-tests") public class ManagementBeanLocal { @Resource private SessionContext context; @PermitAll public String whoAmI() { return context.getCallerPrincipal().getName(); } @PermitAll public boolean invokeEntryDoIHaveRole(String role) { EntryLocal entry = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.ejb.propagation.local.EntryLocal"); return entry.doIHaveRole(role); } @PermitAll public String[] switchThenInvokeEntryDoIHaveRole(String username, String password, String role) { EntryLocal entry = lookup(EntryLocal.class, "java:global/ear-ejb-deployment-local/ear-ejb-deployment-local-ejb/EntryBeanLocal!org.wildfly.test.integration.elytron.ejb.propagation.local.EntryLocal"); final Callable<String[]> callable = () -> { String localWho = entry.whoAmI(); boolean hasRole = entry.doIHaveRole(role); return new String[] { localWho, String.valueOf(hasRole) }; }; try { return switchIdentity(username, password, callable); } catch (Exception e) { throw new IllegalStateException(e); } } public static <T> T lookup(Class<T> clazz, String jndiName) { Object bean = lookup(jndiName); return clazz.cast(bean); } private static Object lookup(String jndiName) { Context context = null; try { context = new InitialContext(); return context.lookup(jndiName); } catch (NamingException ex) { throw new IllegalStateException(ex); } finally { try { context.close(); } catch (NamingException ex) { throw new IllegalStateException(ex); } } } }
3,656
36.316327
206
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/WhoAmIBeanLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @Stateless @SecurityDomain("ejb-domain") public class WhoAmIBeanLocal extends org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean implements WhoAmILocal { }
1,466
38.648649
118
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/ComplexServletLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import java.io.IOException; import java.io.Writer; import jakarta.annotation.security.DeclareRoles; import jakarta.ejb.EJB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.HttpConstraint; import jakarta.servlet.annotation.ServletSecurity; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @WebServlet(urlPatterns = "/whoAmI", loadOnStartup = 1) @ServletSecurity(@HttpConstraint(rolesAllowed = { "Users" })) @DeclareRoles("Users") public class ComplexServletLocal extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private ManagementBeanLocal bean; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); Writer writer = resp.getWriter(); String method = req.getParameter("method"); String username = req.getParameter("username"); String password = req.getParameter("password"); String role = req.getParameter("role"); if ("whoAmI".equals(method)) { try { writer.write(bean.whoAmI()); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("invokeEntryDoIHaveRole".equals(method)) { try { writer.write(String.valueOf(bean.invokeEntryDoIHaveRole(role))); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else if ("switchThenInvokeEntryDoIHaveRole".equals(method)) { try { String[] result = bean.switchThenInvokeEntryDoIHaveRole(username, password, role); writer.write(result[0] + "," + result[1]); } catch (Exception e) { throw new ServletException("Unexpected Failure", e); } } else { throw new IllegalArgumentException("Parameter 'method' either missing or invalid method='" + method + "'"); } } }
3,362
38.564706
119
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/EntryLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import jakarta.ejb.Local; /** * Interface for the bean used as the entry point to verify Enterprise Beans 3 security behaviour. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Local public interface EntryLocal { /** * @return The name of the Principal obtained from a call to EJBContext.getCallerPrincipal() */ String whoAmI(); /** * @param roleName - The role to check. * @return the response from EJBContext.isCallerInRole() with the supplied role name. */ boolean doIHaveRole(String roleName); }
1,677
35.478261
98
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/propagation/local/EntryBeanLocal.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.propagation.local; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateless; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ @Stateless @SecurityDomain("ejb-domain") public class EntryBeanLocal implements EntryLocal { @EJB private WhoAmILocal whoAmIBean; @Resource private SessionContext context; public String whoAmI() { return context.getCallerPrincipal().getName(); } public boolean doIHaveRole(String roleName) { return context.isCallerInRole(roleName); } }
1,790
30.982143
70
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/base/EntryBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.base; import java.util.concurrent.Callable; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.SessionContext; import org.wildfly.security.auth.server.RealmUnavailableException; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.evidence.PasswordGuessEvidence; import org.wildfly.test.integration.elytron.ejb.WhoAmI; /** * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public abstract class EntryBean { @EJB private WhoAmI whoAmIBean; @Resource private SessionContext context; public String whoAmI() { return context.getCallerPrincipal().getName(); } public String[] doubleWhoAmI() { String localWho = context.getCallerPrincipal().getName(); String remoteWho = whoAmIBean.getCallerPrincipal().getName(); String secondLocalWho = context.getCallerPrincipal().getName(); if (secondLocalWho.equals(localWho) == false) { throw new IllegalStateException("Local getCallerPrincipal changed from '" + localWho + "' to '" + secondLocalWho); } return new String[] { localWho, remoteWho }; } public String[] doubleWhoAmI(String username, String password) throws Exception { String localWho = context.getCallerPrincipal().getName(); final Callable<String[]> callable = () -> { String remoteWho = whoAmIBean.getCallerPrincipal().getName(); return new String[] { localWho, remoteWho }; }; try { return switchIdentity(username, password, callable); } finally { String secondLocalWho = context.getCallerPrincipal().getName(); if (secondLocalWho.equals(localWho) == false) { throw new IllegalStateException( "Local getCallerPrincipal changed from '" + localWho + "' to '" + secondLocalWho); } } } public boolean doIHaveRole(String roleName) { return context.isCallerInRole(roleName); } public boolean[] doubleDoIHaveRole(String roleName) { boolean localDoI = context.isCallerInRole(roleName); boolean remoteDoI = whoAmIBean.doIHaveRole(roleName); return new boolean[] { localDoI, remoteDoI }; } public boolean[] doubleDoIHaveRole(String roleName, String username, String password) throws Exception { boolean localDoI = context.isCallerInRole(roleName); final Callable<boolean[]> callable = () -> { boolean remoteDoI = whoAmIBean.doIHaveRole(roleName); return new boolean[] { localDoI, remoteDoI }; }; try { return switchIdentity(username, password, callable); } finally { boolean secondLocalDoI = context.isCallerInRole(roleName); if (secondLocalDoI != localDoI) { throw new IllegalStateException("Local call to isCallerInRole for '" + roleName + "' changed from " + localDoI + " to " + secondLocalDoI); } } } private static <T> T switchIdentity(final String username, final String password, final Callable<T> callable) throws RealmUnavailableException, Exception { return SecurityDomain.getCurrent().authenticate(username, new PasswordGuessEvidence(password.toCharArray())) .runAs(callable); } }
4,493
38.421053
126
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/base/WhoAmIBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.base; import java.security.Principal; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; /** * @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a> */ public abstract class WhoAmIBean { @Resource private SessionContext context; public Principal getCallerPrincipal() { return context.getCallerPrincipal(); } public boolean doIHaveRole(String roleName) { return context.isCallerInRole(roleName); } }
1,552
32.76087
70
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/authentication/EntryBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.authentication; import jakarta.ejb.Stateless; import org.wildfly.test.integration.elytron.ejb.Entry; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Stateless @SecurityDomain("elytron-tests") public class EntryBean extends org.wildfly.test.integration.elytron.ejb.base.EntryBean implements Entry { }
1,524
39.131579
105
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/ejb/authentication/WhoAmIBean.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.ejb.authentication; import jakarta.ejb.Stateless; import org.wildfly.test.integration.elytron.ejb.WhoAmI; import org.jboss.ejb3.annotation.SecurityDomain; /** * Concrete implementation to allow deployment of bean. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ @Stateless @SecurityDomain("elytron-tests") public class WhoAmIBean extends org.wildfly.test.integration.elytron.ejb.base.WhoAmIBean implements WhoAmI { }
1,528
39.236842
108
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/util/HttpAuthorization.java
/* * Copyright 2021 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.test.integration.elytron.util; import java.nio.charset.StandardCharsets; import java.util.Base64; import jakarta.ws.rs.client.ClientRequestFilter; import jakarta.ws.rs.core.HttpHeaders; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class HttpAuthorization { public static ClientRequestFilter basic(final String username, final String password) { return requestContext -> { final String key = username + ':' + password; final String authHeader = "Basic " + Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)); requestContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, authHeader); }; } }
1,332
35.027027
122
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/util/ClientConfigProviderBearerTokenAbortFilter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.util; import org.junit.Assert; import jakarta.ws.rs.client.ClientRequestContext; import jakarta.ws.rs.client.ClientRequestFilter; import jakarta.ws.rs.core.Response; public class ClientConfigProviderBearerTokenAbortFilter implements ClientRequestFilter { @Override public void filter(ClientRequestContext requestContext) { String authorizationHeader = requestContext.getHeaderString("Authorization"); Assert.assertEquals("The request authorization header is not correct", "Bearer myTestToken", authorizationHeader); requestContext.abortWith(Response.ok().build()); } }
1,678
40.975
122
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/util/ClientConfigProviderNoBasicAuthorizationHeaderFilter.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.util; import org.junit.Assert; import jakarta.ws.rs.client.ClientRequestContext; import jakarta.ws.rs.client.ClientRequestFilter; public class ClientConfigProviderNoBasicAuthorizationHeaderFilter implements ClientRequestFilter { @Override public void filter(ClientRequestContext requestContext) { String authorizationHeader = requestContext.getHeaderString("Authorization"); Assert.assertTrue("There should be no Basic authorization header", authorizationHeader == null || !authorizationHeader.contains("Basic")); } }
1,619
41.631579
146
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/util/WelcomeContent.java
package org.wildfly.test.integration.elytron.util; import org.apache.commons.io.FileUtils; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.AbstractConfigurableElement; import org.wildfly.test.security.common.elytron.ConfigurableElement; import java.io.File; import java.io.FileWriter; import static org.jboss.as.test.integration.security.common.Utils.createTemporaryFolder; import static org.jboss.as.test.shared.CliUtils.escapePath; /** * Installs mock welcome-content for Galleon slimmed installation testing where that * is not provided. TODO having tests rely on welcome-content instead of a deployment * is odd, unless the point is to validate handling of the way welcome-content * is installed. */ public class WelcomeContent extends AbstractConfigurableElement { private final boolean layersTest = Boolean.getBoolean("ts.layers") || Boolean.getBoolean("ts.bootable"); private WelcomeContent(Builder builder) { super(builder); } private File tempFolder; @Override public void create(CLIWrapper cli) throws Exception { if (layersTest){ this.tempFolder = createTemporaryFolder("ely-welcome-content" + name); try (FileWriter writer = new FileWriter(new File(tempFolder, "index.html"))) { // Tests check for 'Welcome to ' in the entity returned by reading the root resource. So include that. writer.write("Welcome to AMeaninglessValueThatShouldNotBeAsserted"); } cli.sendLine(String.format("/subsystem=undertow/configuration=handler/file=welcome-content:add(path=%s)", escapePath(tempFolder.getAbsolutePath()))); cli.sendLine("/subsystem=undertow/server=default-server/host=default-host/location=\"/\":add(handler=welcome-content)"); } // else the server is already configured with the standard welcome content } @Override public void remove(CLIWrapper cli) throws Exception { if (layersTest){ cli.sendLine("/subsystem=undertow/server=default-server/host=default-host/location=\"/\":remove"); cli.sendLine("/subsystem=undertow/configuration=handler/file=welcome-content:remove"); FileUtils.deleteQuietly(tempFolder); tempFolder = null; } } public static class Builder extends AbstractConfigurableElement.Builder<Builder> { public WelcomeContent build() { return new WelcomeContent(this); } @Override protected Builder self() { return this; } } public static Builder builder() { return new Builder(); } public static class SetupTask extends AbstractElytronSetupTask { @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { super.setup(managementClient, containerId); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { super.tearDown(managementClient, containerId); } @Override protected ConfigurableElement[] getConfigurableElements() { return new ConfigurableElement[]{WelcomeContent.builder().withName(getName()).build()}; } public String getName() { return "WelcomeContent"; } } }
3,572
37.419355
132
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/util/HttpUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; /** * Utility method for handling HTTP invocations. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class HttpUtil { public static String get(final String spec, final String username, final String password, final long timeout, final TimeUnit unit) throws IOException, TimeoutException { final Map<String, String> headers; if (username != null) { final String userpassword = username + ":" + password; final String basicAuthorization = java.util.Base64.getEncoder().encodeToString(userpassword.getBytes(StandardCharsets.UTF_8)); headers = Collections.singletonMap("Authorization", "Basic " + basicAuthorization); } else { headers = Collections.emptyMap(); } return get(spec, headers, timeout, unit, new AtomicReference<String>()); } public static String get(final String spec, final Map<String, String> headers, final long timeout, final TimeUnit unit, final AtomicReference<String> sessionId) throws IOException, TimeoutException { final URL url = new URL(spec); Callable<String> task = new Callable<String>() { @Override public String call() throws IOException { final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); headers.entrySet().forEach(e -> conn.addRequestProperty(e.getKey(), e.getValue())); String cookie = sessionId.get(); if (cookie != null) { conn.addRequestProperty("Cookie", cookie); } conn.setDoInput(true); return processResponse(conn, sessionId); } }; return execute(task, timeout, unit); } private static String execute(final Callable<String> task, final long timeout, final TimeUnit unit) throws TimeoutException, IOException { final ExecutorService executor = Executors.newSingleThreadExecutor(); final Future<String> result = executor.submit(task); try { return result.get(timeout, unit); } catch (TimeoutException e) { result.cancel(true); throw e; } catch (InterruptedException e) { // should not happen throw new RuntimeException(e); } catch (ExecutionException e) { // by virtue of the Callable redefinition above I can cast throw new IOException(e); } finally { executor.shutdownNow(); try { executor.awaitTermination(timeout, unit); } catch (InterruptedException e) { // ignore } } } public static String read(final InputStream in) throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while ((b = in.read()) != -1) { out.write(b); } return out.toString(); } public static String processResponse(HttpURLConnection conn, AtomicReference<String> sessionId) throws IOException { int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { final InputStream err = conn.getErrorStream(); try { String response = err != null ? read(err) : null; throw new IOException(String.format("HTTP Status %d Response: %s", responseCode, response)); } finally { if (err != null) { err.close(); } } } List<String> cookies = conn.getHeaderFields().get("Set-Cookie"); if (cookies != null) { for (String cookie : cookies) { if (cookie.startsWith("JSESSIONID=")) { sessionId.set(cookie.substring(0, cookie.indexOf(';'))); break; } } } final InputStream in = conn.getInputStream(); try { return read(in); } finally { in.close(); } } }
5,810
38.530612
203
java
null
wildfly-main/testsuite/integration/elytron/src/test/java/org/wildfly/test/integration/elytron/permissionmappers/ConstantPermissionMapperTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.integration.elytron.permissionmappers; import static jakarta.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static jakarta.servlet.http.HttpServletResponse.SC_OK; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.AllPermission; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.OperateOnDeployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ServerSetup; import org.jboss.as.test.integration.security.common.SecurityTestConstants; import org.jboss.as.test.integration.security.common.Utils; import org.jboss.as.test.shared.PermissionUtils; import org.jboss.ejb.client.RemoteEJBPermission; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.joda.time.JodaTimePermission; import org.junit.Test; import org.junit.runner.RunWith; import org.wildfly.extension.batch.jberet.deployment.BatchPermission; import org.wildfly.security.auth.permission.LoginPermission; import org.wildfly.security.permission.ElytronPermission; import org.wildfly.security.permission.NoPermission; import org.wildfly.test.security.common.AbstractElytronSetupTask; import org.wildfly.test.security.common.elytron.ConfigurableElement; import org.wildfly.test.security.common.elytron.ConstantPermissionMapper; import org.wildfly.test.security.common.elytron.PermissionRef; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain; import org.wildfly.test.security.common.elytron.SimpleSecurityDomain.SecurityDomainRealm; import org.wildfly.test.security.common.elytron.UndertowDomainMapper; import org.wildfly.test.security.servlets.CheckIdentityPermissionServlet; import org.wildfly.transaction.client.RemoteTransactionPermission; /** * Test for "constant-permission-mapper" Elytron resource. It tests if the defined permissions are correctly mapped to users. * * @author Josef Cacek */ @RunWith(Arquillian.class) @RunAsClient @ServerSetup({ ConstantPermissionMapperTestCase.ServerSetup.class }) public class ConstantPermissionMapperTestCase { private static final String SD_DEFAULT = "other"; private static final String SD_NO_MAPPER = "no-permission-mapper"; private static final String SD_LOGIN = "login-permission"; private static final String SD_ALL = "all-permission"; private static final String SD_MODULES = "permissions-in-modules"; private static final String TARGET_NAME = "name"; private static final String TARGET_NAME_START = "start"; private static final String ACTION = "action"; @Deployment(testable = false, name = SD_NO_MAPPER) public static WebArchive deployment1() { return createWar(SD_NO_MAPPER); } @Deployment(testable = false, name = SD_DEFAULT) public static WebArchive deployment2() { return createWar(SD_DEFAULT); } @Deployment(testable = false, name = SD_LOGIN) public static WebArchive deployment3() { return createWar(SD_LOGIN); } @Deployment(testable = false, name = SD_ALL) public static WebArchive deployment4() { return createWar(SD_ALL); } @Deployment(testable = false, name = SD_MODULES) public static WebArchive deployment5() { return createWar(SD_MODULES); } /** * Tests default security domain permissions. */ @Test @OperateOnDeployment(SD_DEFAULT) public void testDefaultDomainPermissions(@ArquillianResource URL url) throws Exception { // anonymous assertUserHasntPermission(url, null, null, AllPermission.class.getName(), null, null); // WFCORE-2666 assertUserHasntPermission(url, null, null, LoginPermission.class.getName(), null, null); assertUserHasPermission(url, null, null, BatchPermission.class.getName(), TARGET_NAME_START, null); assertUserHasPermission(url, null, null, RemoteTransactionPermission.class.getName(), null, null); assertUserHasPermission(url, null, null, RemoteEJBPermission.class.getName(), null, null); // valid user assertUserHasPermission(url, "guest", "guest", LoginPermission.class.getName(), null, null); assertUserHasPermission(url, "guest", "guest", BatchPermission.class.getName(), TARGET_NAME_START, null); assertUserHasPermission(url, "guest", "guest", RemoteTransactionPermission.class.getName(), null, null); assertUserHasPermission(url, "guest", "guest", RemoteEJBPermission.class.getName(), null, null); } /** * Tests security domain which doesn't contain any permission-mapper. */ @Test @OperateOnDeployment(SD_NO_MAPPER) public void testNoMapper(@ArquillianResource URL url) throws Exception { // anonymous assertUserHasntPermission(url, null, null, AllPermission.class.getName(), null, null); assertUserHasntPermission(url, null, null, LoginPermission.class.getName(), null, null); // valid user assertUserHasntPermission(url, "guest", "guest", LoginPermission.class.getName(), null, null); assertUserHasntPermission(url, "guest", "guest", BatchPermission.class.getName(), TARGET_NAME_START, null); } /** * Tests security domain which contains constant-permission-mapper with AllPermission. */ @Test @OperateOnDeployment(SD_ALL) public void testAllPermission(@ArquillianResource URL url) throws Exception { // anonymous assertUserHasPermission(url, null, null, AllPermission.class.getName(), null, null); assertUserHasPermission(url, null, null, LoginPermission.class.getName(), null, null); // valid user assertUserHasPermission(url, "guest", "guest", LoginPermission.class.getName(), null, null); assertUserHasPermission(url, "guest", "guest", BatchPermission.class.getName(), TARGET_NAME_START, null); assertUserHasPermission(url, "guest", "guest", NoPermission.class.getName(), null, null); } /** * Tests security domain which contains constant-permission-mapper with LoginPermission. */ @Test @OperateOnDeployment(SD_LOGIN) public void testLoginPermission(@ArquillianResource URL url) throws Exception { // anonymous assertUserHasntPermission(url, null, null, AllPermission.class.getName(), null, null); assertUserHasPermission(url, null, null, LoginPermission.class.getName(), null, null); // login permission doesn't take into account the name and action assertUserHasPermission(url, null, null, LoginPermission.class.getName(), TARGET_NAME, ACTION); // valid user assertUserHasPermission(url, "guest", "guest", LoginPermission.class.getName(), null, null); assertUserHasntPermission(url, "guest", "guest", BatchPermission.class.getName(), TARGET_NAME_START, null); assertUserHasntPermission(url, "guest", "guest", NoPermission.class.getName(), null, null); } /** * Tests security domain which contains constant-permission-mapper with permissions from different modules */ @Test @OperateOnDeployment(SD_MODULES) public void testPermissionsInModules(@ArquillianResource URL url) throws Exception { // anonymous assertUserHasntPermission(url, null, null, AllPermission.class.getName(), null, null); assertUserHasPermission(url, null, null, LoginPermission.class.getName(), null, null); assertUserHasntPermission(url, null, null, BatchPermission.class.getName(), "stop", null); assertUserHasPermission(url, null, null, BatchPermission.class.getName(), TARGET_NAME_START, null); assertUserHasPermission(url, null, null, JodaTimePermission.class.getName(), TARGET_NAME, null); // valid user assertUserHasPermission(url, "guest", "guest", LoginPermission.class.getName(), null, null); assertUserHasPermission(url, "guest", "guest", BatchPermission.class.getName(), TARGET_NAME_START, null); assertUserHasPermission(url, "guest", "guest", JodaTimePermission.class.getName(), TARGET_NAME, null); } private void assertUserHasPermission(URL webappUrl, String user, String password, String className, String target, String action) throws Exception { assertEquals("true", doPermissionCheckPostReq(webappUrl, user, password, className, target, action)); } private void assertUserHasntPermission(URL webappUrl, String user, String password, String className, String target, String action) throws Exception { assertEquals("false", doPermissionCheckPostReq(webappUrl, user, password, className, target, action)); } /** * Makes request to {@link CheckIdentityPermissionServlet}. */ private String doPermissionCheckPostReq(URL url, String user, String password, String className, String target, String action) throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException { String body; final URI uri = new URI(url.toExternalForm() + CheckIdentityPermissionServlet.SERVLET_PATH.substring(1)); final HttpPost post = new HttpPost(uri); List<NameValuePair> nvps = new ArrayList<>(); setParam(nvps, CheckIdentityPermissionServlet.PARAM_USER, user); setParam(nvps, CheckIdentityPermissionServlet.PARAM_PASSWORD, password); setParam(nvps, CheckIdentityPermissionServlet.PARAM_CLASS, className); setParam(nvps, CheckIdentityPermissionServlet.PARAM_TARGET, target); setParam(nvps, CheckIdentityPermissionServlet.PARAM_ACTION, action); post.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8)); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { try (CloseableHttpResponse response = httpClient.execute(post)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == SC_FORBIDDEN && user != null) { return Boolean.toString(false); } assertEquals("Unexpected status code in HTTP response.", SC_OK, statusCode); body = EntityUtils.toString(response.getEntity()); } } return body; } private void setParam(List<NameValuePair> nvps, final String paramName, String paramValue) { if (paramValue != null) { nvps.add(new BasicNameValuePair(paramName, paramValue)); } } /** * Creates web application with given name security domain name reference. The name is used as the archive name too. */ private static WebArchive createWar(final String sd) { return ShrinkWrap.create(WebArchive.class, sd + ".war").addClasses(CheckIdentityPermissionServlet.class) .addAsWebInfResource(Utils.getJBossWebXmlAsset(sd), "jboss-web.xml") .addAsManifestResource(PermissionUtils.createPermissionsXmlAsset( new ElytronPermission("authenticate"), new ElytronPermission("getSecurityDomain") ), "permissions.xml") .addAsManifestResource( Utils.getJBossDeploymentStructure("org.wildfly.extension.batch.jberet", "org.wildfly.transaction.client", "org.jboss.ejb-client", "org.joda.time"), "jboss-deployment-structure.xml") .addAsWebInfResource(new StringAsset(SecurityTestConstants.WEB_XML_BASIC_AUTHN), "web.xml"); } /** * Setup task which configures Elytron security domains for this test. */ public static class ServerSetup extends AbstractElytronSetupTask { @Override protected ConfigurableElement[] getConfigurableElements() { List<ConfigurableElement> elements = new ArrayList<>(); elements.add( SimpleSecurityDomain.builder() .withName(SD_NO_MAPPER).withDefaultRealm("ApplicationRealm").withRealms(SecurityDomainRealm .builder().withRealm("ApplicationRealm").withRoleDecoder("groups-to-roles").build()) .build()); elements.add(UndertowDomainMapper.builder().withName(SD_NO_MAPPER).withApplicationDomains(SD_NO_MAPPER).build()); addSecurityDomain(elements, SD_ALL, PermissionRef.fromPermission(new AllPermission())); addSecurityDomain(elements, SD_LOGIN, PermissionRef.fromPermission(new LoginPermission(TARGET_NAME, ACTION))); addSecurityDomain(elements, SD_MODULES, PermissionRef.fromPermission(new LoginPermission()), PermissionRef.fromPermission(new BatchPermission(TARGET_NAME_START), "org.wildfly.extension.batch.jberet"), PermissionRef.fromPermission(new JodaTimePermission(TARGET_NAME), "org.joda.time")); return elements.toArray(new ConfigurableElement[elements.size()]); } private void addSecurityDomain(List<ConfigurableElement> elements, String sdName, PermissionRef... permRefs) { elements.add(ConstantPermissionMapper.builder().withName(sdName).withPermissions(permRefs).build()); elements.add( SimpleSecurityDomain.builder().withName(sdName) .withDefaultRealm("ApplicationFsRealm").withPermissionMapper(sdName).withRealms(SecurityDomainRealm .builder().withRealm("ApplicationFsRealm").withRoleDecoder("groups-to-roles").build()) .build()); elements.add(UndertowDomainMapper.builder().withName(sdName).withApplicationDomains(sdName).build()); } } }
15,658
50.173203
127
java