Skip to content

Commit

Permalink
Switch from file upload to user entry
Browse files Browse the repository at this point in the history
As PEMs are not binary files but tet encoding it makes more sense to
have users enter them.

Additionally feedback is that user normally manage the certificate chain
and keys separately
  • Loading branch information
jtnord committed Jul 5, 2024
1 parent 462e240 commit 44569cb
Show file tree
Hide file tree
Showing 11 changed files with 427 additions and 214 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<?jelly escape-by-default='true'?>
<!--
~ The MIT License
~
~ Copyright (c) 2024, CloudBees, Inc.
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in
~ all copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
~ THE SOFTWARE.
-->

<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
<f:entry title="Certificates" field="certChain">
<f:textarea />
</f:entry>
<f:entry title="Private key" field="privateKey">
<f:textarea />
</f:entry>
</j:jelly>
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!--
# The MIT License
#
# Copyright (c) 2024, CloudBees
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-->

<div>
A certificate chain containing one or more PEM encoded certificates.
The certificates must be in order such that each one directly certifies the preceding one.
The certificate, for which the private key will be entered below must appear first.
<p>The entry should look something like the following:</p>
<pre>
-----BEGIN CERTIFICATE-----
Base64 encoded contents
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
Base64 encoded contents
-----END CERTIFICATE----</pre>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<!--
# The MIT License
#
# Copyright (c) 2024, CloudBees
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-->

