Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LiveTest, & fix for CCE in SamlSecurityRealm.doFinishLogin #93

Merged
merged 17 commits into from
Mar 12, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ under the License.
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>4.3</version>
<version>4.16</version>
</parent>

<artifactId>saml</artifactId>
Expand All @@ -44,9 +44,9 @@ under the License.
<properties>
<revision>2.0.1</revision>
<changelist>-SNAPSHOT</changelist>
<jenkins.version>2.266</jenkins.version>
<jenkins.version>2.277</jenkins.version>
<java.level>8</java.level>
<jcasc.version>1.35</jcasc.version>
<jenkins-test-harness.version>1492.v843c23c9d568</jenkins-test-harness.version> <!-- TODO https://github.com/jenkinsci/jenkins-test-harness/pull/281 -->
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using RealJenkinsRule here because

thread.setContextClassLoader(InitializationService.class.getClassLoader());
or
<exclusions>
make it less than obvious that plain JenkinsRule would simulate plugin operation as accurately as ATH.

</properties>

<licenses>
Expand Down Expand Up @@ -187,8 +187,6 @@ under the License.
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>mailer</artifactId>
<version>1.29</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
Expand All @@ -210,22 +208,38 @@ under the License.
<dependency>
<groupId>io.jenkins</groupId>
<artifactId>configuration-as-code</artifactId>
<version>${jcasc.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jenkins.configuration-as-code</groupId>
<artifactId>test-harness</artifactId>
<version>${jcasc.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.15.2</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.jenkins.tools.bom</groupId>
<artifactId>bom-2.249.x</artifactId>
<version>17</version>
<artifactId>bom-2.277.x</artifactId>
<version>26</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Expand All @@ -239,12 +253,6 @@ under the License.
<artifactId>xmlsec</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.pac4j</groupId>
<artifactId>pac4j-saml</artifactId>
<!-- versions 4.x.x require JDK 11 -->
<version>3.9.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
Expand Down
208 changes: 208 additions & 0 deletions src/test/java/org/jenkinsci/plugins/saml/LiveTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
/*
* Copyright 2021 CloudBees, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.jenkinsci.plugins.saml;

import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import hudson.util.Secret;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import jenkins.model.Jenkins;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.jvnet.hudson.test.RealJenkinsRule;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.MountableFile;

public class LiveTest {

@Rule public RealJenkinsRule rr = new RealJenkinsRule();

@SuppressWarnings("rawtypes")
private GenericContainer samlContainer = new GenericContainer("kristophjunge/test-saml-idp:1.14.15").withExposedPorts(80);

@After public void stop() {
samlContainer.stop();
}

public static final String SAML2_REDIRECT_BINDING_URI = "HTTP-Redirect";
public static final String SAML2_POST_BINDING_URI = "HTTP-POST";

private static final String SERVICE_PROVIDER_ID = "jenkins-dev";

@Test
public void authenticationOK() throws Throwable {
startSimpleSAML(rr.getUrl().toString());
String idpMetadata = readIdPMetadataFromURL();

rr.then(new AuthenticationOK(idpMetadata));
}
private static class AuthenticationOK implements RealJenkinsRule.Step {
private final String idpMetadata;
AuthenticationOK(String idpMetadata) {
this.idpMetadata = idpMetadata;
}
@Override
public void run(JenkinsRule r) throws Throwable {
// Authentication
SamlSecurityRealm realm = configureBasicSettings(new IdpMetadataConfiguration(idpMetadata), new SamlAdvancedConfiguration(false, null, SERVICE_PROVIDER_ID, null, /* TODO maximumSessionLifetime unused */null));
Jenkins.XSTREAM2.toXMLUTF8(realm, System.out);
System.out.println();
r.jenkins.setSecurityRealm(realm);

configureAuthorization();

makeLoginWithUser1(r);
}
}

/*
@Test
public void authenticationOKFromURL() throws IOException, InterruptedException {
jenkins.open(); // navigate to root
String rootUrl = jenkins.getCurrentUrl();
SAMLContainer samlServer = startSimpleSAML(rootUrl);

GlobalSecurityConfig sc = new GlobalSecurityConfig(jenkins);
sc.open();

// Authentication
SamlSecurityRealm realm = configureBasicSettings(sc);
realm.setUrl(createIdPMetadataURL(samlServer));

configureEncrytion(realm);
configureAuthorization(sc);

waitFor().withTimeout(10, TimeUnit.SECONDS).until(() -> hasContent("Enter your username and password")); // SAML service login page

// SAML server login
makeLoginWithUser1();
}

@Test
public void authenticationOKPostBinding() throws IOException, InterruptedException {
jenkins.open(); // navigate to root
String rootUrl = jenkins.getCurrentUrl();
SAMLContainer samlServer = startSimpleSAML(rootUrl);

GlobalSecurityConfig sc = new GlobalSecurityConfig(jenkins);
sc.open();

// Authentication
SamlSecurityRealm realm = configureBasicSettings(sc);
String idpMetadata = readIdPMetadataFromURL(samlServer);
realm.setXml(idpMetadata);
realm.setBinding(SAML2_POST_BINDING_URI);
configureEncrytion(realm);
configureAuthorization(sc);

waitFor().withTimeout(10, TimeUnit.SECONDS).until(() -> hasContent("Enter your username and password")); // SAML service login page

// SAML server login
makeLoginWithUser1();
}

@Test
public void authenticationFail() throws IOException, InterruptedException {
jenkins.open(); // navigate to root
String rootUrl = jenkins.getCurrentUrl();
SAMLContainer samlServer = startSimpleSAML(rootUrl);

GlobalSecurityConfig sc = new GlobalSecurityConfig(jenkins);
sc.open();

// Authentication
SamlSecurityRealm realm = configureBasicSettings(sc);
String idpMetadata = readIdPMetadataFromURL(samlServer);
realm.setXml(idpMetadata);

configureEncrytion(realm);
configureAuthorization(sc);

waitFor().withTimeout(10, TimeUnit.SECONDS).until(() -> hasContent("Enter your username and password")); // SAML service login page

// SAML server login
find(by.id("username")).sendKeys("user1");
find(by.id("password")).sendKeys("WrOnGpAsSwOrD");
find(by.button("Login")).click();

waitFor().withTimeout(5, TimeUnit.SECONDS).until(() -> hasContent("Either no user with the given username could be found, or the password you gave was wrong").matchesSafely(driver)); // wait for the login to propagate
assertThat(jenkins.getCurrentUrl(), containsString("simplesaml/module.php/core/loginuserpass.php"));
}
*/

