From a1dd3c1ad2b79331c6b681d2fc23b20776cb739b Mon Sep 17 00:00:00 2001 From: strangelookingnerd Date: Fri, 14 Feb 2025 14:51:06 +0100 Subject: [PATCH] Migrate tests to JUnit5 * Migrate annotations and imports * Migrate assertions * Remove public visibility for test classes and methods * Minor clean up --- pom.xml | 4 +- .../plugins/oic/ConfigurationAsCodeTest.java | 84 ++-- .../plugins/oic/DescriptorImplTest.java | 39 +- .../oic/EscapeHatchCrumbExclusionTest.java | 23 +- .../org/jenkinsci/plugins/oic/FieldTest.java | 43 +- .../oic/OicAlgorithmValidatorFIPS140Test.java | 2 +- .../plugins/oic/OicCrumbExclusionTest.java | 14 +- .../plugins/oic/OicLogoutActionTest.java | 18 +- .../oic/OicSecurityRealmFIPSAlgoTest.java | 8 +- .../plugins/oic/OicSecurityRealmFipsTest.java | 71 ++- .../oic/OicSecurityRealmIdStrategyTest.java | 183 ++++---- .../plugins/oic/OicSecurityRealmTest.java | 74 ++-- .../oic/OicServerManualConfigurationTest.java | 33 +- .../OicServerWellKnownConfigurationTest.java | 55 ++- .../plugins/oic/OicUserDetailsTest.java | 30 +- .../org/jenkinsci/plugins/oic/PluginTest.java | 415 +++++++++--------- .../oic/ProxyAwareResourceRetrieverTest.java | 34 +- .../SecurityRealmConfigurationFIPSTest.java | 39 +- .../org/jenkinsci/plugins/oic/TestRealm.java | 39 +- .../oic/monitor/OicStrategyMonitorTest.java | 81 ++-- .../failsOnMigrationTest/config.xml | 28 -- 21 files changed, 629 insertions(+), 688 deletions(-) delete mode 100644 src/test/resources/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest/failsOnMigrationTest/config.xml diff --git a/pom.xml b/pom.xml index 399325cb..6e2fd36e 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,7 @@ io.jenkins.tools.bom bom-${jenkins.baseline}.x - 4051.v78dce3ce8b_d6 + 4136.vca_c3202a_7fd1 pom import @@ -230,7 +230,7 @@ org.wiremock wiremock-standalone - 3.11.0 + 3.12.0 test diff --git a/src/test/java/org/jenkinsci/plugins/oic/ConfigurationAsCodeTest.java b/src/test/java/org/jenkinsci/plugins/oic/ConfigurationAsCodeTest.java index d5de7619..3ac1617c 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/ConfigurationAsCodeTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/ConfigurationAsCodeTest.java @@ -1,46 +1,60 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import hudson.security.SecurityRealm; import hudson.util.Secret; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; +import io.jenkins.plugins.casc.misc.junit.jupiter.WithJenkinsConfiguredWithCode; import io.jenkins.plugins.casc.model.CNode; import java.util.ArrayList; import java.util.List; import jenkins.model.Jenkins; import org.jenkinsci.plugins.oic.OicSecurityRealm.TokenAuthMethod; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static io.jenkins.plugins.casc.misc.Util.getJenkinsRoot; import static io.jenkins.plugins.casc.misc.Util.toStringFromYamlFile; import static io.jenkins.plugins.casc.misc.Util.toYamlString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ConfigurationAsCodeTest { +@WithJenkinsConfiguredWithCode +class ConfigurationAsCodeTest { - @Rule(order = 1) - public final JenkinsConfiguredWithCodeRule j = new JenkinsConfiguredWithCodeRule(); + @RegisterExtension + static WellKnownMockExtension wellKnownMockExtension = new WellKnownMockExtension( + "MOCK_PORT", + "{\"issuer\": \"http://localhost:%1$d/\"," + + "\"authorization_endpoint\": \"http://localhost:%1$d/authorize\"," + + "\"token_endpoint\":\"http://localhost:%1$d/token\"," + + "\"userinfo_endpoint\":\"http://localhost:%1$d/user\"," + + "\"jwks_uri\":\"http://localhost:%1$d/jwks\"," + + "\"scopes_supported\": [\"openid\",\"email\"]," + + "\"subject_types_supported\": [\"public\"]," + + "\"end_session_endpoint\":\"http://localhost:%1$d/logout\"}"); @Test @ConfiguredWithCode("ConfigurationAsCode.yml") - public void testConfig() { + void testConfig(JenkinsConfiguredWithCodeRule j) { SecurityRealm realm = Jenkins.get().getSecurityRealm(); - assertTrue(realm instanceof OicSecurityRealm); + assertInstanceOf(OicSecurityRealm.class, realm); OicSecurityRealm oicSecurityRealm = (OicSecurityRealm) realm; OicServerManualConfiguration serverConf = @@ -72,7 +86,7 @@ public void testConfig() { @Test @ConfiguredWithCode("ConfigurationAsCode.yml") - public void testExport() throws Exception { + void testExport(JenkinsConfiguredWithCodeRule j) throws Exception { ConfigurationContext context = new ConfigurationContext(ConfiguratorRegistry.get()); CNode yourAttribute = @@ -97,10 +111,10 @@ public void testExport() throws Exception { @Test @ConfiguredWithCode("ConfigurationAsCodeMinimal.yml") - public void testMinimal() throws Exception { + void testMinimal(JenkinsConfiguredWithCodeRule j) { SecurityRealm realm = Jenkins.get().getSecurityRealm(); - assertTrue(realm instanceof OicSecurityRealm); + assertInstanceOf(OicSecurityRealm.class, realm); OicSecurityRealm oicSecurityRealm = (OicSecurityRealm) realm; OicServerManualConfiguration serverConf = (OicServerManualConfiguration) oicSecurityRealm.getServerConfiguration(); @@ -120,25 +134,13 @@ public void testMinimal() throws Exception { assertEquals("sub", oicSecurityRealm.getUserNameField()); assertTrue(oicSecurityRealm.isLogoutFromOpenidProvider()); assertFalse(oicSecurityRealm.isRootURLFromRequest()); - assertEquals(null, serverConf.getJwksServerUrl()); + assertNull(serverConf.getJwksServerUrl()); assertFalse(oicSecurityRealm.isDisableTokenVerification()); } - @Rule(order = 0) - public final WellKnownMockRule wellKnownMockRule = new WellKnownMockRule( - "MOCK_PORT", - "{\"issuer\": \"http://localhost:%1$d/\"," - + "\"authorization_endpoint\": \"http://localhost:%1$d/authorize\"," - + "\"token_endpoint\":\"http://localhost:%1$d/token\"," - + "\"userinfo_endpoint\":\"http://localhost:%1$d/user\"," - + "\"jwks_uri\":\"http://localhost:%1$d/jwks\"," - + "\"scopes_supported\": [\"openid\",\"email\"]," - + "\"subject_types_supported\": [\"public\"]," - + "\"end_session_endpoint\":\"http://localhost:%1$d/logout\"}"); - @Test @ConfiguredWithCode("ConfigurationAsCodeMinimalWellKnown.yml") - public void testMinimalWellKnown() throws Exception { + void testMinimalWellKnown(JenkinsConfiguredWithCodeRule j) { SecurityRealm realm = Jenkins.get().getSecurityRealm(); assertThat(realm, instanceOf(OicSecurityRealm.class)); OicSecurityRealm oicSecurityRealm = (OicSecurityRealm) realm; @@ -147,7 +149,7 @@ public void testMinimalWellKnown() throws Exception { OicServerWellKnownConfiguration serverConf = (OicServerWellKnownConfiguration) oicSecurityRealm.getServerConfiguration(); - String urlBase = String.format("http://localhost:%d", wellKnownMockRule.port()); + String urlBase = String.format("http://localhost:%d", wellKnownMockExtension.getPort()); assertFalse(oicSecurityRealm.isDisableSslVerification()); assertNull(oicSecurityRealm.getEmailFieldName()); @@ -165,33 +167,33 @@ public void testMinimalWellKnown() throws Exception { assertEquals(urlBase + "/well.known", serverConf.getWellKnownOpenIDConfigurationUrl()); } - /** Class to setup WireMockRule for well known with stub and setting port in env variable + /** Class to setup WellKnownMockExtension for well known with stub and setting port in env variable */ - public class WellKnownMockRule extends WireMockRule { + public static class WellKnownMockExtension extends WireMockExtension { private final String mockPortEnvName; private final String wellKnownAnswer; private String previousEnvValue; - public WellKnownMockRule(String mockPortEnvName, String wellKnownAnswer) { - super(new WireMockConfiguration().dynamicPort(), true); + public WellKnownMockExtension(String mockPortEnvName, String wellKnownAnswer) { + super(WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort())); this.mockPortEnvName = mockPortEnvName; this.wellKnownAnswer = wellKnownAnswer; } @Override - protected void before() { + protected void onBeforeAll(ExtensionContext context, WireMockRuntimeInfo info) { this.previousEnvValue = System.getProperty(this.mockPortEnvName); - System.setProperty(this.mockPortEnvName, String.valueOf(port())); + System.setProperty(this.mockPortEnvName, String.valueOf(getPort())); stubFor(get(urlPathEqualTo("/well.known")) .willReturn(aResponse() .withHeader("Content-Type", "text/html; charset=utf-8") - .withBody(String.format(this.wellKnownAnswer, port())))); - super.before(); + .withBody(String.format(this.wellKnownAnswer, getPort())))); } @Override - protected void after() { - super.after(); + protected void onAfterAll(ExtensionContext context, WireMockRuntimeInfo info) { if (this.previousEnvValue != null) { System.setProperty(this.mockPortEnvName, this.previousEnvValue); } else { diff --git a/src/test/java/org/jenkinsci/plugins/oic/DescriptorImplTest.java b/src/test/java/org/jenkinsci/plugins/oic/DescriptorImplTest.java index 8599cccd..cda81a0a 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/DescriptorImplTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/DescriptorImplTest.java @@ -1,34 +1,31 @@ package org.jenkinsci.plugins.oic; import hudson.util.FormValidation; -import java.io.IOException; import jenkins.model.Jenkins; import org.jenkinsci.plugins.oic.OicSecurityRealm.DescriptorImpl; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class DescriptorImplTest { - - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); +@WithJenkins +class DescriptorImplTest { private Jenkins jenkins; - @Before - public void setUp() { + @BeforeEach + void setUp(JenkinsRule jenkinsRule) { jenkins = jenkinsRule.getInstance(); } @Test - public void testOicSecurityRealmDescriptorImplManual() throws Exception { + void testOicSecurityRealmDescriptorImplManual() throws Exception { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptor(OicSecurityRealm.class); assertNotNull(descriptor); @@ -56,7 +53,7 @@ public void testOicSecurityRealmDescriptorImplManual() throws Exception { } @Test - public void testOicSecurityRealmDescriptorImplAuto() throws Exception { + void testOicSecurityRealmDescriptorImplAuto() throws Exception { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); @@ -84,7 +81,7 @@ public void testOicSecurityRealmDescriptorImplAuto() throws Exception { } @Test - public void doCheckUserNameField() throws IOException { + void doCheckUserNameField() { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); @@ -98,7 +95,7 @@ public void doCheckUserNameField() throws IOException { } @Test - public void doCheckFullNameFieldName() throws IOException { + void doCheckFullNameFieldName() { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); @@ -108,7 +105,7 @@ public void doCheckFullNameFieldName() throws IOException { } @Test - public void doCheckEmailFieldName() throws IOException { + void doCheckEmailFieldName() { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); @@ -118,7 +115,7 @@ public void doCheckEmailFieldName() throws IOException { } @Test - public void doCheckGroupsFieldName() throws IOException { + void doCheckGroupsFieldName() { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); @@ -128,7 +125,7 @@ public void doCheckGroupsFieldName() throws IOException { } @Test - public void doCheckTokenFieldToCheckKey() throws IOException { + void doCheckTokenFieldToCheckKey() { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); @@ -138,7 +135,7 @@ public void doCheckTokenFieldToCheckKey() throws IOException { } @Test - public void doCheckPostLogoutRedirectUrl() throws IOException { + void doCheckPostLogoutRedirectUrl() { OicSecurityRealm.DescriptorImpl descriptor = (DescriptorImpl) jenkins.getDescriptorOrDie(OicSecurityRealm.class); diff --git a/src/test/java/org/jenkinsci/plugins/oic/EscapeHatchCrumbExclusionTest.java b/src/test/java/org/jenkinsci/plugins/oic/EscapeHatchCrumbExclusionTest.java index 14b91baa..413dfc9c 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/EscapeHatchCrumbExclusionTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/EscapeHatchCrumbExclusionTest.java @@ -2,16 +2,14 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class EscapeHatchCrumbExclusionTest { +class EscapeHatchCrumbExclusionTest { private EscapeHatchCrumbExclusion crumb = new EscapeHatchCrumbExclusion(); private HttpServletResponse response = null; @@ -28,24 +26,21 @@ public String getPathInfo() { } @Test - public void process_WithNullPath() throws IOException, ServletException { + void process_WithNullPath() throws IOException, ServletException { MockHttpServletRequest request = newRequestWithPath(""); assertFalse(crumb.process(request, response, chain)); } @Test - public void process_WithWrongPath() throws IOException, ServletException { + void process_WithWrongPath() throws IOException, ServletException { MockHttpServletRequest request = newRequestWithPath("fictionalPath"); assertFalse(crumb.process(request, response, chain)); } @Test - public void process_WithGoodPath() throws IOException, ServletException { - chain = new FilterChain() { - @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException { - // do nothing - } + void process_WithGoodPath() throws IOException, ServletException { + chain = (arg0, arg1) -> { + // do nothing }; MockHttpServletRequest request = newRequestWithPath("/securityRealm/escapeHatch"); diff --git a/src/test/java/org/jenkinsci/plugins/oic/FieldTest.java b/src/test/java/org/jenkinsci/plugins/oic/FieldTest.java index 2beb61ee..087485e1 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/FieldTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/FieldTest.java @@ -1,26 +1,27 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import java.util.HashMap; import java.util.Map; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.test.JenkinsRule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class FieldTest { +@WithJenkins +class FieldTest { - @Rule - public WireMockRule wireMockRule = new WireMockRule(new WireMockConfiguration().dynamicPort(), true); - - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort()) + .build(); @Test - public void testNestedLookup() throws Exception { + void testNestedLookup() throws Exception { HashMap user = new HashMap<>(); user.put("id", "100"); @@ -29,7 +30,7 @@ public void testNestedLookup() throws Exception { payload.put("user", user); payload.put("none", null); - TestRealm realm = new TestRealm(wireMockRule); + TestRealm realm = new TestRealm(wireMock); assertEquals("myemail@example.com", realm.getStringFieldFromJMESPath(payload, "email")); assertEquals("100", realm.getStringFieldFromJMESPath(payload, "user.id")); @@ -40,7 +41,7 @@ public void testNestedLookup() throws Exception { } @Test - public void testNormalLookupDueToDot() throws Exception { + void testNormalLookupDueToDot() throws Exception { HashMap user = new HashMap<>(); user.put("id", "100"); @@ -50,7 +51,7 @@ public void testNormalLookupDueToDot() throws Exception { payload.put("none", null); payload.put("user.name", "myusername"); - TestRealm realm = new TestRealm(wireMockRule); + TestRealm realm = new TestRealm(wireMock); assertEquals("myemail@example.com", realm.getStringFieldFromJMESPath(payload, "email")); assertNull(realm.getStringFieldFromJMESPath(payload, "unknown")); @@ -61,7 +62,7 @@ public void testNormalLookupDueToDot() throws Exception { } @Test - public void testFieldProcessing() throws Exception { + void testFieldProcessing() throws Exception { HashMap user = new HashMap<>(); user.put("id", "100"); user.put("name", "john"); @@ -70,17 +71,17 @@ public void testFieldProcessing() throws Exception { Map payload = new HashMap<>(); payload.put("user", user); - TestRealm realm = new TestRealm(wireMockRule); + TestRealm realm = new TestRealm(wireMock); assertEquals("john dow", realm.getStringFieldFromJMESPath(payload, "[user.name, user.surname] | join(' ', @)")); } @Test - public void testInvalidFieldName() throws Exception { + void testInvalidFieldName() throws Exception { Map payload = new HashMap<>(); payload.put("user", "john"); - TestRealm realm = new TestRealm(wireMockRule); + TestRealm realm = new TestRealm(wireMock); assertNull(realm.getStringFieldFromJMESPath(payload, "[user)")); } diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicAlgorithmValidatorFIPS140Test.java b/src/test/java/org/jenkinsci/plugins/oic/OicAlgorithmValidatorFIPS140Test.java index 43275d45..23d048ca 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicAlgorithmValidatorFIPS140Test.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicAlgorithmValidatorFIPS140Test.java @@ -9,7 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mockStatic; -public class OicAlgorithmValidatorFIPS140Test { +class OicAlgorithmValidatorFIPS140Test { @Test void isJwsAlgorithmFipsCompliant() { diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicCrumbExclusionTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicCrumbExclusionTest.java index 22ed2133..599ab29e 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicCrumbExclusionTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicCrumbExclusionTest.java @@ -11,8 +11,8 @@ import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; @@ -57,7 +57,7 @@ void exclusion_applies_when_realm_is_OIC_and_path_is_finishLogin() throws Except withOicSecurityRealm(); OicCrumbExclusion oicCrumbExclusion = new OicCrumbExclusion(); - assertTrue("path should be excluded", oicCrumbExclusion.process(request, response, chain)); + assertTrue(oicCrumbExclusion.process(request, response, chain), "path should be excluded"); Mockito.verify(chain, times(1)).doFilter(request, response); } @@ -68,7 +68,7 @@ void exclusion_does_not_apply_when_realm_is_OIC_and_path_is_not_finishLogin() th withOicSecurityRealm(); OicCrumbExclusion oicCrumbExclusion = new OicCrumbExclusion(); - assertFalse("path should not be excluded", oicCrumbExclusion.process(request, response, chain)); + assertFalse(oicCrumbExclusion.process(request, response, chain), "path should not be excluded"); Mockito.verify(chain, times(0)).doFilter(request, response); } @@ -78,7 +78,7 @@ void exclusion_does_not_apply_when_realm_is_not_OIC_and_path_is_finishLogin() th withRequestPath("/securityRealm/finishLogin"); OicCrumbExclusion oicCrumbExclusion = new OicCrumbExclusion(); - assertFalse("path should not be excluded", oicCrumbExclusion.process(request, response, chain)); + assertFalse(oicCrumbExclusion.process(request, response, chain), "path should not be excluded"); Mockito.verify(chain, times(0)).doFilter(request, response); } @@ -88,14 +88,14 @@ void exclusion_does_not_apply_when_realm_is_not_OIC_and_path_is_not_finishLogin( withRequestPath("/securityRealm/anything"); OicCrumbExclusion oicCrumbExclusion = new OicCrumbExclusion(); - assertFalse("path should not be excluded", oicCrumbExclusion.process(request, response, chain)); + assertFalse(oicCrumbExclusion.process(request, response, chain), "path should not be excluded"); Mockito.verify(chain, times(0)).doFilter(request, response); } @Test void exclusion_does_not_apply_when_jenkins_is_not_set() throws Exception { OicCrumbExclusion oicCrumbExclusion = new OicCrumbExclusion(); - assertFalse("path should not be excluded", oicCrumbExclusion.process(request, response, chain)); + assertFalse(oicCrumbExclusion.process(request, response, chain), "path should not be excluded"); Mockito.verify(chain, times(0)).doFilter(request, response); } } diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicLogoutActionTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicLogoutActionTest.java index 6c6c2120..b54c45c3 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicLogoutActionTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicLogoutActionTest.java @@ -1,28 +1,28 @@ package org.jenkinsci.plugins.oic; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.jenkinsci.plugins.oic.OicLogoutAction.POST_LOGOUT_URL; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -public class OicLogoutActionTest { +class OicLogoutActionTest { private OicLogoutAction action; - @Before - public void init() { + @BeforeEach + void init() { action = new OicLogoutAction(); } @Test - public void getIconFileName() { + void getIconFileName() { assertNull(action.getIconFileName()); } @Test - public void getUrlName() { + void getUrlName() { assertEquals(POST_LOGOUT_URL, action.getUrlName()); } } diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFIPSAlgoTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFIPSAlgoTest.java index 08e17612..ae875738 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFIPSAlgoTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFIPSAlgoTest.java @@ -10,7 +10,7 @@ import java.nio.file.Paths; import jenkins.security.FIPS140; import org.apache.commons.io.FileUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import static org.hamcrest.MatcherAssert.assertThat; @@ -22,10 +22,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; -public class OicSecurityRealmFIPSAlgoTest { +class OicSecurityRealmFIPSAlgoTest { @Test - public void doCheckAlgorithmFilteredNotInFipsMode() throws Exception { + void doCheckAlgorithmFilteredNotInFipsMode() throws Exception { try (MockedStatic fips140Mocked = mockStatic(FIPS140.class)) { fips140Mocked.when(FIPS140::useCompliantAlgorithms).thenReturn(false); @@ -86,7 +86,7 @@ public void doCheckAlgorithmFilteredNotInFipsMode() throws Exception { } @Test - public void doCheckAlgorithmFilteredInFipsMode() throws Exception { + void doCheckAlgorithmFilteredInFipsMode() throws Exception { try (MockedStatic fips140Mocked = mockStatic(FIPS140.class)) { fips140Mocked.when(FIPS140::useCompliantAlgorithms).thenReturn(true); diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest.java index befb9410..73c142b2 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest.java @@ -1,42 +1,51 @@ package org.jenkinsci.plugins.oic; import hudson.Util; +import hudson.init.InitMilestone; import hudson.model.Descriptor; import hudson.util.FormValidation; import hudson.util.Secret; import java.io.IOException; import jenkins.security.FIPS140; import org.hamcrest.Matcher; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.jvnet.hudson.reactor.ReactorException; -import org.jvnet.hudson.test.FlagRule; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.WithoutJenkins; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.jvnet.hudson.test.recipes.LocalData; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.jvnet.hudson.test.JenkinsMatchers.hasKind; -public class OicSecurityRealmFipsTest { +@WithJenkins +class OicSecurityRealmFipsTest { - @ClassRule - public static FlagRule fipsFlag = FlagRule.systemProperty(FIPS140.class.getName() + ".COMPLIANCE", "true"); + private static Object fipsProperty; - @Rule - public NonFailingOnStartupJenkinsRule j = new NonFailingOnStartupJenkinsRule(); + @BeforeAll + static void setUp() { + fipsProperty = System.getProperties().setProperty(FIPS140.class.getName() + ".COMPLIANCE", "true"); + } + + @AfterAll + static void tearDown() { + if (fipsProperty != null) { + System.setProperty(FIPS140.class.getName() + ".COMPLIANCE", String.valueOf(fipsProperty)); + } else { + System.clearProperty(FIPS140.class.getName() + ".COMPLIANCE"); + } + } @Test @WithoutJenkins - public void settingNonCompliantValuesNotAllowedTest() throws IOException, Descriptor.FormException { + void settingNonCompliantValuesNotAllowedTest() throws IOException, Descriptor.FormException { OicSecurityRealm realm = new OicSecurityRealm("clientId", Secret.fromString("secret"), null, false, null, null); Descriptor.FormException ex = assertThrows( Descriptor.FormException.class, @@ -55,7 +64,7 @@ public void settingNonCompliantValuesNotAllowedTest() throws IOException, Descri @Test @WithoutJenkins - public void validationWarnsOfInvalidValuesTest() { + void validationWarnsOfInvalidValuesTest() { OicSecurityRealm.DescriptorImpl descriptor = new OicSecurityRealm.DescriptorImpl(); FormValidation response = descriptor.doCheckDisableSslVerification(true); assertThat( @@ -78,38 +87,10 @@ public void validationWarnsOfInvalidValuesTest() { assertThat("Validation is ok", response.kind, is(FormValidation.Kind.OK)); } - // This test is not strictly needed as per - // https://github.com/jenkinsci/jep/blob/master/jep/237/README.adoc#backwards-compatibility - // Just adding it to cover corner cases @Test @LocalData - public void failsOnMigrationTest() { - assertThat( - "We should get a ReactorException, startup failed", j.getError(), instanceOf(ReactorException.class)); - } - - @Test - @LocalData - public void worksOnMigrationWithValidValuesTest() { - assertThat("Instance is up and running with no errors", j.getError(), nullValue()); - } - - // Simple JenkinsRule extension that doesn't make test fail on startup errors, so we can check the error. - public static class NonFailingOnStartupJenkinsRule extends JenkinsRule { - private Throwable error; - - @Override - public void before() throws Throwable { - try { - super.before(); - } catch (Throwable t) { - error = t; - } - } - - public Throwable getError() { - return error; - } + void worksOnMigrationWithValidValuesTest(JenkinsRule j) { + assertThat("Instance is up and running with no errors", j.jenkins.getInitLevel(), is(InitMilestone.COMPLETED)); } private static Matcher withMessageContaining(String message) { diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmIdStrategyTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmIdStrategyTest.java index 28e7da7b..0c9be157 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmIdStrategyTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmIdStrategyTest.java @@ -1,117 +1,116 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.model.User; import hudson.security.SecurityRealm; import jenkins.model.IdStrategy; import jenkins.model.Jenkins; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.JenkinsSessionRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class OicSecurityRealmIdStrategyTest { +@WithJenkins +class OicSecurityRealmIdStrategyTest { - @Rule - public JenkinsSessionRule sessions = new JenkinsSessionRule(); - - @Rule - public WireMockRule wireMockRule = new WireMockRule(new WireMockConfiguration().dynamicPort(), true); + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort()) + .build(); @Test @Issue("SECURITY-3461") - public void testUserIdStrategy_caseInsensitive() throws Throwable { - sessions.then(r -> { - TestRealm realm = new TestRealm(new TestRealm.Builder(wireMockRule) - .WithMinimalDefaults().WithUserIdStrategy(IdStrategy.CASE_INSENSITIVE)); - Jenkins.get().setSecurityRealm(realm); - User testuser = User.getById("testuser", true); - assertNotNull(testuser); - assertEquals("testuser", testuser.getDisplayName()); - testuser.save(); - - User testUSER = User.getById("testUSER", true); - assertNotNull(testUSER); - assertEquals("testuser", testUSER.getDisplayName()); - testUSER.save(); - - assertEquals(testuser, testUSER); - }); - sessions.then(r -> { - User testuser = User.getById("testuser", false); - assertNotNull(testuser); - assertEquals("testuser", testuser.getDisplayName()); - - User testUSER = User.getById("testUSER", false); - assertNotNull(testUSER); - assertEquals("testuser", testUSER.getDisplayName()); - assertEquals(testuser, testUSER); - }); + void testUserIdStrategy_caseInsensitive(JenkinsRule r) throws Throwable { + TestRealm realm = new TestRealm( + new TestRealm.Builder(wireMock).WithMinimalDefaults().WithUserIdStrategy(IdStrategy.CASE_INSENSITIVE)); + Jenkins.get().setSecurityRealm(realm); + User testuser = User.getById("testuser", true); + assertNotNull(testuser); + assertEquals("testuser", testuser.getDisplayName()); + testuser.save(); + + User testUSER = User.getById("testUSER", true); + assertNotNull(testUSER); + assertEquals("testuser", testUSER.getDisplayName()); + testUSER.save(); + + assertEquals(testuser, testUSER); + + r.restart(); + + testuser = User.getById("testuser", false); + assertNotNull(testuser); + assertEquals("testuser", testuser.getDisplayName()); + + testUSER = User.getById("testUSER", false); + assertNotNull(testUSER); + assertEquals("testuser", testUSER.getDisplayName()); + assertEquals(testuser, testUSER); } @Test @Issue("SECURITY-3461") - public void testUserIdStrategy_caseSensitive() throws Throwable { - sessions.then(r -> { - TestRealm realm = new TestRealm(new TestRealm.Builder(wireMockRule) - .WithMinimalDefaults().WithUserIdStrategy(new IdStrategy.CaseSensitive())); - Jenkins.get().setSecurityRealm(realm); - User testuser = User.getById("testuser", true); - assertNotNull(testuser); - assertEquals("testuser", testuser.getDisplayName()); - testuser.save(); - - User testUSER = User.getById("testUSER", true); - assertNotNull(testUSER); - assertEquals("testUSER", testUSER.getDisplayName()); - testUSER.save(); - - assertNotEquals(testuser, testUSER); - }); - sessions.then(r -> { - User testuser = User.getById("testuser", false); - assertNotNull(testuser); - assertEquals("testuser", testuser.getDisplayName()); - - User testUSER = User.getById("testUSER", false); - assertNotNull(testUSER); - assertEquals("testUSER", testUSER.getDisplayName()); - - assertNotEquals(testuser, testUSER); - }); + void testUserIdStrategy_caseSensitive(JenkinsRule r) throws Throwable { + TestRealm realm = new TestRealm(new TestRealm.Builder(wireMock) + .WithMinimalDefaults().WithUserIdStrategy(new IdStrategy.CaseSensitive())); + Jenkins.get().setSecurityRealm(realm); + User testuser = User.getById("testuser", true); + assertNotNull(testuser); + assertEquals("testuser", testuser.getDisplayName()); + testuser.save(); + + User testUSER = User.getById("testUSER", true); + assertNotNull(testUSER); + assertEquals("testUSER", testUSER.getDisplayName()); + testUSER.save(); + + assertNotEquals(testuser, testUSER); + + r.restart(); + + testuser = User.getById("testuser", false); + assertNotNull(testuser); + assertEquals("testuser", testuser.getDisplayName()); + + testUSER = User.getById("testUSER", false); + assertNotNull(testUSER); + assertEquals("testUSER", testUSER.getDisplayName()); + + assertNotEquals(testuser, testUSER); } @Test @Issue("SECURITY-3461") - public void testUserIdStrategy_default() throws Throwable { - sessions.then(r -> { - TestRealm realm = new TestRealm(wireMockRule); - Jenkins.get().setSecurityRealm(realm); - }); - sessions.then(r -> { - // when restarting, ensure the default case-insensitive is used - SecurityRealm securityRealm = Jenkins.get().getSecurityRealm(); - assertThat(securityRealm, instanceOf(OicSecurityRealm.class)); - OicSecurityRealm oicSecurityRealm = (OicSecurityRealm) securityRealm; - assertTrue(oicSecurityRealm.isMissingIdStrategy()); - assertEquals(IdStrategy.CASE_INSENSITIVE, securityRealm.getUserIdStrategy()); - assertEquals(IdStrategy.CASE_INSENSITIVE, securityRealm.getGroupIdStrategy()); - - TestRealm realm = new TestRealm(new TestRealm.Builder(wireMockRule) - .WithMinimalDefaults() - .WithUserIdStrategy(IdStrategy.CASE_INSENSITIVE) - .WithGroupIdStrategy(IdStrategy.CASE_INSENSITIVE)); - Jenkins.get().setSecurityRealm(realm); - assertFalse(realm.isMissingIdStrategy()); - }); + void testUserIdStrategy_default(JenkinsRule r) throws Throwable { + TestRealm realm = new TestRealm(wireMock); + Jenkins.get().setSecurityRealm(realm); + + r.restart(); + + // when restarting, ensure the default case-insensitive is used + SecurityRealm securityRealm = Jenkins.get().getSecurityRealm(); + assertThat(securityRealm, instanceOf(OicSecurityRealm.class)); + OicSecurityRealm oicSecurityRealm = (OicSecurityRealm) securityRealm; + assertTrue(oicSecurityRealm.isMissingIdStrategy()); + assertEquals(IdStrategy.CASE_INSENSITIVE, securityRealm.getUserIdStrategy()); + assertEquals(IdStrategy.CASE_INSENSITIVE, securityRealm.getGroupIdStrategy()); + + realm = new TestRealm(new TestRealm.Builder(wireMock) + .WithMinimalDefaults() + .WithUserIdStrategy(IdStrategy.CASE_INSENSITIVE) + .WithGroupIdStrategy(IdStrategy.CASE_INSENSITIVE)); + Jenkins.get().setSecurityRealm(realm); + assertFalse(realm.isMissingIdStrategy()); } } diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmTest.java index 45398b67..af892f61 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicSecurityRealmTest.java @@ -1,13 +1,13 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.util.Secret; import java.util.Collection; import java.util.List; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; @@ -16,27 +16,30 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.crypto.bcrypt.BCrypt; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class OicSecurityRealmTest { +@WithJenkins +class OicSecurityRealmTest { public static final String ADMIN = "admin"; private static final SimpleGrantedAuthority GRANTED_AUTH1 = new SimpleGrantedAuthority(ADMIN); - @Rule - public WireMockRule wireMockRule = new WireMockRule(new WireMockConfiguration().dynamicPort(), true); - - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort()) + .build(); @Test - public void testAuthenticate_withAnonymousAuthenticationToken() throws Exception { - TestRealm realm = new TestRealm(wireMockRule); + void testAuthenticate_withAnonymousAuthenticationToken(JenkinsRule jenkinsRule) throws Exception { + TestRealm realm = new TestRealm(wireMock); AuthenticationManager manager = realm.getSecurityComponents().manager2; assertNotNull(manager); @@ -49,42 +52,38 @@ public void testAuthenticate_withAnonymousAuthenticationToken() throws Exception assertEquals(token, manager.authenticate(token)); } - @Test(expected = BadCredentialsException.class) - public void testAuthenticate_withUsernamePasswordAuthenticationToken() throws Exception { - TestRealm realm = new TestRealm(wireMockRule); + @Test + void testAuthenticate_withUsernamePasswordAuthenticationToken(JenkinsRule jenkinsRule) throws Exception { + TestRealm realm = new TestRealm(wireMock); AuthenticationManager manager = realm.getSecurityComponents().manager2; - assertNotNull(manager); - String key = "testKey"; Object principal = "testUser"; Collection authorities = List.of(GRANTED_AUTH1); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(key, principal, authorities); - - assertEquals(token, manager.authenticate(token)); + assertThrows(BadCredentialsException.class, () -> assertEquals(token, manager.authenticate(token))); } @Test - public void testGetAuthenticationGatewayUrl() throws Exception { - TestRealm realm = new TestRealm(wireMockRule); + void testGetAuthenticationGatewayUrl(JenkinsRule jenkinsRule) throws Exception { + TestRealm realm = new TestRealm(wireMock); assertEquals("securityRealm/escapeHatch", realm.getAuthenticationGatewayUrl()); } @Test - public void testShouldSetNullClientSecretWhenSecretIsNull() throws Exception { - TestRealm realm = new TestRealm.Builder(wireMockRule) + void testShouldSetNullClientSecretWhenSecretIsNull(JenkinsRule jenkinsRule) throws Exception { + TestRealm realm = new TestRealm.Builder(wireMock) .WithMinimalDefaults().WithClient("id without secret", null).build(); assertEquals("none", Secret.toString(realm.getClientSecret())); } @Test - public void testGetValidRedirectUrl() throws Exception { + void testGetValidRedirectUrl(JenkinsRule jenkinsRule) throws Exception { // root url is http://localhost:????/jenkins/ final String rootUrl = jenkinsRule.jenkins.getRootUrl(); - TestRealm realm = - new TestRealm.Builder(wireMockRule).WithMinimalDefaults().build(); + TestRealm realm = new TestRealm.Builder(wireMock).WithMinimalDefaults().build(); assertEquals(rootUrl + "foo", realm.getValidRedirectUrl("foo")); assertEquals(rootUrl + "foo", realm.getValidRedirectUrl("/jenkins/foo")); @@ -96,12 +95,11 @@ public void testGetValidRedirectUrl() throws Exception { } @Test - public void testShouldReturnRootUrlWhenRedirectUrlIsInvalid() throws Exception { + void testShouldReturnRootUrlWhenRedirectUrlIsInvalid(JenkinsRule jenkinsRule) throws Exception { // root url is http://localhost:????/jenkins/ String rootUrl = jenkinsRule.jenkins.getRootUrl(); - TestRealm realm = - new TestRealm.Builder(wireMockRule).WithMinimalDefaults().build(); + TestRealm realm = new TestRealm.Builder(wireMock).WithMinimalDefaults().build(); assertEquals(rootUrl, realm.getValidRedirectUrl("/bar")); assertEquals(rootUrl, realm.getValidRedirectUrl("../bar")); @@ -111,11 +109,11 @@ public void testShouldReturnRootUrlWhenRedirectUrlIsInvalid() throws Exception { } @Test - public void testShouldCheckEscapeHatchWithPlainPassword() throws Exception { + void testShouldCheckEscapeHatchWithPlainPassword(JenkinsRule jenkinsRule) throws Exception { final String escapeHatchUsername = "aUsername"; final String escapeHatchPassword = "aSecretPassword"; - TestRealm realm = new TestRealm.Builder(wireMockRule) + TestRealm realm = new TestRealm.Builder(wireMock) .WithMinimalDefaults() .WithEscapeHatch(true, escapeHatchUsername, escapeHatchPassword, "Group") .build(); @@ -128,12 +126,12 @@ public void testShouldCheckEscapeHatchWithPlainPassword() throws Exception { } @Test - public void testShouldCheckEscapeHatchWithHashedPassword() throws Exception { + void testShouldCheckEscapeHatchWithHashedPassword(JenkinsRule jenkinsRule) throws Exception { final String escapeHatchUsername = "aUsername"; final String escapeHatchPassword = "aSecretPassword"; final String escapeHatchCryptedPassword = BCrypt.hashpw(escapeHatchPassword, BCrypt.gensalt()); - TestRealm realm = new TestRealm.Builder(wireMockRule) + TestRealm realm = new TestRealm.Builder(wireMock) .WithMinimalDefaults() .WithEscapeHatch(true, escapeHatchUsername, escapeHatchCryptedPassword, "Group") .build(); diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicServerManualConfigurationTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicServerManualConfigurationTest.java index 8f2309f3..5451dc55 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicServerManualConfigurationTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicServerManualConfigurationTest.java @@ -2,12 +2,11 @@ import hudson.Util; import hudson.util.FormValidation; -import java.io.IOException; import org.hamcrest.Matcher; import org.jenkinsci.plugins.oic.OicServerManualConfiguration.DescriptorImpl; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; @@ -16,14 +15,12 @@ import static org.hamcrest.Matchers.is; import static org.jvnet.hudson.test.JenkinsMatchers.hasKind; -public class OicServerManualConfigurationTest { - - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); +@WithJenkins +class OicServerManualConfigurationTest { @Test - public void ddoCheckTokenServerUrl() throws IOException { - DescriptorImpl descriptor = getDescriptor(); + void ddoCheckTokenServerUrl(JenkinsRule jenkinsRule) { + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat( descriptor.doCheckTokenServerUrl(null), @@ -35,8 +32,8 @@ public void ddoCheckTokenServerUrl() throws IOException { } @Test - public void doCheckAuthorizationServerUrl() throws IOException { - DescriptorImpl descriptor = getDescriptor(); + void doCheckAuthorizationServerUrl(JenkinsRule jenkinsRule) { + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat( descriptor.doCheckAuthorizationServerUrl(null), @@ -48,8 +45,8 @@ public void doCheckAuthorizationServerUrl() throws IOException { } @Test - public void doCheckJwksServerUrl() throws IOException { - DescriptorImpl descriptor = getDescriptor(); + void doCheckJwksServerUrl(JenkinsRule jenkinsRule) { + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat(descriptor.doCheckJwksServerUrl(null), hasKind(FormValidation.Kind.OK)); assertThat(descriptor.doCheckJwksServerUrl(""), hasKind(FormValidation.Kind.OK)); @@ -57,8 +54,8 @@ public void doCheckJwksServerUrl() throws IOException { } @Test - public void doCheckScopes() throws IOException { - DescriptorImpl descriptor = getDescriptor(); + void doCheckScopes(JenkinsRule jenkinsRule) { + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat( descriptor.doCheckScopes(null), @@ -76,8 +73,8 @@ public void doCheckScopes() throws IOException { } @Test - public void doCheckEndSessionEndpoint() throws IOException { - DescriptorImpl descriptor = getDescriptor(); + void doCheckEndSessionEndpoint(JenkinsRule jenkinsRule) { + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat( descriptor.doCheckEndSessionUrl(null), @@ -91,7 +88,7 @@ public void doCheckEndSessionEndpoint() throws IOException { assertThat(descriptor.doCheckEndSessionUrl("http://localhost.jwks"), hasKind(FormValidation.Kind.OK)); } - private static DescriptorImpl getDescriptor() { + private static DescriptorImpl getDescriptor(JenkinsRule jenkinsRule) { return (DescriptorImpl) jenkinsRule.jenkins.getDescriptor(OicServerManualConfiguration.class); } diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicServerWellKnownConfigurationTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicServerWellKnownConfigurationTest.java index 418bd5e9..13e962d6 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicServerWellKnownConfigurationTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicServerWellKnownConfigurationTest.java @@ -1,20 +1,19 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.Util; import hudson.util.FormValidation; -import java.io.IOException; import org.hamcrest.Matcher; import org.jenkinsci.plugins.oic.OicServerWellKnownConfiguration.DescriptorImpl; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; @@ -22,19 +21,19 @@ import static org.hamcrest.Matchers.is; import static org.jvnet.hudson.test.JenkinsMatchers.hasKind; -public class OicServerWellKnownConfigurationTest { +@WithJenkins +class OicServerWellKnownConfigurationTest { - @ClassRule - public static JenkinsRule jenkinsRule = new JenkinsRule(); - - @Rule - public WireMockRule wireMockRule = - new WireMockRule(new WireMockConfiguration().dynamicPort().dynamicHttpsPort(), true); + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort().dynamicHttpsPort()) + .build(); @Test - public void doCheckWellKnownOpenIDConfigurationUrl() throws IOException { - configureWireMockWellKnownEndpoint(); - DescriptorImpl descriptor = getDescriptor(); + void doCheckWellKnownOpenIDConfigurationUrl(JenkinsRule jenkinsRule) { + configureWireMockWellKnownEndpoint(jenkinsRule); + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat( descriptor.doCheckWellKnownOpenIDConfigurationUrl(null, false), @@ -44,16 +43,16 @@ public void doCheckWellKnownOpenIDConfigurationUrl() throws IOException { allOf(hasKind(FormValidation.Kind.ERROR), withMessage("Not a valid url."))); assertThat( descriptor.doCheckWellKnownOpenIDConfigurationUrl( - "http://localhost:" + wireMockRule.port() + ("/.well-known/openid-configuration"), false), + "http://localhost:" + wireMock.getPort() + ("/.well-known/openid-configuration"), false), hasKind(FormValidation.Kind.OK)); assertThat( descriptor.doCheckWellKnownOpenIDConfigurationUrl( - wireMockRule.url("/.well-known/openid-configuration"), true), // disable TLS + wireMock.url("/.well-known/openid-configuration"), true), // disable TLS hasKind(FormValidation.Kind.OK)); // TLS error. assertThat( descriptor.doCheckWellKnownOpenIDConfigurationUrl( - wireMockRule.url("/.well-known/openid-configuration"), false), + wireMock.url("/.well-known/openid-configuration"), false), allOf( hasKind(FormValidation.Kind.ERROR), withMessageContaining("The server presented an invalid or incorrect TLS certificate"))); @@ -80,8 +79,8 @@ public void doCheckWellKnownOpenIDConfigurationUrl() throws IOException { } @Test - public void doCheckOverrideScopes() throws IOException { - DescriptorImpl descriptor = getDescriptor(); + void doCheckOverrideScopes(JenkinsRule jenkinsRule) { + DescriptorImpl descriptor = getDescriptor(jenkinsRule); assertThat(descriptor.doCheckScopesOverride(null), hasKind(FormValidation.Kind.OK)); assertThat(descriptor.doCheckScopesOverride(""), hasKind(FormValidation.Kind.OK)); @@ -95,15 +94,15 @@ public void doCheckOverrideScopes() throws IOException { withMessage("Are you sure you don't want to include 'openid' as a scope?"))); } - private void configureWireMockWellKnownEndpoint() { - String authUrl = "http://localhost:" + wireMockRule.port() + "/authorization"; - String tokenUrl = "http://localhost:" + wireMockRule.port() + "/token"; - String userInfoUrl = "http://localhost:" + wireMockRule.port() + "/userinfo"; - String issuer = "http://localhost:" + wireMockRule.port() + "/"; + private void configureWireMockWellKnownEndpoint(JenkinsRule jenkinsRule) { + String authUrl = "http://localhost:" + wireMock.getPort() + "/authorization"; + String tokenUrl = "http://localhost:" + wireMock.getPort() + "/token"; + String userInfoUrl = "http://localhost:" + wireMock.getPort() + "/userinfo"; + String issuer = "http://localhost:" + wireMock.getPort() + "/"; String jwksUrl = "null"; String endSessionUrl = "null"; - wireMockRule.stubFor(get(urlPathEqualTo("/.well-known/openid-configuration")) + wireMock.stubFor(get(urlPathEqualTo("/.well-known/openid-configuration")) .willReturn(aResponse() .withHeader("Content-Type", "text/html; charset=utf-8") .withBody(String.format( @@ -114,7 +113,7 @@ private void configureWireMockWellKnownEndpoint() { authUrl, issuer, tokenUrl, userInfoUrl, jwksUrl, endSessionUrl)))); } - private static DescriptorImpl getDescriptor() { + private static DescriptorImpl getDescriptor(JenkinsRule jenkinsRule) { return (DescriptorImpl) jenkinsRule.jenkins.getDescriptor(OicServerWellKnownConfiguration.class); } diff --git a/src/test/java/org/jenkinsci/plugins/oic/OicUserDetailsTest.java b/src/test/java/org/jenkinsci/plugins/oic/OicUserDetailsTest.java index 328a7302..a630428f 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/OicUserDetailsTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/OicUserDetailsTest.java @@ -2,18 +2,18 @@ import java.util.Arrays; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class OicUserDetailsTest { +class OicUserDetailsTest { private OicUserDetails details; @@ -25,44 +25,44 @@ public class OicUserDetailsTest { private List grantedAuthorities = Arrays.asList(admin, read); - @Before - public void init() { + @BeforeEach + void init() { details = new OicUserDetails(userName, grantedAuthorities); } @Test - public void testGetAuthorities() { + void testGetAuthorities() { assertThat(details.getAuthorities(), containsInAnyOrder(admin, read)); } @Test - public void testGetPassword() { + void testGetPassword() { // OpenID Connect => no passwords... assertNull(details.getPassword()); } @Test - public void testGetUsername() { + void testGetUsername() { assertEquals(userName, details.getUsername()); } @Test - public void TestIsAccountNonExpired() { + void TestIsAccountNonExpired() { assertTrue(details.isAccountNonExpired()); } @Test - public void TestIsAccountNonLocked() { + void TestIsAccountNonLocked() { assertTrue(details.isAccountNonLocked()); } @Test - public void TestIsCredentialsNonExpired() { + void TestIsCredentialsNonExpired() { assertTrue(details.isCredentialsNonExpired()); } @Test - public void TestIsEnabled() { + void TestIsEnabled() { assertTrue(details.isEnabled()); } } diff --git a/src/test/java/org/jenkinsci/plugins/oic/PluginTest.java b/src/test/java/org/jenkinsci/plugins/oic/PluginTest.java index 2b502218..7069bd88 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/PluginTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/PluginTest.java @@ -1,8 +1,6 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.common.ConsoleNotifier; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import com.google.api.client.auth.openidconnect.IdToken; import com.google.api.client.json.gson.GsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; @@ -46,18 +44,17 @@ import jenkins.model.Jenkins; import jenkins.security.ApiTokenProperty; import jenkins.security.LastGrantedAuthoritiesProperty; -import org.hamcrest.MatcherAssert; import org.htmlunit.CookieManager; import org.htmlunit.html.HtmlPage; import org.htmlunit.util.Cookie; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.DisableOnDebug; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.Url; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; import org.kohsuke.stapler.Stapler; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -67,7 +64,6 @@ import static com.github.tomakehurst.wiremock.client.WireMock.absent; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.matching; @@ -75,7 +71,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static com.google.gson.JsonParser.parseString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -84,13 +80,13 @@ import static org.jenkinsci.plugins.oic.TestRealm.EMAIL_FIELD; import static org.jenkinsci.plugins.oic.TestRealm.FULL_NAME_FIELD; import static org.jenkinsci.plugins.oic.TestRealm.GROUPS_FIELD; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * goes through a login scenario, the openid provider is mocked and always @@ -99,7 +95,8 @@ * interaction works and if the plugin code works. */ @Url("https://jenkins.io/blog/2018/01/13/jep-200/") -public class PluginTest { +@WithJenkins +class PluginTest { private static final String TEST_USER_USERNAME = "testUser"; private static final String TEST_USER_EMAIL_ADDRESS = "test@jenkins.oic"; private static final String TEST_USER_FULL_NAME = "Oic Test User"; @@ -108,31 +105,25 @@ public class PluginTest { private static final List> TEST_USER_GROUPS_MAP = List.of(Map.of("id", "id1", "name", "group1"), Map.of("id", "id2", "name", "group2")); - @Rule - public WireMockRule wireMockRule = new WireMockRule( - new WireMockConfiguration() - .dynamicPort() - .dynamicHttpsPort() - .notifier(new ConsoleNotifier(new DisableOnDebug(null).isDebugging())), - true); - - @Rule - public JenkinsRule jenkinsRule = new JenkinsRule(); + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort().dynamicHttpsPort()) + .build(); + private JenkinsRule jenkinsRule; private JenkinsRule.WebClient webClient; private Jenkins jenkins; - @Before - public void setUp() { + @BeforeEach + void setUp(JenkinsRule jenkinsRule) { + this.jenkinsRule = jenkinsRule; jenkins = jenkinsRule.getInstance(); webClient = jenkinsRule.createWebClient(); - if (new DisableOnDebug(null).isDebugging()) { - webClient.getOptions().setTimeout(0); - } } @Test - public void testLoginWithDefaults() throws Exception { + void testLoginWithDefaults() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); configureTestRealm(sc -> {}); @@ -142,10 +133,10 @@ public void testLoginWithDefaults() throws Exception { assertTestUserEmail(user); assertTestUserIsMemberOfTestGroups(user); - verify(getRequestedFor(urlPathEqualTo("/authorization")) + wireMock.verify(getRequestedFor(urlPathEqualTo("/authorization")) .withQueryParam("scope", equalTo("openid email")) .withQueryParam("nonce", matching(".+"))); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(notMatching(".*&scope=.*"))); + wireMock.verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(notMatching(".*&scope=.*"))); webClient.executeOnServer(() -> { HttpSession session = Stapler.getCurrentRequest2().getSession(); assertNotNull(((OicSecurityRealm) Jenkins.get().getSecurityRealm()).getStateAttribute(session)); @@ -154,20 +145,20 @@ public void testLoginWithDefaults() throws Exception { } @Test - public void testLoginWithDefaultsUntrustedTLSFails() throws Exception { + void testLoginWithDefaultsUntrustedTLSFails() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); - TestRealm.Builder builder = new TestRealm.Builder(wireMockRule, true).WithMinimalDefaults(); + TestRealm.Builder builder = new TestRealm.Builder(wireMock, true).WithMinimalDefaults(); jenkins.setSecurityRealm(builder.build()); - assertThrows(SSLException.class, () -> browseLoginPage()); + assertThrows(SSLException.class, this::browseLoginPage); } @Test - public void testLoginWithDefaultsUntrustedTLSPassesWhenTLSChecksDisabled() throws Exception { + void testLoginWithDefaultsUntrustedTLSPassesWhenTLSChecksDisabled() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); TestRealm.Builder builder = - new TestRealm.Builder(wireMockRule, true).WithMinimalDefaults().WithDisableSslVerification(true); + new TestRealm.Builder(wireMock, true).WithMinimalDefaults().WithDisableSslVerification(true); jenkins.setSecurityRealm(builder.build()); // webclient talks to the OP via SSL so we need to disable Webclients TLS validation also webClient.getOptions().setUseInsecureSSL(true); @@ -179,7 +170,7 @@ public void testLoginWithDefaultsUntrustedTLSPassesWhenTLSChecksDisabled() throw @Test @Issue("SECURITY-3473") - public void testSessionRefresh() throws Exception { + void testSessionRefresh() throws Exception { String cookieName = "JSESSIONID"; String cookieHost = jenkinsRule.getURL().getHost(); // Dev memo: jenkinsRule.getURL().getPath() has a trailing / which breaks Cookie#equals @@ -195,11 +186,11 @@ public void testSessionRefresh() throws Exception { // Not yet logged in assertAnonymous(); assertEquals( - "No session cookie should be present", 0, cookieManager.getCookies().stream() .filter(c -> Objects.equals(c.getName(), cookieName)) - .count()); + .count(), + "No session cookie should be present"); // Set a JSESSIONID cookie value before the first login is attempted. cookieManager.addCookie(jSessionIDCookie); @@ -208,19 +199,19 @@ public void testSessionRefresh() throws Exception { // Multiple JSESSIONID can exist if, for example, the path is different assertEquals( - "Only one session cookie should be present", 1, cookieManager.getCookies().stream() .filter(c -> Objects.equals(c.getName(), cookieName)) - .count()); + .count(), + "Only one session cookie should be present"); String firstLoginSession = cookieManager.getCookie(cookieName).getValue(); - assertNotEquals("The previous session should be replaced with a new one", previousSession, firstLoginSession); + assertNotEquals(previousSession, firstLoginSession, "The previous session should be replaced with a new one"); browseLoginPage(); String secondLoginSession = cookieManager.getCookie(cookieName).getValue(); - assertNotEquals("The session should be renewed when the user log in", firstLoginSession, secondLoginSession); + assertNotEquals(firstLoginSession, secondLoginSession, "The session should be renewed when the user log in"); } private void browseLoginPage() throws IOException, SAXException { @@ -228,7 +219,7 @@ private void browseLoginPage() throws IOException, SAXException { } private void configureTestRealm(@NonNull Consumer consumer) throws Exception { - var securityRealm = new TestRealm(wireMockRule); + var securityRealm = new TestRealm(wireMock); consumer.accept(securityRealm); jenkins.setSecurityRealm(securityRealm); } @@ -239,21 +230,17 @@ private static void assertTestUserIsMemberOfTestGroups(User user) { private static void assertTestUserIsMemberOfGroups(User user, String... testUserGroups) { for (String group : testUserGroups) { - assertTrue( - "User should be part of group " + group, - user.getAuthorities().contains(group)); + assertTrue(user.getAuthorities().contains(group), "User should be part of group " + group); } } private void assertAnonymous() { assertEquals( - "Shouldn't be authenticated", - Jenkins.ANONYMOUS2.getPrincipal(), - getAuthentication().getPrincipal()); + Jenkins.ANONYMOUS2.getPrincipal(), getAuthentication().getPrincipal(), "Shouldn't be authenticated"); } private void mockAuthorizationRedirectsToFinishLogin() { - wireMockRule.stubFor(get(urlPathEqualTo("/authorization")) + wireMock.stubFor(get(urlPathEqualTo("/authorization")) .willReturn(aResponse() .withTransformers("response-template") .withStatus(302) @@ -265,40 +252,42 @@ private void mockAuthorizationRedirectsToFinishLogin() { } @Test - @Ignore("there is no configuration option for this and the spec does not have scopes in a token endpoint") - public void testLoginWithScopesInTokenRequest() throws Exception { + @Disabled("there is no configuration option for this and the spec does not have scopes in a token endpoint") + void testLoginWithScopesInTokenRequest() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); configureTestRealm(sc -> sc.setSendScopesInTokenRequest(true)); browseLoginPage(); - verify(getRequestedFor(urlPathEqualTo("/authorization")).withQueryParam("scope", equalTo("openid email"))); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("&scope=openid+email&"))); + wireMock.verify( + getRequestedFor(urlPathEqualTo("/authorization")).withQueryParam("scope", equalTo("openid email"))); + wireMock.verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("&scope=openid+email&"))); } @Test - public void testLoginWithPkceEnabled() throws Exception { + void testLoginWithPkceEnabled() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); configureTestRealm(sc -> sc.setPkceEnabled(true)); browseLoginPage(); - verify(getRequestedFor(urlPathEqualTo("/authorization")) + wireMock.verify(getRequestedFor(urlPathEqualTo("/authorization")) .withQueryParam("code_challenge_method", equalTo("S256")) .withQueryParam("code_challenge", matching(".+"))); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(matching(".*&code_verifier=[^&]+.*"))); + wireMock.verify( + postRequestedFor(urlPathEqualTo("/token")).withRequestBody(matching(".*&code_verifier=[^&]+.*"))); // check PKCE // - get codeChallenge - final String codeChallenge = findAll(getRequestedFor(urlPathEqualTo("/authorization"))) + final String codeChallenge = wireMock.findAll(getRequestedFor(urlPathEqualTo("/authorization"))) .get(0) .queryParameter("code_challenge") .values() .get(0); // - get verifierCode Matcher m = Pattern.compile(".*&code_verifier=([^&]+).*") - .matcher(findAll(postRequestedFor(urlPathEqualTo("/token"))) + .matcher(wireMock.findAll(postRequestedFor(urlPathEqualTo("/token"))) .get(0) .getBodyAsString()); assertTrue(m.find()); @@ -315,24 +304,24 @@ public void testLoginWithPkceEnabled() throws Exception { } @Test - public void testLoginWithNonceDisabled() throws Exception { + void testLoginWithNonceDisabled() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); configureTestRealm(sc -> sc.setNonceDisabled(true)); browseLoginPage(); - verify(getRequestedFor(urlPathEqualTo("/authorization")).withQueryParam("nonce", absent())); + wireMock.verify(getRequestedFor(urlPathEqualTo("/authorization")).withQueryParam("nonce", absent())); } @Test - public void testLoginUsingUserInfoEndpointWithGroupsMap() throws Exception { + void testLoginUsingUserInfoEndpointWithGroupsMap() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfoWithGroups(TEST_USER_GROUPS_MAP); System.out.println("jsonarray : " + toJson(TEST_USER_GROUPS_MAP)); jenkins.setSecurityRealm(new TestRealm( - wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo", "email", "groups[].name")); + wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo", "email", "groups[].name")); assertAnonymous(); browseLoginPage(); @@ -341,32 +330,29 @@ public void testLoginUsingUserInfoEndpointWithGroupsMap() throws Exception { assertTestUserEmail(user); for (Map group : TEST_USER_GROUPS_MAP) { var groupName = group.get("name"); - assertTrue( - "User should be part of group " + groupName, - user.getAuthorities().contains(groupName)); + assertTrue(user.getAuthorities().contains(groupName), "User should be part of group " + groupName); } } @Test - public void testLoginWithMinimalConfiguration() throws Exception { + void testLoginWithMinimalConfiguration() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, null, null)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, null, null)); assertAnonymous(); browseLoginPage(); var user = assertTestUser(); - assertTrue( - "User should be not be part of any group", user.getAuthorities().isEmpty()); + assertTrue(user.getAuthorities().isEmpty(), "User should be not be part of any group"); } @Test - public void testLoginWithAutoConfiguration() throws Exception { + void testLoginWithAutoConfiguration() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); mockUserInfoWithTestGroups(); configureWellKnown(null, null); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true)); assertAnonymous(); browseLoginPage(); var user = assertTestUser(); @@ -375,15 +361,15 @@ public void testLoginWithAutoConfiguration() throws Exception { } @Test - public void testLoginWithAutoConfiguration_WithNoScope() throws Exception { + void testLoginWithAutoConfiguration_WithNoScope() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithValues(setUpKeyValuesNoGroup()); mockUserInfoWithGroups(null); configureWellKnown(null, null); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true)); assertAnonymous(); configureWellKnown(null, null); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true)); assertAnonymous(); browseLoginPage(); var user = assertTestUser(); @@ -392,61 +378,61 @@ public void testLoginWithAutoConfiguration_WithNoScope() throws Exception { } @Test - public void testConfigurationWithAutoConfiguration_withScopeOverride() throws Exception { + void testConfigurationWithAutoConfiguration_withScopeOverride() throws Exception { configureWellKnown(null, List.of("openid", "profile", "scope1", "scope2", "scope3")); - TestRealm oicsr = new TestRealm.Builder(wireMockRule) + TestRealm oicsr = new TestRealm.Builder(wireMock) .WithMinimalDefaults().WithAutomanualconfigure(true).build(); jenkins.setSecurityRealm(oicsr); assertEquals( - "All scopes of WellKnown should be used", new Scope("openid", "profile", "scope1", "scope2", "scope3"), - oicsr.getServerConfiguration().toProviderMetadata().getScopes()); + oicsr.getServerConfiguration().toProviderMetadata().getScopes(), + "All scopes of WellKnown should be used"); OicServerWellKnownConfiguration serverConfig = (OicServerWellKnownConfiguration) oicsr.getServerConfiguration(); serverConfig.setScopesOverride("openid profile scope2 other"); serverConfig.invalidateProviderMetadata(); // XXX should not be used as it is not a normal code flow, rather the // code should create a new ServerConfig assertEquals( - "scopes should be completely overridden", new Scope("openid", "profile", "scope2", "other"), - serverConfig.toProviderMetadata().getScopes()); + serverConfig.toProviderMetadata().getScopes(), + "scopes should be completely overridden"); serverConfig.invalidateProviderMetadata(); // XXX should not be used as it is not a normal code flow, rather the // code should create a new ServerConfig serverConfig.setScopesOverride(""); assertEquals( - "All scopes of WellKnown should be used", new Scope("openid", "profile", "scope1", "scope2", "scope3"), - serverConfig.toProviderMetadata().getScopes()); + serverConfig.toProviderMetadata().getScopes(), + "All scopes of WellKnown should be used"); } @Test - public void testConfigurationWithAutoConfiguration_withRefreshToken() throws Exception { + void testConfigurationWithAutoConfiguration_withRefreshToken() throws Exception { configureWellKnown(null, null, "authorization_code", "refresh_token"); - TestRealm oicsr = new TestRealm.Builder(wireMockRule) + TestRealm oicsr = new TestRealm.Builder(wireMock) .WithMinimalDefaults().WithAutomanualconfigure(true).build(); jenkins.setSecurityRealm(oicsr); assertTrue( - "Refresh token should be enabled", oicsr.getServerConfiguration() .toProviderMetadata() .getGrantTypes() - .contains(GrantType.REFRESH_TOKEN)); + .contains(GrantType.REFRESH_TOKEN), + "Refresh token should be enabled"); } @Test - public void testRefreshToken_validAndExtendedToken() throws Exception { + void testRefreshToken_validAndExtendedToken() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code", "refresh_token"); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true)); // user groups on first login mockTokenReturnsIdTokenWithGroup(); mockUserInfoWithTestGroups(); browseLoginPage(); var user = assertTestUser(); assertFalse( - "User should not be part of group " + TEST_USER_GROUPS_REFRESHED[2], - user.getAuthorities().contains(TEST_USER_GROUPS_REFRESHED[2])); + user.getAuthorities().contains(TEST_USER_GROUPS_REFRESHED[2]), + "User should not be part of group " + TEST_USER_GROUPS_REFRESHED[2]); // refresh user with different groups mockTokenReturnsIdTokenWithValues(setUpKeyValuesWithGroup(TEST_USER_GROUPS_REFRESHED)); @@ -456,10 +442,11 @@ public void testRefreshToken_validAndExtendedToken() throws Exception { user = assertTestUser(); assertTrue( - "User should be part of group " + TEST_USER_GROUPS_REFRESHED[2], - user.getAuthorities().contains(TEST_USER_GROUPS_REFRESHED[2])); + user.getAuthorities().contains(TEST_USER_GROUPS_REFRESHED[2]), + "User should be part of group " + TEST_USER_GROUPS_REFRESHED[2]); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("grant_type=refresh_token"))); + wireMock.verify( + postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("grant_type=refresh_token"))); } private HttpResponse getPageWithGet(String url) throws IOException, InterruptedException { @@ -510,10 +497,10 @@ private HttpResponse getPageWithGet(String user, String token, String ur } @Test - public void testRefreshTokenAndTokenExpiration_withoutRefreshToken() throws Exception { + void testRefreshTokenAndTokenExpiration_withoutRefreshToken() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code"); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true)); // login mockTokenReturnsIdTokenWithGroup(PluginTest::withoutRefreshToken); mockUserInfoWithTestGroups(); @@ -523,15 +510,16 @@ public void testRefreshTokenAndTokenExpiration_withoutRefreshToken() throws Exce expire(); // use an actual HttpClient to make checking redirects easier HttpResponse rsp = getPageWithGet("/manage"); - MatcherAssert.assertThat("response should have been 302\n" + rsp.body(), rsp.statusCode(), is(302)); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(notMatching(".*grant_type=refresh_token.*"))); + assertThat("response should have been 302\n" + rsp.body(), rsp.statusCode(), is(302)); + wireMock.verify(postRequestedFor(urlPathEqualTo("/token")) + .withRequestBody(notMatching(".*grant_type=refresh_token.*"))); } @Test - public void testRefreshTokenWithTokenExpirationCheckDisabled_withoutRefreshToken() throws Exception { + void testRefreshTokenWithTokenExpirationCheckDisabled_withoutRefreshToken() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code"); - var realm = new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true); + var realm = new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true); realm.setTokenExpirationCheckDisabled(true); jenkins.setSecurityRealm(realm); // login @@ -543,14 +531,15 @@ public void testRefreshTokenWithTokenExpirationCheckDisabled_withoutRefreshToken expire(); webClient.goTo(jenkins.getSearchUrl()); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(notMatching(".*grant_type=refresh_token.*"))); + wireMock.verify(postRequestedFor(urlPathEqualTo("/token")) + .withRequestBody(notMatching(".*grant_type=refresh_token.*"))); } @Test - public void testRefreshTokenWithTokenExpirationCheckDisabled_expiredRefreshToken() throws Exception { + void testRefreshTokenWithTokenExpirationCheckDisabled_expiredRefreshToken() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code", "refresh_token"); - TestRealm testRealm = new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true); + TestRealm testRealm = new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true); testRealm.setTokenExpirationCheckDisabled(true); jenkins.setSecurityRealm(testRealm); // login @@ -559,7 +548,7 @@ public void testRefreshTokenWithTokenExpirationCheckDisabled_expiredRefreshToken browseLoginPage(); assertTestUser(); - wireMockRule.stubFor(post(urlPathEqualTo("/token")) + wireMock.stubFor(post(urlPathEqualTo("/token")) .willReturn(aResponse() .withStatus(400) .withHeader("Content-Type", "application/json") @@ -567,14 +556,15 @@ public void testRefreshTokenWithTokenExpirationCheckDisabled_expiredRefreshToken expire(); webClient.goTo(jenkins.getSearchUrl(), ""); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("grant_type=refresh_token"))); + wireMock.verify( + postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("grant_type=refresh_token"))); } @Test - public void testRefreshTokenAndTokenExpiration_expiredRefreshToken() throws Exception { + void testRefreshTokenAndTokenExpiration_expiredRefreshToken() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code", "refresh_token"); - TestRealm testRealm = new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true); + TestRealm testRealm = new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true); jenkins.setSecurityRealm(testRealm); // login mockTokenReturnsIdTokenWithGroup(); @@ -582,7 +572,7 @@ public void testRefreshTokenAndTokenExpiration_expiredRefreshToken() throws Exce browseLoginPage(); assertTestUser(); - wireMockRule.stubFor(post(urlPathEqualTo("/token")) + wireMock.stubFor(post(urlPathEqualTo("/token")) .willReturn(aResponse() .withStatus(400) .withHeader("Content-Type", "application/json") @@ -590,14 +580,15 @@ public void testRefreshTokenAndTokenExpiration_expiredRefreshToken() throws Exce expire(); webClient.assertFails(jenkins.getSearchUrl(), 500); - verify(postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("grant_type=refresh_token"))); + wireMock.verify( + postRequestedFor(urlPathEqualTo("/token")).withRequestBody(containing("grant_type=refresh_token"))); } @Test - public void testTokenExpiration_withoutExpiresInValue() throws Exception { + void testTokenExpiration_withoutExpiresInValue() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code", "refresh_token"); - TestRealm testRealm = new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true); + TestRealm testRealm = new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true); jenkins.setSecurityRealm(testRealm); // login mockTokenReturnsIdTokenWithGroup(PluginTest::withoutExpiresIn); @@ -629,36 +620,36 @@ private void expire() throws Exception { } @Test - public void testreadResolve_withNulls() throws Exception { + void testreadResolve_withNulls() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithValues(setUpKeyValuesWithGroup()); mockUserInfoWithTestGroups(); configureWellKnown(null, null); - TestRealm realm = new TestRealm(wireMockRule, null, null, null, true); + TestRealm realm = new TestRealm(wireMock, null, null, null, true); jenkins.setSecurityRealm(realm); assertEquals(realm, realm.readResolve()); } @Test - public void testreadResolve_withNonNulls() throws Exception { + void testreadResolve_withNonNulls() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); mockUserInfoWithTestGroups(); configureWellKnown("http://localhost/endSession", null); - TestRealm realm = new TestRealm(wireMockRule, null, null, null, true); + TestRealm realm = new TestRealm(wireMock, null, null, null, true); jenkins.setSecurityRealm(realm); assertEquals(realm, realm.readResolve()); } @Test - public void testLoginUsingUserInfoEndpoint() throws Exception { + void testLoginUsingUserInfoEndpoint() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfoWithTestGroups(); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo")); + jenkins.setSecurityRealm(new TestRealm(wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo")); assertAnonymous(); browseLoginPage(); var user = assertTestUser(); @@ -667,13 +658,13 @@ public void testLoginUsingUserInfoEndpoint() throws Exception { } @Test - public void testLoginUsingUserInfoWithJWT() throws Exception { + void testLoginUsingUserInfoWithJWT() throws Exception { KeyPair keyPair = createKeyPair(); mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfoJwtWithTestGroups(keyPair, "group1"); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo")); + jenkins.setSecurityRealm(new TestRealm(wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo")); assertAnonymous(); @@ -685,10 +676,10 @@ public void testLoginUsingUserInfoWithJWT() throws Exception { } @Test - public void testLoginWithJWTSignature() throws Exception { + void testLoginWithJWTSignature() throws Exception { KeyPair keyPair = createKeyPair(); - wireMockRule.stubFor(get(urlPathEqualTo("/jwks")) + wireMock.stubFor(get(urlPathEqualTo("/jwks")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{\"keys\":[{" + encodePublicKey(keyPair) + ",\"use\":\"sig\",\"kid\":\"jwks_key_id\"" @@ -697,9 +688,9 @@ public void testLoginWithJWTSignature() throws Exception { mockTokenReturnsIdTokenWithoutValues(keyPair); mockUserInfoJwtWithTestGroups(keyPair, TEST_USER_GROUPS); - jenkins.setSecurityRealm(new TestRealm.Builder(wireMockRule) - .WithUserInfoServerUrl("http://localhost:" + wireMockRule.port() + "/userinfo") - .WithJwksServerUrl("http://localhost:" + wireMockRule.port() + "/jwks") + jenkins.setSecurityRealm(new TestRealm.Builder(wireMock) + .WithUserInfoServerUrl("http://localhost:" + wireMock.getPort() + "/userinfo") + .WithJwksServerUrl("http://localhost:" + wireMock.getPort() + "/jwks") .WithDisableTokenValidation(false) .build()); @@ -708,15 +699,15 @@ public void testLoginWithJWTSignature() throws Exception { browseLoginPage(); Authentication authentication = getAuthentication(); - assertEquals("Should be logged-in as " + TEST_USER_USERNAME, TEST_USER_USERNAME, authentication.getPrincipal()); + assertEquals(TEST_USER_USERNAME, authentication.getPrincipal(), "Should be logged-in as " + TEST_USER_USERNAME); } @Test - @Ignore("never enabled, fails because of https://github.com/jenkinsci/oic-auth-plugin/pull/308") - public void testLoginWithWrongJWTSignature() throws Exception { + @Disabled("never enabled, fails because of https://github.com/jenkinsci/oic-auth-plugin/pull/308") + void testLoginWithWrongJWTSignature() throws Exception { KeyPair keyPair = createKeyPair(); - wireMockRule.stubFor(get(urlPathEqualTo("/jwks")) + wireMock.stubFor(get(urlPathEqualTo("/jwks")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody("{\"keys\":[{" + encodePublicKey(keyPair) @@ -724,9 +715,9 @@ public void testLoginWithWrongJWTSignature() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(keyPair); mockUserInfoJwtWithTestGroups(keyPair, TEST_USER_GROUPS); - TestRealm testRealm = new TestRealm.Builder(wireMockRule) - .WithUserInfoServerUrl("http://localhost:" + wireMockRule.port() + "/userinfo") - .WithJwksServerUrl("http://localhost:" + wireMockRule.port() + "/jwks") + TestRealm testRealm = new TestRealm.Builder(wireMock) + .WithUserInfoServerUrl("http://localhost:" + wireMock.getPort() + "/userinfo") + .WithJwksServerUrl("http://localhost:" + wireMock.getPort() + "/jwks") .build(); jenkins.setSecurityRealm(testRealm); assertAnonymous(); @@ -735,62 +726,62 @@ public void testLoginWithWrongJWTSignature() throws Exception { testRealm.setDisableTokenVerification(true); browseLoginPage(); Authentication authentication = getAuthentication(); - assertEquals("Should be logged-in as " + TEST_USER_USERNAME, TEST_USER_USERNAME, authentication.getPrincipal()); + assertEquals(TEST_USER_USERNAME, authentication.getPrincipal(), "Should be logged-in as " + TEST_USER_USERNAME); } @Test - public void testShouldLogUserWithoutGroupsWhenUserGroupIsMissing() throws Exception { + void testShouldLogUserWithoutGroupsWhenUserGroupIsMissing() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfoWithGroups(null); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo")); + jenkins.setSecurityRealm(new TestRealm(wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo")); assertAnonymous(); browseLoginPage(); User user = toUser(getAuthentication()); - assertTrue("User shouldn't be part of any group", user.getAuthorities().isEmpty()); + assertTrue(user.getAuthorities().isEmpty(), "User shouldn't be part of any group"); } @Test - public void testShouldLogUserWithoutGroupsWhenUserGroupIsNull() throws Exception { + void testShouldLogUserWithoutGroupsWhenUserGroupIsNull() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfoWithGroups(JsonNull.INSTANCE); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo")); + jenkins.setSecurityRealm(new TestRealm(wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo")); assertAnonymous(); browseLoginPage(); User user = toUser(getAuthentication()); - assertTrue("User shouldn't be part of any group", user.getAuthorities().isEmpty()); + assertTrue(user.getAuthorities().isEmpty(), "User shouldn't be part of any group"); } @Test - public void testShouldLogUserWithoutGroupsWhenUserGroupIsNotAStringList() throws Exception { + void testShouldLogUserWithoutGroupsWhenUserGroupIsNotAStringList() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfoWithGroups(Map.of("not", "a group")); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo")); + jenkins.setSecurityRealm(new TestRealm(wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo")); assertAnonymous(); browseLoginPage(); User user = toUser(getAuthentication()); - assertTrue("User shouldn't be part of any group", user.getAuthorities().isEmpty()); + assertTrue(user.getAuthorities().isEmpty(), "User shouldn't be part of any group"); } @Test - public void testNestedFieldLookup() throws Exception { + void testNestedFieldLookup() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithValues(setUpKeyValuesNested()); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, "nested.email", "nested.groups")); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, "nested.email", "nested.groups")); assertAnonymous(); browseLoginPage(); var user = assertTestUser(); @@ -799,7 +790,7 @@ public void testNestedFieldLookup() throws Exception { } @Test - public void testNestedFieldLookupFromUserInfoEndpoint() throws Exception { + void testNestedFieldLookupFromUserInfoEndpoint() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfo(Map.of( @@ -813,10 +804,7 @@ public void testNestedFieldLookupFromUserInfoEndpoint() throws Exception { "")); jenkins.setSecurityRealm(new TestRealm( - wireMockRule, - "http://localhost:" + wireMockRule.port() + "/userinfo", - "nested.email", - "nested.groups")); + wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo", "nested.email", "nested.groups")); assertAnonymous(); @@ -829,48 +817,48 @@ public void testNestedFieldLookupFromUserInfoEndpoint() throws Exception { private static void assertTestUserEmail(User user) { assertEquals( - "Email should be " + TEST_USER_EMAIL_ADDRESS, TEST_USER_EMAIL_ADDRESS, - user.getProperty(Mailer.UserProperty.class).getAddress()); + user.getProperty(Mailer.UserProperty.class).getAddress(), + "Email should be " + TEST_USER_EMAIL_ADDRESS); } private @NonNull User assertTestUser() { Authentication authentication = getAuthentication(); - assertEquals("Should be logged-in as " + TEST_USER_USERNAME, TEST_USER_USERNAME, authentication.getPrincipal()); + assertEquals(TEST_USER_USERNAME, authentication.getPrincipal(), "Should be logged-in as " + TEST_USER_USERNAME); User user = toUser(authentication); - assertEquals("Full name should be " + TEST_USER_FULL_NAME, TEST_USER_FULL_NAME, user.getFullName()); + assertEquals(TEST_USER_FULL_NAME, user.getFullName(), "Full name should be " + TEST_USER_FULL_NAME); return user; } @Test - public void testFieldLookupFromIdTokenWhenNotInUserInfoEndpoint() throws Exception { + void testFieldLookupFromIdTokenWhenNotInUserInfoEndpoint() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithValues(setUpKeyValuesWithGroupAndSub()); mockUserInfo(Map.of("sub", "", FULL_NAME_FIELD, JsonNull.INSTANCE, GROUPS_FIELD, TEST_USER_GROUPS)); - jenkins.setSecurityRealm(new TestRealm( - wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo", "email", "groups")); + jenkins.setSecurityRealm( + new TestRealm(wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo", "email", "groups")); browseLoginPage(); Authentication authentication = getAuthentication(); assertEquals( - "Should read field (ex:username) from IdToken when empty in userInfo", TEST_USER_USERNAME, - authentication.getPrincipal()); + authentication.getPrincipal(), + "Should read field (ex:username) from IdToken when empty in userInfo"); User user = toUser(authentication); assertEquals( - "Should read field (ex:full name) from IdToken when null in userInfo", TEST_USER_FULL_NAME, - user.getFullName()); + user.getFullName(), + "Should read field (ex:full name) from IdToken when null in userInfo"); assertEquals( - "Should read field (ex:email) from IdToken when not in userInfo", TEST_USER_EMAIL_ADDRESS, - user.getProperty(Mailer.UserProperty.class).getAddress()); + user.getProperty(Mailer.UserProperty.class).getAddress(), + "Should read field (ex:email) from IdToken when not in userInfo"); } @Test - public void testGroupListFromStringInfoEndpoint() throws Exception { + void testGroupListFromStringInfoEndpoint() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithoutValues(); mockUserInfo(Map.of( @@ -882,10 +870,7 @@ public void testGroupListFromStringInfoEndpoint() throws Exception { Map.of(EMAIL_FIELD, TEST_USER_EMAIL_ADDRESS, GROUPS_FIELD, TEST_USER_GROUPS))); jenkins.setSecurityRealm(new TestRealm( - wireMockRule, - "http://localhost:" + wireMockRule.port() + "/userinfo", - "nested.email", - "nested.groups")); + wireMock, "http://localhost:" + wireMock.getPort() + "/userinfo", "nested.email", "nested.groups")); assertAnonymous(); @@ -894,16 +879,16 @@ public void testGroupListFromStringInfoEndpoint() throws Exception { var user = assertTestUser(); assertTestUserEmail(user); assertTestUserIsMemberOfTestGroups(user); - assertEquals("User should be in 2 groups", 2, user.getAuthorities().size()); + assertEquals(2, user.getAuthorities().size(), "User should be in 2 groups"); } @Test - public void testLastGrantedAuthoritiesProperty() throws Exception { + void testLastGrantedAuthoritiesProperty() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithValues(setUpKeyValuesWithGroup()); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, false)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, false)); assertAnonymous(); @@ -912,26 +897,23 @@ public void testLastGrantedAuthoritiesProperty() throws Exception { var user = assertTestUser(); assertTestUserEmail(user); - assertEquals("User should be in 2 groups", 2, user.getAuthorities().size()); + assertEquals(2, user.getAuthorities().size(), "User should be in 2 groups"); LastGrantedAuthoritiesProperty userProperty = user.getProperty(LastGrantedAuthoritiesProperty.class); assertEquals( - "Property should specify 3 groups (2 + 'authenticated')", - 3, - userProperty.getAuthorities2().size()); + 3, userProperty.getAuthorities2().size(), "Property should specify 3 groups (2 + 'authenticated')"); HtmlPage configure = Jenkins.getVersion().isNewerThan(new VersionNumber("2.467")) ? webClient.goTo("me/account/") : webClient.goTo("me/configure"); jenkinsRule.submit(configure.getFormByName("config")); user = User.getById(TEST_USER_USERNAME, false); - assertEquals( - "User should still be in 2 groups", 2, user.getAuthorities().size()); + assertEquals(2, user.getAuthorities().size(), "User should still be in 2 groups"); userProperty = user.getProperty(LastGrantedAuthoritiesProperty.class); assertEquals( - "Property should still specify 3 groups (2 + 'authenticated')", 3, - userProperty.getAuthorities2().size()); + userProperty.getAuthorities2().size(), + "Property should still specify 3 groups (2 + 'authenticated')"); } private void configureWellKnown(@CheckForNull String endSessionUrl, @CheckForNull List scopesSupported) { @@ -946,16 +928,15 @@ private void configureWellKnown( // if present it must minimally be "openid" // Claims with zero elements MUST be omitted from the response. - Map values = new HashMap<>(); - values.putAll(Map.of( + Map values = new HashMap<>(Map.of( "authorization_endpoint", - "http://localhost:" + wireMockRule.port() + "/authorization", + "http://localhost:" + wireMock.getPort() + "/authorization", "token_endpoint", - "http://localhost:" + wireMockRule.port() + "/token", + "http://localhost:" + wireMock.getPort() + "/token", "userinfo_endpoint", - "http://localhost:" + wireMockRule.port() + "/userinfo", + "http://localhost:" + wireMock.getPort() + "/userinfo", "jwks_uri", - "http://localhost:" + wireMockRule.port() + "/jwks", + "http://localhost:" + wireMock.getPort() + "/jwks", "issuer", TestRealm.ISSUER, "subject_types_supported", @@ -970,15 +951,15 @@ private void configureWellKnown( values.put("grant_types_supported", grantTypesSupported); } - wireMockRule.stubFor(get(urlPathEqualTo("/well.known")) + wireMock.stubFor(get(urlPathEqualTo("/well.known")) .willReturn(aResponse() .withHeader("Content-Type", "text/html; charset=utf-8") .withBody(toJson(values)))); } @Test - public void testLogoutShouldBeJenkinsOnlyWhenNoProviderLogoutConfigured() throws Exception { - final TestRealm oicsr = new TestRealm.Builder(wireMockRule).build(); + void testLogoutShouldBeJenkinsOnlyWhenNoProviderLogoutConfigured() throws Exception { + final TestRealm oicsr = new TestRealm.Builder(wireMock).build(); jenkins.setSecurityRealm(oicsr); String[] logoutURL = new String[1]; @@ -990,8 +971,8 @@ public void testLogoutShouldBeJenkinsOnlyWhenNoProviderLogoutConfigured() throws } @Test - public void testLogoutShouldBeProviderURLWhenProviderLogoutConfigured() throws Exception { - final TestRealm oicsr = new TestRealm.Builder(wireMockRule) + void testLogoutShouldBeProviderURLWhenProviderLogoutConfigured() throws Exception { + final TestRealm oicsr = new TestRealm.Builder(wireMock) .WithLogout(Boolean.TRUE, "http://provider/logout").build(); jenkins.setSecurityRealm(oicsr); @@ -1004,9 +985,9 @@ public void testLogoutShouldBeProviderURLWhenProviderLogoutConfigured() throws E } @Test - public void testLogoutShouldBeProviderURLWithRedirectWhenProviderLogoutConfiguredWithPostlogoutRedirect() + void testLogoutShouldBeProviderURLWithRedirectWhenProviderLogoutConfiguredWithPostlogoutRedirect() throws Exception { - final TestRealm oicsr = new TestRealm.Builder(wireMockRule) + final TestRealm oicsr = new TestRealm.Builder(wireMock) .WithLogout(Boolean.TRUE, "http://provider/logout") .WithPostLogoutRedirectUrl("http://see.it/?cat&color=white") .build(); @@ -1066,25 +1047,25 @@ private String createUserInfoJWT(PrivateKey privateKey, String userInfo) throws } @Test - public void testLoginWithMissingIdTokenShouldBeRefused() throws Exception { + void testLoginWithMissingIdTokenShouldBeRefused() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdToken(null); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, null, null)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, null, null)); assertAnonymous(); webClient.assertFails(jenkins.getSecurityRealm().getLoginUrl(), 500); } @Test - public void testLoginWithUnreadableIdTokenShouldBeRefused() throws Exception { + void testLoginWithUnreadableIdTokenShouldBeRefused() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdToken("This is not an IdToken"); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, null, null)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, null, null)); assertAnonymous(); webClient.assertFails(jenkins.getSecurityRealm().getLoginUrl(), 500); } @Test - public void loginWithCheckTokenSuccess() throws Exception { + void loginWithCheckTokenSuccess() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); configureTestRealm(belongsToGroup("group1")); @@ -1094,7 +1075,7 @@ public void loginWithCheckTokenSuccess() throws Exception { } @Test - public void loginWithCheckTokenFailure() throws Exception { + void loginWithCheckTokenFailure() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); configureTestRealm(belongsToGroup("missing-group")); @@ -1106,10 +1087,10 @@ public void loginWithCheckTokenFailure() throws Exception { @Test @Issue("SECURITY-3441") - public void loginWithIncorrectIssuerFails() throws Exception { + void loginWithIncorrectIssuerFails() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); - jenkins.setSecurityRealm(new TestRealm.Builder(wireMockRule) + jenkins.setSecurityRealm(new TestRealm.Builder(wireMock) .WithIssuer("another_issuer").WithDisableTokenValidation(false).build()); assertAnonymous(); webClient.setThrowExceptionOnFailingStatusCode(false); @@ -1119,10 +1100,10 @@ public void loginWithIncorrectIssuerFails() throws Exception { @Test @Issue("SECURITY-3441") - public void loginWithIncorrectAudienceFails() throws Exception { + void loginWithIncorrectAudienceFails() throws Exception { mockAuthorizationRedirectsToFinishLogin(); mockTokenReturnsIdTokenWithGroup(); - jenkins.setSecurityRealm(new TestRealm.Builder(wireMockRule) + jenkins.setSecurityRealm(new TestRealm.Builder(wireMock) .WithClient("another_client_id", "client_secret") .WithDisableTokenValidation(false) .build()); @@ -1133,10 +1114,10 @@ public void loginWithIncorrectAudienceFails() throws Exception { } @Test - public void testAccessUsingJenkinsApiTokens() throws Exception { + void testAccessUsingJenkinsApiTokens() throws Exception { mockAuthorizationRedirectsToFinishLogin(); configureWellKnown(null, null, "authorization_code"); - jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, EMAIL_FIELD, GROUPS_FIELD, true)); + jenkins.setSecurityRealm(new TestRealm(wireMock, null, EMAIL_FIELD, GROUPS_FIELD, true)); // explicitly ensure allowTokenAccessWithoutOicSession is disabled TestRealm testRealm = (TestRealm) jenkins.getSecurityRealm(); testRealm.setAllowTokenAccessWithoutOicSession(false); @@ -1155,9 +1136,9 @@ public void testAccessUsingJenkinsApiTokens() throws Exception { // validate that the token can be used HttpResponse rsp = getPageWithGet(TEST_USER_USERNAME, token, "/whoAmI/api/xml"); - MatcherAssert.assertThat("response should have been 200\n" + rsp.body(), rsp.statusCode(), is(200)); + assertThat("response should have been 200\n" + rsp.body(), rsp.statusCode(), is(200)); - MatcherAssert.assertThat( + assertThat( "response should have been 200\n" + rsp.body(), rsp.body(), containsString("true")); @@ -1168,15 +1149,15 @@ public void testAccessUsingJenkinsApiTokens() throws Exception { // the default behavior expects there to be a valid oic session, so token based // access should now fail (unauthorized) rsp = getPageWithGet(TEST_USER_USERNAME, token, "/whoAmI/api/xml"); - MatcherAssert.assertThat("response should have been 302\n" + rsp.body(), rsp.statusCode(), is(302)); + assertThat("response should have been 302\n" + rsp.body(), rsp.statusCode(), is(302)); // enable "traditional api token access" testRealm.setAllowTokenAccessWithoutOicSession(true); // verify that jenkins api token is now working again rsp = getPageWithGet(TEST_USER_USERNAME, token, "/whoAmI/api/xml"); - MatcherAssert.assertThat("response should have been 200\n" + rsp.body(), rsp.statusCode(), is(200)); - MatcherAssert.assertThat( + assertThat("response should have been 200\n" + rsp.body(), rsp.statusCode(), is(200)); + assertThat( "response should have been 200\n" + rsp.body(), rsp.body(), containsString("true")); @@ -1257,14 +1238,14 @@ private void mockUserInfoWithGroups(@Nullable Object groups) { } private void mockUserInfoJwtWithTestGroups(KeyPair keyPair, Object testUserGroups) throws Exception { - wireMockRule.stubFor(get(urlPathEqualTo("/userinfo")) + wireMock.stubFor(get(urlPathEqualTo("/userinfo")) .willReturn(aResponse() .withHeader("Content-Type", "application/jwt") .withBody(createUserInfoJWT(keyPair.getPrivate(), toJson(getUserInfo(testUserGroups)))))); } private void mockUserInfo(Map userInfo) { - wireMockRule.stubFor(get(urlPathEqualTo("/userinfo")) + wireMock.stubFor(get(urlPathEqualTo("/userinfo")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(toJson(userInfo)))); @@ -1331,7 +1312,7 @@ private void mockTokenReturnsIdToken( if (tokenAcceptors != null) { Arrays.stream(tokenAcceptors).forEach(a -> a.accept(token)); } - wireMockRule.stubFor(post(urlPathEqualTo("/token")) + wireMock.stubFor(post(urlPathEqualTo("/token")) .willReturn(aResponse() .withHeader("Content-Type", "application/json") .withBody(toJson(token)))); diff --git a/src/test/java/org/jenkinsci/plugins/oic/ProxyAwareResourceRetrieverTest.java b/src/test/java/org/jenkinsci/plugins/oic/ProxyAwareResourceRetrieverTest.java index 62354a08..4e5d7dee 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/ProxyAwareResourceRetrieverTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/ProxyAwareResourceRetrieverTest.java @@ -3,45 +3,43 @@ import hudson.ProxyConfiguration; import java.net.HttpURLConnection; import java.net.UnknownHostException; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -public class ProxyAwareResourceRetrieverTest { - - @Rule - public JenkinsRule jr = new JenkinsRule(); +@WithJenkins +class ProxyAwareResourceRetrieverTest { @Test - public void testOpenConnection_WithoutProxy() throws Exception { - jr.jenkins.setProxy(null); + void testOpenConnection_WithoutProxy(JenkinsRule r) throws Exception { + r.jenkins.setProxy(null); ProxyAwareResourceRetriever retreiver = ProxyAwareResourceRetriever.createProxyAwareResourceRetriver(false); - HttpURLConnection conn = retreiver.openHTTPConnection(jr.getURL()); + HttpURLConnection conn = retreiver.openHTTPConnection(r.getURL()); assertNotNull(conn.getContent()); } @Test - public void testOpenConnection_WithProxy() throws Exception { - jr.jenkins.setProxy(new ProxyConfiguration("ignored.invalid", 8000)); + void testOpenConnection_WithProxy(JenkinsRule r) throws Exception { + r.jenkins.setProxy(new ProxyConfiguration("ignored.invalid", 8000)); ProxyAwareResourceRetriever retreiver = ProxyAwareResourceRetriever.createProxyAwareResourceRetriver(false); - HttpURLConnection conn = retreiver.openHTTPConnection(jr.getURL()); + HttpURLConnection conn = retreiver.openHTTPConnection(r.getURL()); // should attempt to connect to the proxy which is ignored.invalid which can not be resolved and hence throw an // UnknownHostException - assertThrows(UnknownHostException.class, () -> conn.getContent()); + assertThrows(UnknownHostException.class, conn::getContent); } @Test - public void testOpenConnection_WithProxyAndExclusion() throws Exception { - jr.jenkins.setProxy(new ProxyConfiguration( - "ignored.invalid", 8000, null, null, jr.getURL().getHost())); + void testOpenConnection_WithProxyAndExclusion(JenkinsRule r) throws Exception { + r.jenkins.setProxy(new ProxyConfiguration( + "ignored.invalid", 8000, null, null, r.getURL().getHost())); ProxyAwareResourceRetriever retreiver = ProxyAwareResourceRetriever.createProxyAwareResourceRetriver(false); - HttpURLConnection conn = retreiver.openHTTPConnection(jr.getURL()); + HttpURLConnection conn = retreiver.openHTTPConnection(r.getURL()); assertNotNull(conn.getContent()); } } diff --git a/src/test/java/org/jenkinsci/plugins/oic/SecurityRealmConfigurationFIPSTest.java b/src/test/java/org/jenkinsci/plugins/oic/SecurityRealmConfigurationFIPSTest.java index 4eb8aae1..e5e4ccb6 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/SecurityRealmConfigurationFIPSTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/SecurityRealmConfigurationFIPSTest.java @@ -1,32 +1,49 @@ package org.jenkinsci.plugins.oic; import hudson.model.Descriptor; -import org.junit.ClassRule; -import org.junit.Test; -import org.jvnet.hudson.test.FlagRule; +import jenkins.security.FIPS140; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class SecurityRealmConfigurationFIPSTest { +class SecurityRealmConfigurationFIPSTest { - @ClassRule - public static FlagRule FIPS_RULE = FlagRule.systemProperty("jenkins.security.FIPS140.COMPLIANCE", "true"); + private static Object fipsProperty; - @Test(expected = Descriptor.FormException.class) - public void escapeHatchThrowsException() throws Exception { - new OicSecurityRealm("clientId", null, null, null, null, null).setEscapeHatchEnabled(true); + @BeforeAll + static void setUp() { + fipsProperty = System.getProperties().setProperty(FIPS140.class.getName() + ".COMPLIANCE", "true"); + } + + @AfterAll + static void tearDown() { + if (fipsProperty != null) { + System.setProperty(FIPS140.class.getName() + ".COMPLIANCE", String.valueOf(fipsProperty)); + } else { + System.clearProperty(FIPS140.class.getName() + ".COMPLIANCE"); + } + } + + @Test + void escapeHatchThrowsException() { + assertThrows( + Descriptor.FormException.class, + () -> new OicSecurityRealm("clientId", null, null, null, null, null).setEscapeHatchEnabled(true)); } @Test - public void escapeHatchToFalse() throws Exception { + void escapeHatchToFalse() throws Exception { OicSecurityRealm oicSecurityRealm = new OicSecurityRealm("clientId", null, null, null, null, null); oicSecurityRealm.setEscapeHatchEnabled(false); assertThat(oicSecurityRealm.isEscapeHatchEnabled(), is(false)); } @Test - public void readresolve() throws Exception { + void readResolve() throws Exception { OicSecurityRealm oicSecurityRealm = new OicSecurityRealm("clientId", null, null, null, null, null); oicSecurityRealm.setEscapeHatchEnabled(false); assertThat(oicSecurityRealm.isEscapeHatchEnabled(), is(false)); diff --git a/src/test/java/org/jenkinsci/plugins/oic/TestRealm.java b/src/test/java/org/jenkinsci/plugins/oic/TestRealm.java index 320edb20..ffa02ec1 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/TestRealm.java +++ b/src/test/java/org/jenkinsci/plugins/oic/TestRealm.java @@ -1,12 +1,13 @@ package org.jenkinsci.plugins.oic; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import hudson.model.Descriptor; import hudson.security.SecurityRealm; import hudson.util.Secret; import io.burt.jmespath.Expression; import java.io.IOException; import java.io.ObjectStreamException; +import java.io.Serial; import java.text.ParseException; import jenkins.model.IdStrategy; import org.kohsuke.stapler.StaplerRequest2; @@ -57,18 +58,18 @@ public static class Builder { public IdStrategy userIdStrategy; public IdStrategy groupIdStrategy; - public Builder(WireMockRule wireMockRule, boolean useTLS) throws IOException { + public Builder(WireMockExtension wireMock, boolean useTLS) throws IOException { this( useTLS - ? "https://localhost:" + wireMockRule.httpsPort() + "/" - : "http://localhost:" + wireMockRule.port() + "/"); + ? "https://localhost:" + wireMock.getHttpsPort() + "/" + : "http://localhost:" + wireMock.getPort() + "/"); } - public Builder(WireMockRule wireMockRule) throws IOException { - this(wireMockRule, false); + public Builder(WireMockExtension wireMock) throws IOException { + this(wireMock, false); } - public Builder(String rootUrl) throws IOException { + public Builder(String rootUrl) { this.wellKnownOpenIDConfigurationUrl = rootUrl + "well.known"; this.tokenServerUrl = rootUrl + "token"; this.authorizationServerUrl = rootUrl + "authorization"; @@ -219,30 +220,31 @@ public TestRealm(Builder builder) throws Exception { super.createProxyAwareResourceRetriver(); } - public TestRealm(WireMockRule wireMockRule, String userInfoServerUrl, String emailFieldName, String groupsFieldName) + public TestRealm( + WireMockExtension wireMock, String userInfoServerUrl, String emailFieldName, String groupsFieldName) throws Exception { - this(new Builder(wireMockRule) + this(new Builder(wireMock) .WithUserInfoServerUrl(userInfoServerUrl) .WithEmailFieldName(emailFieldName) .WithGroupsFieldName(groupsFieldName)); } - public TestRealm(WireMockRule wireMockRule) throws Exception { - this(new Builder(wireMockRule).WithMinimalDefaults()); + public TestRealm(WireMockExtension wireMock) throws Exception { + this(new Builder(wireMock).WithMinimalDefaults()); } - public TestRealm(WireMockRule wireMockRule, String userInfoServerUrl) throws Exception { - this(new Builder(wireMockRule).WithMinimalDefaults().WithUserInfoServerUrl(userInfoServerUrl)); + public TestRealm(WireMockExtension wireMock, String userInfoServerUrl) throws Exception { + this(new Builder(wireMock).WithMinimalDefaults().WithUserInfoServerUrl(userInfoServerUrl)); } public TestRealm( - WireMockRule wireMockRule, + WireMockExtension wireMock, String userInfoServerUrl, String emailFieldName, String groupFieldName, boolean automanualconfigure) throws Exception { - this(new Builder(wireMockRule) + this(new Builder(wireMock) .WithMinimalDefaults() .WithUserInfoServerUrl(userInfoServerUrl) .WithEmailFieldName(emailFieldName) @@ -251,7 +253,7 @@ public TestRealm( } public TestRealm( - WireMockRule wireMockRule, + WireMockExtension wireMock, String userInfoServerUrl, String emailFieldName, String groupFieldName, @@ -261,7 +263,7 @@ public TestRealm( String escapeHatchSecret, String escapeHatchGroup) throws Exception { - this(new Builder(wireMockRule) + this(new Builder(wireMock) .WithMinimalDefaults() .WithUserInfoServerUrl(userInfoServerUrl) .WithEmailFieldName(emailFieldName) @@ -292,13 +294,14 @@ public void doFinishLogin(StaplerRequest2 request, StaplerResponse2 response) th } public String getStringFieldFromJMESPath(Object object, String jmespathField) { - Expression expr = super.compileJMESPath(jmespathField, "test field"); + Expression expr = compileJMESPath(jmespathField, "test field"); if (expr == null) { return null; } return super.getStringField(object, expr); } + @Serial @Override public Object readResolve() throws ObjectStreamException { return super.readResolve(); diff --git a/src/test/java/org/jenkinsci/plugins/oic/monitor/OicStrategyMonitorTest.java b/src/test/java/org/jenkinsci/plugins/oic/monitor/OicStrategyMonitorTest.java index d9693a58..291623cc 100644 --- a/src/test/java/org/jenkinsci/plugins/oic/monitor/OicStrategyMonitorTest.java +++ b/src/test/java/org/jenkinsci/plugins/oic/monitor/OicStrategyMonitorTest.java @@ -1,58 +1,59 @@ package org.jenkinsci.plugins.oic.monitor; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import com.github.tomakehurst.wiremock.junit.WireMockRule; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import jenkins.model.IdStrategy; import jenkins.model.Jenkins; import org.jenkinsci.plugins.oic.TestRealm; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.jvnet.hudson.test.Issue; -import org.jvnet.hudson.test.JenkinsSessionRule; +import org.jvnet.hudson.test.JenkinsRule; +import org.jvnet.hudson.test.junit.jupiter.WithJenkins; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class OicStrategyMonitorTest { +@WithJenkins +class OicStrategyMonitorTest { - @Rule - public JenkinsSessionRule sessions = new JenkinsSessionRule(); - - @Rule - public WireMockRule wireMockRule = new WireMockRule(new WireMockConfiguration().dynamicPort(), true); + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .failOnUnmatchedRequests(true) + .options(wireMockConfig().dynamicPort()) + .build(); @Test @Issue("SECURITY-3461") - public void smokes_caseInsensitive() throws Throwable { - sessions.then(r -> { - TestRealm realm = new TestRealm(wireMockRule); - Jenkins.get().setSecurityRealm(realm); - assertTrue(OicIdStrategyMonitor.get().isActivated()); - }); - sessions.then(r -> { - assertTrue(OicIdStrategyMonitor.get().isActivated()); - TestRealm realm = new TestRealm(new TestRealm.Builder(wireMockRule) - .WithMinimalDefaults() - .WithGroupIdStrategy(IdStrategy.CASE_INSENSITIVE) - .WithUserIdStrategy(IdStrategy.CASE_INSENSITIVE)); - Jenkins.get().setSecurityRealm(realm); - assertFalse(OicIdStrategyMonitor.get().isActivated()); - }); - sessions.then(r -> { - assertFalse(OicIdStrategyMonitor.get().isActivated()); - }); + void smokes_caseInsensitive(JenkinsRule r) throws Throwable { + TestRealm realm = new TestRealm(wireMock); + Jenkins.get().setSecurityRealm(realm); + assertTrue(OicIdStrategyMonitor.get().isActivated()); + + r.restart(); + + assertTrue(OicIdStrategyMonitor.get().isActivated()); + realm = new TestRealm(new TestRealm.Builder(wireMock) + .WithMinimalDefaults() + .WithGroupIdStrategy(IdStrategy.CASE_INSENSITIVE) + .WithUserIdStrategy(IdStrategy.CASE_INSENSITIVE)); + Jenkins.get().setSecurityRealm(realm); + assertFalse(OicIdStrategyMonitor.get().isActivated()); + + r.restart(); + + assertFalse(OicIdStrategyMonitor.get().isActivated()); } @Test @Issue("SECURITY-3461") - public void smokes_noChange() throws Throwable { - sessions.then(r -> { - TestRealm realm = new TestRealm(wireMockRule); - Jenkins.get().setSecurityRealm(realm); - assertTrue(OicIdStrategyMonitor.get().isActivated()); - }); - sessions.then(r -> { - assertTrue(OicIdStrategyMonitor.get().isActivated()); - }); + void smokes_noChange(JenkinsRule r) throws Throwable { + TestRealm realm = new TestRealm(wireMock); + Jenkins.get().setSecurityRealm(realm); + assertTrue(OicIdStrategyMonitor.get().isActivated()); + + r.restart(); + + assertTrue(OicIdStrategyMonitor.get().isActivated()); } } diff --git a/src/test/resources/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest/failsOnMigrationTest/config.xml b/src/test/resources/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest/failsOnMigrationTest/config.xml deleted file mode 100644 index 74aebde6..00000000 --- a/src/test/resources/org/jenkinsci/plugins/oic/OicSecurityRealmFipsTest/failsOnMigrationTest/config.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - 2.426.3 - 2 - NORMAL - true - - client-id - {AQAAABAAAAAQ6eIZw98uUCRkQ7ug3nSTzQ4EKjZWLpSQFIxRg9AMWNo=} - sub - false - false - false - {AQAAABAAAABAPfWEOWZptuocLQqIjwfXTQ6Ky/3yq4CIWvdUYhH4jX1CuCzrFvr2ICIiBIIpp79McMBCTHq9QhVjfgbPN9XPEbjsFiWihgKHZYF+3+wz3kM=} - - https://example.test - - false - false - false - true - false - false - false - 0 - - \ No newline at end of file