<div>
A single PEM encoded private key that is the key for the primary certificate entered above.
<p>The entry should look something like the following:</p>
<pre>
-----BEGIN PRIVATE KEY-----
Base64 encoded contents
-----END PRIVATE KEY----- </pre>
</div>

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@
uploadedCertFileInput.onchange = fileOnChange.bind(uploadedCertFileInput);
}
function fileOnChange() {
// only trigger validation if the PKCS12 upload is selected
var e = document.getElementById("${fileId}");
if (e.closest(".form-container").className.indexOf("-hidden") != -1) {
return
}
try { // inspired by https://stackoverflow.com/a/754398
var uploadedCertFileInputFile = uploadedCertFileInput.files[0];
var reader = new FileReader();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
</j:choose>
</f:entry>
<f:entry title="${%Password}" field="password">
<f:password value="${instance==null || instance.passwordEmpty ? '' : instance.password}"/>
<f:password value="${instance==null || instance.passwordEmpty ? '' : instance.password}" />
</f:entry>
<st:include page="id-and-description" class="${descriptor.clazz}"/>
</j:jelly>
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,7 @@ CertificateCredentialsImpl.LoadKeyFailedQueryEmptyPassword=Could retrieve key "{
CertificateCredentialsImpl.LoadKeystoreFailed=Could not load keystore
CertificateCredentialsImpl.NoCertificateUploaded=No certificate uploaded
CertificateCredentialsImpl.UploadedKeyStoreSourceDisplayName=Upload PKCS#12 certificate and key
CertificateCredentialsImpl.PEMUploadedKeyStoreSourceDisplayName=Upload PEM encoded certificate and key

CertificateCredentialsImpl.PEMEntryKeyStoreSourceDisplayName=PEM encoded certificate and key
CertificateCredentialsImpl.PEMNoCertificates=No certificates where provided
CertificateCredentialsImpl.PEMNoKey=No key was provided
CertificateCredentialsImpl.PEMNoPassword=No password was provided
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@
import org.htmlunit.WebRequest;
import org.htmlunit.html.DomNode;
import org.htmlunit.html.DomNodeList;
import org.htmlunit.html.HtmlButton;
import org.htmlunit.html.HtmlElementUtil;
import org.htmlunit.html.HtmlFileInput;
import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlOption;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.html.HtmlRadioButtonInput;

import hudson.FilePath;
import hudson.Util;
import hudson.cli.CLICommandInvoker;
Expand All @@ -57,6 +59,7 @@
import hudson.util.Secret;
import jenkins.model.Jenkins;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
Expand All @@ -71,6 +74,7 @@
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.KeyStore;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
Expand All @@ -91,10 +95,14 @@ public class CertificateCredentialsImplTest {

private File p12;
private File p12Invalid;
private String pemCert;
private String pemKey;

private static final String VALID_PASSWORD = "password";
private static final String INVALID_PASSWORD = "blabla";
private static final String EXPECTED_DISPLAY_NAME = "[email protected], CN=pkcs12, O=Fort-Funston, L=SanFrancisco, ST=CA, C=US";
// BC uses a different format even though the file was converted from the pkcs12 file
private static final String EXPECTED_DISPLAY_NAME_PEM = "C=US,ST=CA,L=SanFrancisco,O=Fort-Funston,CN=pkcs12,[email protected]";

@Before
public void setup() throws IOException {
Expand All @@ -103,6 +111,9 @@ public void setup() throws IOException {
p12Invalid = tmp.newFile("invalid.p12");
FileUtils.copyURLToFile(CertificateCredentialsImplTest.class.getResource("invalid.p12"), p12Invalid);

pemCert = IOUtils.toString(CertificateCredentialsImplTest.class.getResource("certs.pem"), StandardCharsets.UTF_8);
pemKey = IOUtils.toString(CertificateCredentialsImplTest.class.getResource("key.pem"), StandardCharsets.UTF_8);

r.jenkins.setCrumbIssuer(null);
}

Expand Down Expand Up @@ -212,7 +223,8 @@ public void doCheckUploadedKeystore_keyStoreInvalid() throws Exception {
@Issue("JENKINS-63761")
public void fullSubmitOfUploadedKeystore() throws Exception {
String certificateDisplayName = r.jenkins.getDescriptor(CertificateCredentialsImpl.class).getDisplayName();

String KeyStoreSourceDisplayName = r.jenkins.getDescriptor(CertificateCredentialsImpl.UploadedKeyStoreSource.class).getDisplayName();

JenkinsRule.WebClient wc = r.createWebClient();
HtmlPage htmlPage = wc.goTo("credentials/store/system/domain/_/newCredentials");
HtmlForm newCredentialsForm = htmlPage.getFormByName("newCredentials");
Expand All @@ -234,9 +246,11 @@ public void fullSubmitOfUploadedKeystore() throws Exception {
return false;
});
assertTrue("The Certificate option was not found in the credentials type select", optionFound);

HtmlRadioButtonInput keyStoreRadio = htmlPage.getDocumentElement().querySelector("input[name$=keyStoreSource]");
HtmlElementUtil.click(keyStoreRadio);

List<HtmlRadioButtonInput> inputs = htmlPage.getDocumentElement().
getByXPath("//input[contains(@name, 'keyStoreSource') and following-sibling::label[contains(.,'"+KeyStoreSourceDisplayName+"')]]");
assertThat("query should return only a singular input", inputs, hasSize(1));
HtmlElementUtil.click(inputs.get(0));

HtmlFileInput uploadedCertFileInput = htmlPage.getDocumentElement().querySelector("input[type=file][name=uploadedCertFile]");
uploadedCertFileInput.setFiles(p12);
Expand All @@ -258,6 +272,66 @@ public void fullSubmitOfUploadedKeystore() throws Exception {
assertEquals(EXPECTED_DISPLAY_NAME, displayName);
}

@Test
@Issue("JENKINS-73335")
public void fullSubmitOfUploadedPEM() throws Exception {
String certificateDisplayName = r.jenkins.getDescriptor(CertificateCredentialsImpl.class).getDisplayName();
String KeyStoreSourceDisplayName = r.jenkins.getDescriptor(CertificateCredentialsImpl.PEMEntryKeyStoreSource.class).getDisplayName();

JenkinsRule.WebClient wc = r.createWebClient();
HtmlPage htmlPage = wc.goTo("credentials/store/system/domain/_/newCredentials");
HtmlForm newCredentialsForm = htmlPage.getFormByName("newCredentials");

DomNodeList<DomNode> allOptions = htmlPage.getDocumentElement().querySelectorAll("select.dropdownList option");
boolean optionFound = allOptions.stream().anyMatch(domNode -> {
if (domNode instanceof HtmlOption) {
HtmlOption option = (HtmlOption) domNode;
if (option.getVisibleText().equals(certificateDisplayName)) {
try {
HtmlElementUtil.click(option);
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
}

return false;
});
assertTrue("The Certificate option was not found in the credentials type select", optionFound);

List<HtmlRadioButtonInput> inputs = htmlPage.getDocumentElement().
getByXPath("//input[contains(@name, 'keyStoreSource') and following-sibling::label[contains(.,'"+KeyStoreSourceDisplayName+"')]]");
assertThat("query should return only a singular input", inputs, hasSize(1));
HtmlElementUtil.click(inputs.get(0));

// enable entry of the secret (HACK just click all the Add buttons)
List<HtmlButton> buttonsByName = htmlPage.getDocumentElement().getByXPath("//button[contains(.,'Add')]");
assertThat("I need 2 buttons", buttonsByName, hasSize(2));
for (HtmlButton b : buttonsByName) {
HtmlElementUtil.click(b);
}

newCredentialsForm.getTextAreaByName("_.certChain").setTextContent(pemCert);
newCredentialsForm.getTextAreaByName("_.privateKey").setTextContent(pemKey);

// for all the types of credentials
newCredentialsForm.getInputsByName("_.password").forEach(input -> input.setValue(VALID_PASSWORD));

List<CertificateCredentials> certificateCredentials = CredentialsProvider.lookupCredentialsInItemGroup(CertificateCredentials.class, (ItemGroup<?>) null, ACL.SYSTEM2);
assertThat(certificateCredentials, hasSize(0));

r.submit(newCredentialsForm);

certificateCredentials = CredentialsProvider.lookupCredentialsInItemGroup(CertificateCredentials.class, (ItemGroup<?>) null, ACL.SYSTEM2);
assertThat(certificateCredentials, hasSize(1));

CertificateCredentials certificate = certificateCredentials.get(0);
KeyStore ks = certificate.getKeyStore();
String displayName = StandardCertificateCredentials.NameProvider.getSubjectDN(certificate.getKeyStore());
assertEquals(EXPECTED_DISPLAY_NAME_PEM, displayName);
}

private String getValidP12_base64() throws Exception {
return Base64.getEncoder().encodeToString(Files.readAllBytes(p12.toPath()));
}
Expand Down
Loading

0 comments on commit 44569cb

Please sign in to comment.