private String readIdPMetadataFromURL() throws IOException {
// get saml metadata from IdP
URL metadata = new URL(createIdPMetadataURL());
URLConnection connection = metadata.openConnection();
return IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8);
}

private String createIdPMetadataURL() {
return "http://" + samlContainer.getHost() + ":" + samlContainer.getFirstMappedPort() + "/simplesaml/saml2/idp/metadata.php";
}

private static void configureAuthorization() {
Jenkins.get().setAuthorizationStrategy(new MockAuthorizationStrategy().
grant(Jenkins.ADMINISTER).everywhere().to("group1").
grant(Jenkins.READ).everywhere().to("group2"));
}

private static SamlSecurityRealm configureBasicSettings(IdpMetadataConfiguration idpMetadataConfiguration, SamlAdvancedConfiguration advancedConfiguration) throws IOException {
// TODO use @DataBoundSetter wherever possible and load defaults from DescriptorImpl
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Would likely also be better for CasC: should be able to omit default values of attributes.)

File samlKey = new File(Jenkins.get().getRootDir(), "saml-key.jks");
FileUtils.copyURLToFile(LiveTest.class.getResource("LiveTest/saml-key.jks"), samlKey);
SamlEncryptionData samlEncryptionData = new SamlEncryptionData(samlKey.getAbsolutePath(), Secret.fromString("changeit"), Secret.fromString("changeit"), null, false);
return new SamlSecurityRealm(idpMetadataConfiguration, "displayName", "eduPersonAffiliation", 86400, "uid", "email", null, advancedConfiguration, samlEncryptionData, "none", SAML2_REDIRECT_BINDING_URI, Collections.emptyList());
}

private void startSimpleSAML(String rootUrl) throws IOException, InterruptedException {
samlContainer.
withEnv("SIMPLESAMLPHP_SP_ENTITY_ID", SERVICE_PROVIDER_ID).
withEnv("SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE", rootUrl + "securityRealm/finishLogin"). // login back URL
withEnv("SIMPLESAMLPHP_SP_SINGLE_LOGOUT_SERVICE", rootUrl + "logout"); // unused
samlContainer.start();
samlContainer.copyFileToContainer(MountableFile.forClasspathResource("org/jenkinsci/plugins/saml/LiveTest/users.php"), "/var/www/simplesamlphp/config/authsources.php"); // users info
samlContainer.copyFileToContainer(MountableFile.forClasspathResource("org/jenkinsci/plugins/saml/LiveTest/config.php"), "/var/www/simplesamlphp/config/config.php"); // config info,
samlContainer.copyFileToContainer(MountableFile.forClasspathResource("org/jenkinsci/plugins/saml/LiveTest/saml20-idp-hosted.php"), "/var/www/simplesamlphp/metadata/saml20-idp-hosted.php"); //IdP advanced configuration
}

private static void makeLoginWithUser1(JenkinsRule r) throws Exception {
// TODO commenceLogin fails with: SAMLException: Identity provider has no single sign on service available for the selected profileHTTP-Redirect
jglick marked this conversation as resolved.
Show resolved Hide resolved
// https://github.com/jenkinsci/saml-plugin/blob/master/doc/TROUBLESHOOTING.md#samlexception-identity-provider-has-no-single-sign-on-service-available-for-the-selected
HtmlPage login = r.createWebClient().goTo("");
assertThat(login.getWebResponse().getContentAsString(), containsString("Enter your username and password")); // SAML service login page
((HtmlTextInput) login.getElementById("username")).setText("user1");
((HtmlTextInput) login.getElementById("password")).setText("user1pass");
HtmlPage dashboard = ((HtmlButton) login.getElementByName("Login")).click();
assertThat(dashboard.getWebResponse().getContentAsString(), allOf(containsString("User 1"), containsString("Manage Jenkins")));
}

}
Loading