author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
686,981
03.06.2020 11:11:23
-3,600
8b7f1e1c1368f6e064e052f9e1eff387ef11925e
Add a TrustSpecificHostsStrategy to allow trusting specific hosts All the tests now pass, but lots of refactoring is needed!
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "diff": "@@ -20,6 +20,7 @@ import com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\nimport com.github.tomakehurst.wiremock.http.ssl.TrustEverythingStrategy;\nimport com.github.tomakehurst.wiremock.http.ssl.TrustSelfSignedStrategy;\n+import com.github.tomakehurst.wiremock.http.ssl.TrustSpecificHostsStrategy;\nimport org.apache.http.HttpHost;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\n@@ -32,11 +33,11 @@ import org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n-import org.apache.http.ssl.SSLContexts;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSession;\n+import java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n@@ -92,7 +93,7 @@ public class HttpClientFactory {\n}\n}\n- final SSLContext sslContext = buildSslContext(trustStoreSettings, trustSelfSignedCertificates);\n+ final SSLContext sslContext = buildSslContext(trustStoreSettings, trustSelfSignedCertificates, trustedHosts);\nbuilder.setSSLContext(sslContext);\nreturn builder.build();\n@@ -100,14 +101,19 @@ public class HttpClientFactory {\nprivate static SSLContext buildSslContext(\nKeyStoreSettings trustStoreSettings,\n- boolean trustSelfSignedCertificates\n+ boolean trustSelfSignedCertificates,\n+ List<String> trustedHosts\n) {\nif (trustStoreSettings != NO_STORE) {\n- return buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates);\n+ return buildSSLContextWithTrustStore(trustStoreSettings, trustSelfSignedCertificates, trustedHosts);\n} else if (trustSelfSignedCertificates) {\nreturn buildAllowAnythingSSLContext();\n} else {\n- return SSLContexts.createSystemDefault();\n+ try {\n+ return SSLContextBuilder.create().loadTrustMaterial(new TrustSpecificHostsStrategy(trustedHosts)).build();\n+ } catch (NoSuchAlgorithmException | KeyManagementException e) {\n+ return throwUnchecked(e, null);\n+ }\n}\n}\n@@ -127,7 +133,7 @@ public class HttpClientFactory {\nreturn createClient(maxConnections, timeoutMilliseconds, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\n}\n- private static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates) {\n+ private static SSLContext buildSSLContextWithTrustStore(KeyStoreSettings trustStoreSettings, boolean trustSelfSignedCertificates, List<String> trustedHosts) {\ntry {\nKeyStore trustStore = trustStoreSettings.loadStore();\nSSLContextBuilder sslContextBuilder = SSLContextBuilder.create()\n@@ -136,7 +142,9 @@ public class HttpClientFactory {\nif (trustSelfSignedCertificates) {\nsslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());\n} else if (containsCertificate(trustStore)) {\n- sslContextBuilder.loadTrustMaterial(trustStore);\n+ sslContextBuilder.loadTrustMaterial(trustStore, new TrustSpecificHostsStrategy(trustedHosts));\n+ } else {\n+ sslContextBuilder.loadTrustMaterial(new TrustSpecificHostsStrategy(trustedHosts));\n}\nreturn sslContextBuilder\n.build();\n@@ -164,7 +172,7 @@ public class HttpClientFactory {\ntry {\nreturn SSLContextBuilder.create().loadTrustMaterial(new TrustEverythingStrategy()).build();\n} catch (Exception e) {\n- return throwUnchecked(e, SSLContext.class);\n+ return throwUnchecked(e, null);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java", "diff": "@@ -66,6 +66,7 @@ import java.util.Map;\nimport java.util.Set;\nimport static com.github.tomakehurst.wiremock.common.ArrayFunctions.concat;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.ListFunctions.splitByType;\nimport static java.util.Collections.addAll;\n@@ -198,6 +199,13 @@ public class SSLContextBuilder {\npublic SSLContextBuilder loadTrustMaterial(\nfinal KeyStore truststore\n) throws NoSuchAlgorithmException, KeyStoreException {\n+ return loadTrustMaterial(truststore, null);\n+ }\n+\n+ public SSLContextBuilder loadTrustMaterial(\n+ final KeyStore truststore,\n+ final TrustStrategy trustStrategy\n+ ) throws NoSuchAlgorithmException, KeyStoreException {\nString algorithm = trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : trustManagerFactoryAlgorithm;\nTrustManager[] tms = loadTrustManagers(truststore, algorithm);\n@@ -207,7 +215,9 @@ public class SSLContextBuilder {\nList<TrustManager> otherTms = split.a;\nList<X509ExtendedTrustManager> x509Tms = split.b;\nif (!x509Tms.isEmpty()) {\n- this.trustManagers.add(new CompositeTrustManager(x509Tms));\n+ CompositeTrustManager trustManager = new CompositeTrustManager(x509Tms);\n+ TrustManager tm = trustStrategy == null ? trustManager : addStrategy(trustManager, trustStrategy);\n+ this.trustManagers.add(tm);\n}\nthis.trustManagers.addAll(otherTms);\nreturn this;\n@@ -215,9 +225,9 @@ public class SSLContextBuilder {\npublic SSLContextBuilder loadTrustMaterial(\nfinal TrustStrategy trustStrategy\n- ) throws NoSuchAlgorithmException, KeyStoreException {\n+ ) {\n- TrustManager[] tms = loadTrustManagers(null, TrustManagerFactory.getDefaultAlgorithm());\n+ TrustManager[] tms = loadDefaultTrustManagers();\nTrustManager[] tmsWithStrategy = addStrategy(tms, trustStrategy);\naddAll(this.trustManagers, tmsWithStrategy);\n@@ -231,8 +241,12 @@ public class SSLContextBuilder {\nreturn tms == null ? new TrustManager[0] : tms;\n}\n- private TrustManager[] loadDefaultTrustManagers() throws KeyStoreException, NoSuchAlgorithmException {\n+ private TrustManager[] loadDefaultTrustManagers() {\n+ try {\nreturn loadTrustManagers(null, TrustManagerFactory.getDefaultAlgorithm());\n+ } catch (NoSuchAlgorithmException | KeyStoreException e) {\n+ return throwUnchecked(e, null);\n+ }\n}\nprivate TrustManager[] addStrategy(TrustManager[] allTms, TrustStrategy trustStrategy) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/TrustSpecificHostsStrategy.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SSLEngine;\n+import java.net.Socket;\n+import java.security.cert.X509Certificate;\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+public class TrustSpecificHostsStrategy implements TrustStrategy {\n+\n+ private final List<String> trustedHosts;\n+\n+ public TrustSpecificHostsStrategy(List<String> trustedHosts) {\n+ this.trustedHosts = new ArrayList<>(trustedHosts);\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType) {\n+ return false;\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType, Socket socket) {\n+ return trustedHosts.contains(socket.getInetAddress().getHostName());\n+ }\n+\n+ @Override\n+ public boolean isTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {\n+ return false;\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add a TrustSpecificHostsStrategy to allow trusting specific hosts All the tests now pass, but lots of refactoring is needed!
686,981
03.06.2020 11:15:27
-3,600
8eea8b3ad19c219c686590c2297eaa70f0bd506c
Move hostname verification into JVM default behaviour Means we don't need to do our own hostname verifier logic that differs depending on whether or not we're just trusting an endpoint regardless of certificate.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\n+import com.github.tomakehurst.wiremock.http.ssl.HostVerifyingSSLSocketFactory;\nimport com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\nimport com.github.tomakehurst.wiremock.http.ssl.TrustEverythingStrategy;\nimport com.github.tomakehurst.wiremock.http.ssl.TrustSelfSignedStrategy;\n@@ -27,16 +28,16 @@ import org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.config.RequestConfig;\nimport org.apache.http.client.methods.*;\nimport org.apache.http.config.SocketConfig;\n-import org.apache.http.conn.ssl.DefaultHostnameVerifier;\n+import org.apache.http.conn.socket.LayeredConnectionSocketFactory;\nimport org.apache.http.conn.ssl.NoopHostnameVerifier;\n+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;\nimport org.apache.http.impl.client.BasicCredentialsProvider;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClientBuilder;\nimport org.apache.http.impl.client.ProxyAuthenticationStrategy;\n+import org.apache.http.util.TextUtils;\n-import javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\n-import javax.net.ssl.SSLSession;\nimport java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n@@ -77,9 +78,6 @@ public class HttpClientFactory {\n.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeoutMilliseconds).build())\n.useSystemProperties();\n- HostnameVerifier hostnameVerifier = buildHostnameVerifier(trustSelfSignedCertificates, trustedHosts);\n- builder.setSSLHostnameVerifier(hostnameVerifier);\n-\nif (proxySettings != NO_PROXY) {\nHttpHost proxyHost = new HttpHost(proxySettings.host(), proxySettings.port());\nbuilder.setProxy(proxyHost);\n@@ -94,11 +92,35 @@ public class HttpClientFactory {\n}\nfinal SSLContext sslContext = buildSslContext(trustStoreSettings, trustSelfSignedCertificates, trustedHosts);\n- builder.setSSLContext(sslContext);\n+ LayeredConnectionSocketFactory sslSocketFactory = buildSslConnectionSocketFactory(sslContext);\n+ builder.setSSLSocketFactory(sslSocketFactory);\nreturn builder.build();\n}\n+ private static LayeredConnectionSocketFactory buildSslConnectionSocketFactory(final SSLContext sslContext) {\n+ final String[] supportedProtocols = split(System.getProperty(\"https.protocols\"));\n+ final String[] supportedCipherSuites = split(System.getProperty(\"https.cipherSuites\"));\n+\n+ return new SSLConnectionSocketFactory(\n+ new HostVerifyingSSLSocketFactory(sslContext.getSocketFactory()),\n+ supportedProtocols,\n+ supportedCipherSuites,\n+ new NoopHostnameVerifier() // using Java's hostname verification\n+ );\n+ }\n+\n+ /**\n+ * Copied from {@link HttpClientBuilder#split(String)} which is not\n+ * the same as {@link org.apache.commons.lang3.StringUtils#split(String)}\n+ */\n+ private static String[] split(final String s) {\n+ if (TextUtils.isBlank(s)) {\n+ return null;\n+ }\n+ return s.split(\" *, *\");\n+ }\n+\nprivate static SSLContext buildSslContext(\nKeyStoreSettings trustStoreSettings,\nboolean trustSelfSignedCertificates,\n@@ -117,14 +139,6 @@ public class HttpClientFactory {\n}\n}\n- private static HostnameVerifier buildHostnameVerifier(boolean trustSelfSignedCertificates, List<String> trustedHosts) {\n- if (trustSelfSignedCertificates) {\n- return new NoopHostnameVerifier();\n- } else {\n- return new ExtraHostsHostnameVerifier(trustedHosts);\n- }\n- }\n-\npublic static CloseableHttpClient createClient(\nint maxConnections,\nint timeoutMilliseconds,\n@@ -214,23 +228,4 @@ public class HttpClientFactory {\nelse\nreturn new GenericHttpUriRequest(method.toString(), url);\n}\n-\n- private static class ExtraHostsHostnameVerifier implements HostnameVerifier {\n-\n- private final List<String> trustedHosts;\n- private final DefaultHostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();\n-\n- public ExtraHostsHostnameVerifier(List<String> trustedHosts) {\n- this.trustedHosts = trustedHosts;\n- }\n-\n- @Override\n- public boolean verify(String hostname, SSLSession session) {\n- if (trustedHosts.contains(hostname)) {\n- return true;\n- } else {\n- return defaultHostnameVerifier.verify(hostname, session);\n- }\n- }\n- }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/HostVerifyingSSLSocketFactory.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SSLParameters;\n+import javax.net.ssl.SSLSocket;\n+import javax.net.ssl.SSLSocketFactory;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.net.InetAddress;\n+import java.net.Socket;\n+import java.net.UnknownHostException;\n+\n+public class HostVerifyingSSLSocketFactory extends SSLSocketFactory {\n+\n+ private final SSLSocketFactory delegate;\n+\n+ public HostVerifyingSSLSocketFactory(SSLSocketFactory delegate) {\n+ this.delegate = delegate;\n+ }\n+\n+ public String[] getDefaultCipherSuites() {\n+ return delegate.getDefaultCipherSuites();\n+ }\n+\n+ public String[] getSupportedCipherSuites() {\n+ return delegate.getSupportedCipherSuites();\n+ }\n+\n+ public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {\n+ return verifyHosts(delegate.createSocket(s, host, port, autoClose));\n+ }\n+\n+ public Socket createSocket(Socket s, InputStream consumed, boolean autoClose) throws IOException {\n+ return verifyHosts(delegate.createSocket(s, consumed, autoClose));\n+ }\n+\n+ public Socket createSocket() throws IOException {\n+ return verifyHosts(delegate.createSocket());\n+ }\n+\n+ public Socket createSocket(String host, int port) throws IOException, UnknownHostException {\n+ return verifyHosts(delegate.createSocket(host, port));\n+ }\n+\n+ public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {\n+ return verifyHosts(delegate.createSocket(host, port, localHost, localPort));\n+ }\n+\n+ public Socket createSocket(InetAddress host, int port) throws IOException {\n+ return verifyHosts(delegate.createSocket(host, port));\n+ }\n+\n+ public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {\n+ return verifyHosts(delegate.createSocket(address, port, localAddress, localPort));\n+ }\n+\n+ public static Socket verifyHosts(Socket socket) {\n+ if (socket instanceof SSLSocket) {\n+ SSLSocket sslSocket = (SSLSocket) socket;\n+ SSLParameters sslParameters = sslSocket.getSSLParameters();\n+ sslParameters.setEndpointIdentificationAlgorithm(\"HTTPS\");\n+ sslSocket.setSSLParameters(sslParameters);\n+ }\n+ return socket;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/TrustSpecificHostsStrategy.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/TrustSpecificHostsStrategy.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\nimport javax.net.ssl.SSLEngine;\n+import java.net.InetAddress;\nimport java.net.Socket;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\n@@ -21,7 +22,8 @@ public class TrustSpecificHostsStrategy implements TrustStrategy {\n@Override\npublic boolean isTrusted(X509Certificate[] chain, String authType, Socket socket) {\n- return trustedHosts.contains(socket.getInetAddress().getHostName());\n+ InetAddress inetAddress = socket.getInetAddress();\n+ return trustedHosts.contains(inetAddress.getHostName()) || trustedHosts.contains(inetAddress.getHostAddress());\n}\n@Override\n" }, { "change_type": "DELETE", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateAcceptsRealValidCertificatesTest.java", "new_path": null, "diff": "-package com.github.tomakehurst.wiremock.http;\n-\n-import org.apache.http.HttpResponse;\n-import org.apache.http.client.methods.HttpGet;\n-import org.junit.Test;\n-import org.junit.function.ThrowingRunnable;\n-\n-import javax.net.ssl.SSLException;\n-import java.util.Collections;\n-\n-import static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsStringAndCloseStream;\n-import static org.junit.Assert.assertThrows;\n-\n-public class HttpClientFactoryCertificateAcceptsRealValidCertificatesTest extends HttpClientFactoryCertificateVerificationTest {\n-\n- public HttpClientFactoryCertificateAcceptsRealValidCertificatesTest() {\n- super(Collections.<String>emptyList(), \"localhost\", true);\n- }\n-\n- @Test\n- public void realCertificateIsAccepted() throws Exception {\n-\n- HttpResponse response = client.execute(new HttpGet(\"https://www.example.com/\"));\n-\n- getEntityAsStringAndCloseStream(response);\n- }\n-\n- @Test\n- public void invalidRealCertificateIsRejected() {\n-\n- assertThrows(SSLException.class, new ThrowingRunnable() {\n- @Override\n- public void run() throws Exception {\n- client.execute(new HttpGet(\"https://wiremock.org/\"));\n- }\n- });\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "diff": "@@ -123,7 +123,7 @@ public class ProxyResponseRendererTest {\nCertificateSpecification certificateSpecification = new X509CertificateSpecification(\n/* version = */V3,\n- /* subject = */\"CN=wiremock.org\",\n+ /* subject = */\"CN=localhost\",\n/* issuer = */\"CN=wiremock.org\",\n/* notBefore = */new Date(),\n/* notAfter = */new Date(System.currentTimeMillis() + (365L * 24 * 60 * 60 * 1000))\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Move hostname verification into JVM default behaviour Means we don't need to do our own hostname verifier logic that differs depending on whether or not we're just trusting an endpoint regardless of certificate.
686,981
03.06.2020 15:11:42
-3,600
badc431a92bda0e7b6f55f62e9b588fb37dcbf5f
Suppress sun internal api warnings It's a deliberate choice
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -136,6 +136,7 @@ allprojects {\ncompileTestJava {\noptions.encoding = 'UTF-8'\n+ options.compilerArgs += '-XDenableSunApiLintControl'\n}\ntest {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateSpecification.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateSpecification.java", "diff": "@@ -26,6 +26,7 @@ import java.util.Date;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.util.Objects.requireNonNull;\n+@SuppressWarnings(\"sunapi\")\npublic class X509CertificateSpecification implements CertificateSpecification {\nprivate final X509CertificateVersion version;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateVersion.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/crypto/X509CertificateVersion.java", "diff": "@@ -6,6 +6,7 @@ import java.io.IOException;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+@SuppressWarnings(\"sunapi\")\npublic enum X509CertificateVersion {\nV1(CertificateVersion.V1),\n@@ -26,7 +27,7 @@ public enum X509CertificateVersion {\n}\n}\n- public CertificateVersion getVersion() {\n+ CertificateVersion getVersion() {\nreturn version;\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Suppress sun internal api warnings It's a deliberate choice
686,981
03.06.2020 15:15:53
-3,600
2158ec2b4c5e30187ac76bd3e62dd399ed764eb3
Accept trusted proxy targets as configuration
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java", "diff": "@@ -74,4 +74,5 @@ public interface Options {\nboolean getStubRequestLoggingDisabled();\nboolean getStubCorsEnabled();\nboolean trustAllProxyTargets();\n+ List<String> trustedProxyTargets();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "diff": "@@ -151,7 +151,8 @@ public class WireMockApp implements StubServer, Admin {\noptions.shouldPreserveHostHeader(),\noptions.proxyHostHeader(),\nglobalSettingsHolder,\n- options.trustAllProxyTargets()\n+ options.trustAllProxyTargets(),\n+ options.trustedProxyTargets()\n),\nImmutableList.copyOf(options.extensionsOfType(ResponseTransformer.class).values())\n),\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "diff": "@@ -37,6 +37,7 @@ import com.google.common.base.Optional;\nimport com.google.common.collect.Maps;\nimport com.google.common.io.Resources;\n+import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n@@ -99,6 +100,7 @@ public class WireMockConfiguration implements Options {\nprivate boolean stubCorsEnabled = false;\nprivate boolean trustAllProxyTargets = false;\n+ private final List<String> trustedProxyTargets = new ArrayList<>();\nprivate MappingsSource getMappingsSource() {\nif (mappingsSource == null) {\n@@ -368,6 +370,15 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration trustedProxyTargets(String... trustedProxyTargets) {\n+ return trustedProxyTargets(asList(trustedProxyTargets));\n+ }\n+\n+ public WireMockConfiguration trustedProxyTargets(List<String> trustedProxyTargets) {\n+ this.trustedProxyTargets.addAll(trustedProxyTargets);\n+ return this;\n+ }\n+\n@Override\npublic int portNumber() {\nreturn portNumber;\n@@ -532,4 +543,9 @@ public class WireMockConfiguration implements Options {\npublic boolean trustAllProxyTargets() {\nreturn trustAllProxyTargets;\n}\n+\n+ @Override\n+ public List<String> trustedProxyTargets() {\n+ return trustedProxyTargets;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "diff": "@@ -69,12 +69,13 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nboolean preserveHostHeader,\nString hostHeaderValue,\nGlobalSettingsHolder globalSettingsHolder,\n- boolean trustAllProxyTargets\n+ boolean trustAllProxyTargets,\n+ List<String> trustedProxyTargets\n) {\nthis.globalSettingsHolder = globalSettingsHolder;\nthis.trustAllProxyTargets = trustAllProxyTargets;\nclient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\n- scepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false, Collections.<String>emptyList());\n+ scepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false, trustedProxyTargets);\nthis.preserveHostHeader = preserveHostHeader;\nthis.hostHeaderValue = hostHeaderValue;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/servlet/WarConfiguration.java", "diff": "@@ -37,6 +37,8 @@ import java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n+import static java.util.Collections.emptyList;\n+\npublic class WarConfiguration implements Options {\nprivate static final String FILE_SOURCE_ROOT_KEY = \"WireMockFileSourceRoot\";\n@@ -124,7 +126,7 @@ public class WarConfiguration implements Options {\n@Override\npublic List<CaseInsensitiveKey> matchingHeaders() {\n- return Collections.emptyList();\n+ return emptyList();\n}\n@Override\n@@ -201,4 +203,9 @@ public class WarConfiguration implements Options {\npublic boolean trustAllProxyTargets() {\nreturn false;\n}\n+\n+ @Override\n+ public List<String> trustedProxyTargets() {\n+ return emptyList();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -97,6 +97,7 @@ public class CommandLineOptions implements Options {\nprivate static final String DISABLE_REQUEST_LOGGING = \"disable-request-logging\";\nprivate static final String ENABLE_STUB_CORS = \"enable-stub-cors\";\nprivate static final String TRUST_ALL_PROXY_TARGETS = \"trust-all-proxy-targets\";\n+ private static final String TRUST_PROXY_TARGET = \"trust-proxy-target\";\nprivate final OptionSet optionSet;\nprivate final FileSource fileSource;\n@@ -148,6 +149,7 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(DISABLE_REQUEST_LOGGING, \"Disable logging of stub requests and responses to the notifier. Useful when performance testing.\");\noptionParser.accepts(ENABLE_STUB_CORS, \"Enable automatic sending of CORS headers with stub responses.\");\noptionParser.accepts(TRUST_ALL_PROXY_TARGETS, \"Trust all certificates presented by origins when browser proxying\");\n+ optionParser.accepts(TRUST_PROXY_TARGET, \"Trust any certificate presented by this origin when browser proxying\").withRequiredArg();\noptionParser.accepts(HELP, \"Print this message\");\n@@ -566,6 +568,11 @@ public class CommandLineOptions implements Options {\nreturn optionSet.has(TRUST_ALL_PROXY_TARGETS);\n}\n+ @Override\n+ public List<String> trustedProxyTargets() {\n+ return (List<String>) optionSet.valuesOf(TRUST_PROXY_TARGET);\n+ }\n+\nprivate Long getMaxTemplateCacheEntries() {\nreturn optionSet.has(MAX_TEMPLATE_CACHE_ENTRIES) ?\nLong.valueOf(optionSet.valueOf(MAX_TEMPLATE_CACHE_ENTRIES).toString()) :\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "diff": "@@ -20,6 +20,7 @@ import java.io.File;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\n+import java.util.Collections;\nimport java.util.Date;\nimport java.util.HashMap;\n@@ -151,7 +152,8 @@ public class ProxyResponseRendererTest {\n/* preserveHostHeader = */ false,\n/* hostHeaderValue = */ null,\nnew GlobalSettingsHolder(),\n- trustAllProxyTargets\n+ trustAllProxyTargets,\n+ Collections.<String>emptyList()\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -32,10 +32,13 @@ import com.github.tomakehurst.wiremock.security.Authenticator;\nimport com.google.common.base.Optional;\nimport org.junit.Test;\n+import java.util.Collections;\nimport java.util.Map;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.matchesMultiLine;\n+import static java.util.Arrays.asList;\n+import static java.util.Collections.singletonList;\nimport static org.hamcrest.Matchers.*;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -478,17 +481,35 @@ public class CommandLineOptionsTest {\n}\n@Test\n- public void trustsAll() {\n+ public void trustAllProxyTargets() {\nCommandLineOptions options = new CommandLineOptions(\"--trust-all-proxy-targets\");\nassertThat(options.trustAllProxyTargets(), is(true));\n}\n@Test\n- public void defaultsToNotTrustingAll() {\n+ public void defaultsToNotTrustingAllProxyTargets() {\nCommandLineOptions options = new CommandLineOptions();\nassertThat(options.trustAllProxyTargets(), is(false));\n}\n+ @Test\n+ public void trustsOneProxyTarget1() {\n+ CommandLineOptions options = new CommandLineOptions(\"--trust-proxy-target\", \"localhost\");\n+ assertThat(options.trustedProxyTargets(), is(singletonList(\"localhost\")));\n+ }\n+\n+ @Test\n+ public void trustsManyProxyTargets() {\n+ CommandLineOptions options = new CommandLineOptions(\"--trust-proxy-target=localhost\", \"--trust-proxy-target\", \"wiremock.org\", \"--trust-proxy-target=www.google.com\");\n+ assertThat(options.trustedProxyTargets(), is(asList(\"localhost\", \"wiremock.org\", \"www.google.com\")));\n+ }\n+\n+ @Test\n+ public void defaultsToNoTrustedProxyTargets() {\n+ CommandLineOptions options = new CommandLineOptions();\n+ assertThat(options.trustedProxyTargets(), is(Collections.<String>emptyList()));\n+ }\n+\n@Test\npublic void printsBothActualPortsOnlyWhenHttpsEnabled() {\nCommandLineOptions options = new CommandLineOptions();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Accept trusted proxy targets as configuration
686,981
03.06.2020 17:35:20
-3,600
94f0ec14b80dd419231e67d3e6e46ba264e3be42
Show proxy target config on startup
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -36,6 +36,7 @@ import com.github.tomakehurst.wiremock.security.NoAuthenticator;\nimport com.github.tomakehurst.wiremock.verification.notmatched.NotMatchedRenderer;\nimport com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer;\nimport com.google.common.annotations.VisibleForTesting;\n+import com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.*;\n@@ -515,6 +516,15 @@ public class CommandLineOptions implements Options {\nbuilder.put(ADMIN_API_REQUIRE_HTTPS, \"true\");\n}\n+ if (trustAllProxyTargets()) {\n+ builder.put(TRUST_ALL_PROXY_TARGETS, \"true\");\n+ }\n+\n+ List<String> trustedProxyTargets = trustedProxyTargets();\n+ if (!trustedProxyTargets.isEmpty()) {\n+ builder.put(TRUST_PROXY_TARGET, Joiner.on(\", \").join(trustedProxyTargets));\n+ }\n+\nStringBuilder sb = new StringBuilder();\nfor (Map.Entry<String, Object> param: builder.build().entrySet()) {\nint paddingLength = 29 - param.getKey().length();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Show proxy target config on startup
686,981
05.06.2020 11:49:06
-3,600
1b4251769b72a305e49e6182654235c2e0602c66
Let mockito handle creating a stub value
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManagerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ssl/CompositeTrustManagerTest.java", "diff": "@@ -132,10 +132,10 @@ public class CompositeTrustManagerTest {\n@Test\npublic void returnAllAcceptedIssuers() {\n- final X509Certificate cert1 = new FakeX509Certificate(\"cert1\");\n- final X509Certificate cert2 = new FakeX509Certificate(\"cert2\");\n- final X509Certificate cert3 = new FakeX509Certificate(\"cert3\");\n- final X509Certificate cert4 = new FakeX509Certificate(\"cert4\");\n+ final X509Certificate cert1 = mock(X509Certificate.class, \"cert1\");\n+ final X509Certificate cert2 = mock(X509Certificate.class, \"cert2\");\n+ final X509Certificate cert3 = mock(X509Certificate.class, \"cert3\");\n+ final X509Certificate cert4 = mock(X509Certificate.class, \"cert4\");\ngiven(trustManager1.getAcceptedIssuers()).willReturn(new X509Certificate[] { cert1, cert2 });\ngiven(trustManager2.getAcceptedIssuers()).willReturn(new X509Certificate[] { cert3, cert4 });\n@@ -149,7 +149,7 @@ public class CompositeTrustManagerTest {\nassertArrayEquals(new X509Certificate[] { cert1, cert2, cert3, cert4 }, acceptedIssuers);\n- acceptedIssuers[2] = new FakeX509Certificate(\"cert5\");\n+ acceptedIssuers[2] = mock(X509Certificate.class, \"cert5\");\nassertArrayEquals(new X509Certificate[] { cert1, cert2, cert3, cert4 }, compositeTrustManager.getAcceptedIssuers());\n}\n@@ -159,143 +159,4 @@ public class CompositeTrustManagerTest {\nwhen(trustManager.getAcceptedIssuers()).thenReturn(new X509Certificate[0]);\nreturn trustManager;\n}\n-\n- private static class FakeX509Certificate extends X509Certificate {\n-\n- private final String name;\n-\n- public FakeX509Certificate(String name) {\n- this.name = name;\n- }\n-\n- @Override\n- public String toString() {\n- return \"X509Certificate{\" + name + \"}\";\n- }\n-\n- @Override\n- public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public int getVersion() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public BigInteger getSerialNumber() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public Principal getIssuerDN() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public Principal getSubjectDN() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public Date getNotBefore() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public Date getNotAfter() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public byte[] getTBSCertificate() throws CertificateEncodingException {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public byte[] getSignature() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public String getSigAlgName() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public String getSigAlgOID() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public byte[] getSigAlgParams() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public boolean[] getIssuerUniqueID() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public boolean[] getSubjectUniqueID() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public boolean[] getKeyUsage() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public int getBasicConstraints() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public byte[] getEncoded() throws CertificateEncodingException {\n- return name.getBytes();\n- }\n-\n- @Override\n- public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public PublicKey getPublicKey() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public boolean hasUnsupportedCriticalExtension() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public Set<String> getCriticalExtensionOIDs() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public Set<String> getNonCriticalExtensionOIDs() {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n-\n- @Override\n- public byte[] getExtensionValue(String oid) {\n- throw new UnsupportedOperationException(\"Not implemented\");\n- }\n- }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Let mockito handle creating a stub value
686,981
05.06.2020 12:12:52
-3,600
4d45cf439933a7c850943ea45da0e517859f73e5
Clean up the SSLContextBuilder Remove unused elements
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "diff": "@@ -151,8 +151,7 @@ public class HttpClientFactory {\ntry {\nKeyStore trustStore = trustStoreSettings.loadStore();\nSSLContextBuilder sslContextBuilder = SSLContextBuilder.create()\n- .loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray())\n- .setProtocol(\"TLS\");\n+ .loadKeyMaterial(trustStore, trustStoreSettings.password().toCharArray());\nif (trustSelfSignedCertificates) {\nsslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());\n} else if (containsCertificate(trustStore)) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java", "diff": "-/*\n- * ====================================================================\n- * Licensed to the Apache Software Foundation (ASF) under one\n- * or more contributor license agreements. See the NOTICE file\n- * distributed with this work for additional information\n- * regarding copyright ownership. The ASF licenses this file\n- * to you under the Apache License, Version 2.0 (the\n- * \"License\"); you may not use this file except in compliance\n- * with the License. You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing,\n- * software distributed under the License is distributed on an\n- * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n- * KIND, either express or implied. See the License for the\n- * specific language governing permissions and limitations\n- * under the License.\n- * ====================================================================\n- *\n- * This software consists of voluntary contributions made by many\n- * individuals on behalf of the Apache Software Foundation. For more\n- * information on the Apache Software Foundation, please see\n- * <http://www.apache.org/>.\n- *\n- */\n-\npackage com.github.tomakehurst.wiremock.http.ssl;\nimport com.github.tomakehurst.wiremock.common.Pair;\n-import org.apache.http.ssl.PrivateKeyDetails;\n-import org.apache.http.ssl.PrivateKeyStrategy;\n-import org.apache.http.util.Args;\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.KeyManagerFactory;\n@@ -38,31 +8,18 @@ import javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLEngine;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\n-import javax.net.ssl.X509ExtendedKeyManager;\nimport javax.net.ssl.X509ExtendedTrustManager;\n-import java.io.File;\n-import java.io.FileInputStream;\n-import java.io.IOException;\n-import java.io.InputStream;\nimport java.net.Socket;\n-import java.net.URL;\nimport java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n-import java.security.Principal;\n-import java.security.PrivateKey;\n-import java.security.Provider;\n-import java.security.SecureRandom;\n-import java.security.Security;\nimport java.security.UnrecoverableKeyException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.Collection;\n-import java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\n-import java.util.Map;\nimport java.util.Set;\nimport static com.github.tomakehurst.wiremock.common.ArrayFunctions.concat;\n@@ -70,144 +27,21 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.ListFunctions.splitByType;\nimport static java.util.Collections.addAll;\n-/**\n- * Builder for {@link SSLContext} instances.\n- * <p>\n- * Please note: the default Oracle JSSE implementation of {@link SSLContext#init(KeyManager[], TrustManager[], SecureRandom)}\n- * accepts multiple key and trust managers, however only only first matching type is ever used.\n- * See for example:\n- * <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLContext.html#init%28javax.net.ssl.KeyManager[],%20javax.net.ssl.TrustManager[],%20java.security.SecureRandom%29\">\n- * SSLContext.html#init\n- * </a>\n- * <p>\n- * TODO Specify which Oracle JSSE versions the above has been verified.\n- * </p>\n- * @since 4.4\n- */\npublic class SSLContextBuilder {\n- static final String TLS = \"TLS\";\n-\n- private String protocol;\nprivate final Set<KeyManager> keyManagers = new LinkedHashSet<>();\n- private String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();\n- private String keyStoreType = KeyStore.getDefaultType();\nprivate final Set<TrustManager> trustManagers = new LinkedHashSet<>();\n- private String trustManagerFactoryAlgorithm = TrustManagerFactory.getDefaultAlgorithm();\n- private SecureRandom secureRandom;\n- private Provider provider;\npublic static SSLContextBuilder create() {\nreturn new SSLContextBuilder();\n}\n- /**\n- * Sets the SSLContext protocol algorithm name.\n- *\n- * @param protocol\n- * the SSLContext protocol algorithm name of the requested protocol. See\n- * the SSLContext section in the <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext\">Java\n- * Cryptography Architecture Standard Algorithm Name\n- * Documentation</a> for more information.\n- * @return this builder\n- * @see <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext\">Java\n- * Cryptography Architecture Standard Algorithm Name Documentation</a>\n- * @since 4.4.7\n- */\n- public SSLContextBuilder setProtocol(final String protocol) {\n- this.protocol = protocol;\n- return this;\n- }\n-\n- public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) {\n- this.secureRandom = secureRandom;\n- return this;\n- }\n-\n- public SSLContextBuilder setProvider(final Provider provider) {\n- this.provider = provider;\n- return this;\n- }\n-\n- public SSLContextBuilder setProvider(final String name) {\n- this.provider = Security.getProvider(name);\n- return this;\n- }\n-\n- /**\n- * Sets the key store type.\n- *\n- * @param keyStoreType\n- * the SSLkey store type. See\n- * the KeyStore section in the <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyStore\">Java\n- * Cryptography Architecture Standard Algorithm Name\n- * Documentation</a> for more information.\n- * @return this builder\n- * @see <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyStore\">Java\n- * Cryptography Architecture Standard Algorithm Name Documentation</a>\n- * @since 4.4.7\n- */\n- public SSLContextBuilder setKeyStoreType(final String keyStoreType) {\n- this.keyStoreType = keyStoreType;\n- return this;\n- }\n-\n- /**\n- * Sets the key manager factory algorithm name.\n- *\n- * @param keyManagerFactoryAlgorithm\n- * the key manager factory algorithm name of the requested protocol. See\n- * the KeyManagerFactory section in the <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyManagerFactory\">Java\n- * Cryptography Architecture Standard Algorithm Name\n- * Documentation</a> for more information.\n- * @return this builder\n- * @see <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyManagerFactory\">Java\n- * Cryptography Architecture Standard Algorithm Name Documentation</a>\n- * @since 4.4.7\n- */\n- public SSLContextBuilder setKeyManagerFactoryAlgorithm(final String keyManagerFactoryAlgorithm) {\n- this.keyManagerFactoryAlgorithm = keyManagerFactoryAlgorithm;\n- return this;\n- }\n-\n- /**\n- * Sets the trust manager factory algorithm name.\n- *\n- * @param trustManagerFactoryAlgorithm\n- * the trust manager algorithm name of the requested protocol. See\n- * the TrustManagerFactory section in the <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#TrustManagerFactory\">Java\n- * Cryptography Architecture Standard Algorithm Name\n- * Documentation</a> for more information.\n- * @return this builder\n- * @see <a href=\n- * \"https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#TrustManagerFactory\">Java\n- * Cryptography Architecture Standard Algorithm Name Documentation</a>\n- * @since 4.4.7\n- */\n- public SSLContextBuilder setTrustManagerFactoryAlgorithm(final String trustManagerFactoryAlgorithm) {\n- this.trustManagerFactoryAlgorithm = trustManagerFactoryAlgorithm;\n- return this;\n- }\n-\n- public SSLContextBuilder loadTrustMaterial(\n- final KeyStore truststore\n- ) throws NoSuchAlgorithmException, KeyStoreException {\n- return loadTrustMaterial(truststore, null);\n- }\n-\npublic SSLContextBuilder loadTrustMaterial(\nfinal KeyStore truststore,\nfinal TrustStrategy trustStrategy\n) throws NoSuchAlgorithmException, KeyStoreException {\n- String algorithm = trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : trustManagerFactoryAlgorithm;\n+ String algorithm = TrustManagerFactory.getDefaultAlgorithm();\nTrustManager[] tms = loadTrustManagers(truststore, algorithm);\nTrustManager[] allTms = concat(tms, loadDefaultTrustManagers());\n@@ -267,94 +101,30 @@ public class SSLContextBuilder {\npublic SSLContextBuilder loadKeyMaterial(\nfinal KeyStore keystore,\n- final char[] keyPassword,\n- final PrivateKeyStrategy aliasStrategy)\n- throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {\n+ final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {\nfinal KeyManagerFactory kmfactory = KeyManagerFactory\n- .getInstance(keyManagerFactoryAlgorithm == null ? KeyManagerFactory.getDefaultAlgorithm()\n- : keyManagerFactoryAlgorithm);\n+ .getInstance(KeyManagerFactory.getDefaultAlgorithm());\nkmfactory.init(keystore, keyPassword);\nfinal KeyManager[] kms = kmfactory.getKeyManagers();\nif (kms != null) {\n- if (aliasStrategy != null) {\n- for (int i = 0; i < kms.length; i++) {\n- final KeyManager km = kms[i];\n- if (km instanceof X509ExtendedKeyManager) {\n- kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy);\n- }\n- }\n- }\naddAll(keyManagers, kms);\n}\nreturn this;\n}\n- public SSLContextBuilder loadKeyMaterial(\n- final KeyStore keystore,\n- final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {\n- return loadKeyMaterial(keystore, keyPassword, null);\n- }\n-\n- public SSLContextBuilder loadKeyMaterial(\n- final File file,\n- final char[] storePassword,\n- final char[] keyPassword,\n- final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n- Args.notNull(file, \"Keystore file\");\n- final KeyStore identityStore = KeyStore.getInstance(keyStoreType);\n- try (FileInputStream inStream = new FileInputStream(file)) {\n- identityStore.load(inStream, storePassword);\n- }\n- return loadKeyMaterial(identityStore, keyPassword, aliasStrategy);\n- }\n-\n- public SSLContextBuilder loadKeyMaterial(\n- final File file,\n- final char[] storePassword,\n- final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n- return loadKeyMaterial(file, storePassword, keyPassword, null);\n- }\n-\n- public SSLContextBuilder loadKeyMaterial(\n- final URL url,\n- final char[] storePassword,\n- final char[] keyPassword,\n- final PrivateKeyStrategy aliasStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n- Args.notNull(url, \"Keystore URL\");\n- final KeyStore identityStore = KeyStore.getInstance(keyStoreType);\n- try (InputStream inStream = url.openStream()) {\n- identityStore.load(inStream, storePassword);\n- }\n- return loadKeyMaterial(identityStore, keyPassword, aliasStrategy);\n- }\n-\n- public SSLContextBuilder loadKeyMaterial(\n- final URL url,\n- final char[] storePassword,\n- final char[] keyPassword) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {\n- return loadKeyMaterial(url, storePassword, keyPassword, null);\n- }\n-\nprotected void initSSLContext(\nfinal SSLContext sslContext,\nfinal Collection<KeyManager> keyManagers,\n- final Collection<TrustManager> trustManagers,\n- final SecureRandom secureRandom) throws KeyManagementException {\n+ final Collection<TrustManager> trustManagers) throws KeyManagementException {\nsslContext.init(\n!keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[0]) : null,\n!trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[0]) : null,\n- secureRandom);\n+ null);\n}\npublic SSLContext build() throws NoSuchAlgorithmException, KeyManagementException {\n- final SSLContext sslContext;\n- final String protocolStr = this.protocol != null ? this.protocol : TLS;\n- if (this.provider != null) {\n- sslContext = SSLContext.getInstance(protocolStr, this.provider);\n- } else {\n- sslContext = SSLContext.getInstance(protocolStr);\n- }\n- initSSLContext(sslContext, keyManagers, trustManagers, secureRandom);\n+ final SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n+ initSSLContext(sslContext, keyManagers, trustManagers);\nreturn sslContext;\n}\n@@ -412,103 +182,9 @@ public class SSLContextBuilder {\n}\n}\n- static class KeyManagerDelegate extends X509ExtendedKeyManager {\n-\n- private final X509ExtendedKeyManager keyManager;\n- private final PrivateKeyStrategy aliasStrategy;\n-\n- KeyManagerDelegate(final X509ExtendedKeyManager keyManager, final PrivateKeyStrategy aliasStrategy) {\n- super();\n- this.keyManager = keyManager;\n- this.aliasStrategy = aliasStrategy;\n- }\n-\n- @Override\n- public String[] getClientAliases(\n- final String keyType, final Principal[] issuers) {\n- return this.keyManager.getClientAliases(keyType, issuers);\n- }\n-\n- public Map<String, PrivateKeyDetails> getClientAliasMap(\n- final String[] keyTypes, final Principal[] issuers) {\n- final Map<String, PrivateKeyDetails> validAliases = new HashMap<>();\n- for (final String keyType: keyTypes) {\n- final String[] aliases = this.keyManager.getClientAliases(keyType, issuers);\n- if (aliases != null) {\n- for (final String alias: aliases) {\n- validAliases.put(alias,\n- new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));\n- }\n- }\n- }\n- return validAliases;\n- }\n-\n- public Map<String, PrivateKeyDetails> getServerAliasMap(\n- final String keyType, final Principal[] issuers) {\n- final Map<String, PrivateKeyDetails> validAliases = new HashMap<>();\n- final String[] aliases = this.keyManager.getServerAliases(keyType, issuers);\n- if (aliases != null) {\n- for (final String alias: aliases) {\n- validAliases.put(alias,\n- new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));\n- }\n- }\n- return validAliases;\n- }\n-\n- @Override\n- public String chooseClientAlias(\n- final String[] keyTypes, final Principal[] issuers, final Socket socket) {\n- final Map<String, PrivateKeyDetails> validAliases = getClientAliasMap(keyTypes, issuers);\n- return this.aliasStrategy.chooseAlias(validAliases, socket);\n- }\n-\n- @Override\n- public String[] getServerAliases(\n- final String keyType, final Principal[] issuers) {\n- return this.keyManager.getServerAliases(keyType, issuers);\n- }\n-\n- @Override\n- public String chooseServerAlias(\n- final String keyType, final Principal[] issuers, final Socket socket) {\n- final Map<String, PrivateKeyDetails> validAliases = getServerAliasMap(keyType, issuers);\n- return this.aliasStrategy.chooseAlias(validAliases, socket);\n- }\n-\n- @Override\n- public X509Certificate[] getCertificateChain(final String alias) {\n- return this.keyManager.getCertificateChain(alias);\n- }\n-\n- @Override\n- public PrivateKey getPrivateKey(final String alias) {\n- return this.keyManager.getPrivateKey(alias);\n- }\n-\n- @Override\n- public String chooseEngineClientAlias(\n- final String[] keyTypes, final Principal[] issuers, final SSLEngine sslEngine) {\n- final Map<String, PrivateKeyDetails> validAliases = getClientAliasMap(keyTypes, issuers);\n- return this.aliasStrategy.chooseAlias(validAliases, null);\n- }\n-\n- @Override\n- public String chooseEngineServerAlias(\n- final String keyType, final Principal[] issuers, final SSLEngine sslEngine) {\n- final Map<String, PrivateKeyDetails> validAliases = getServerAliasMap(keyType, issuers);\n- return this.aliasStrategy.chooseAlias(validAliases, null);\n- }\n-\n- }\n-\n@Override\npublic String toString() {\n- return \"[provider=\" + provider + \", protocol=\" + protocol + \", keyStoreType=\" + keyStoreType\n- + \", keyManagerFactoryAlgorithm=\" + keyManagerFactoryAlgorithm + \", keyManagers=\" + keyManagers\n- + \", trustManagerFactoryAlgorithm=\" + trustManagerFactoryAlgorithm + \", trustManagers=\" + trustManagers\n- + \", secureRandom=\" + secureRandom + \"]\";\n+ return \"[keyManagers=\" + keyManagers\n+ + \", trustManagers=\" + trustManagers + \"]\";\n}\n-\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Clean up the SSLContextBuilder Remove unused elements
686,981
05.06.2020 12:48:52
-3,600
1101f5f66939270813101984f09ffe8992e7b3a7
Document HTTPS proxy behaviour better
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -136,6 +136,35 @@ wiremock-jre8 allows forward proxying, stubbing & recording of HTTPS traffic. By\n```bash\n$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-all-proxy-targets\n```\n+or to trust specific hosts:\n+```bash\n+$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-proxy-target localhost --trust-proxy-target dev.mycorp.com\n+```\n+\n+Additional trusted public certificates can also be added to the keystore\n+specified via the `--https-truststore`, and should then be trusted without\n+needing the `--trust-proxy-target` parameter (so long as match the requested\n+host).\n+\n+As WireMock is here running as a man-in-the-middle, the resulting traffic will\n+appear to the client encrypted with WireMock's (configurable) private key &\n+certificate, and so will not be trusted by default by clients.\n+\n+Proxying of HTTPS traffic when the proxy endpoint is also HTTPS is problematic;\n+Postman seems not to cope with an HTTPS proxy even to proxy HTTP traffic. Older\n+versions of curl fail trying to do the CONNECT call because they try to do so\n+over HTTP/2 (newer versions only offer HTTP/1.1 for the CONNECT call). At time\n+of writing it works using `curl 7.64.1 (x86_64-apple-darwin19.0) libcurl/7.64.1 (SecureTransport) LibreSSL/2.8.3 zlib/1.2.11 nghttp2/1.39.2` as so:\n+```bash\n+curl --proxy-insecure -x https://localhost:8443 -k 'https://www.example.com/'\n+```\n+\n+Please check your client's behaviour proxying via another https proxy such as\n+https://hub.docker.com/r/wernight/spdyproxy to see if it is a client problem:\n+```bash\n+docker run --rm -it -p 44300:44300 wernight/spdyproxy\n+curl --proxy-insecure -x https://localhost:44300 -k 'https://www.example.com/'\n+```\n## Proxying via another proxy server\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -86,8 +86,14 @@ e.g. `--proxy-via http://username:password@webproxy.mycorp.com:8080/`.\n`--enable-browser-proxying`: Run as a browser proxy. See\nbrowser-proxying.\n-`--trust-all-proxy-targets`: Trust all remote certificates when running as a browser proxy and\n-proxying HTTPS traffic.\n+`--trust-all-proxy-targets`: Trust all remote certificates when running as a\n+browser proxy and proxying HTTPS traffic.\n+\n+`--trust-proxy-target`: Trust a specific remote endpoint's certificate when\n+running as a browser proxy and proxying HTTPS traffic. Can be specified multiple\n+times. e.g. `--trust-proxy-target dev.mycorp.com --trust-proxy-target localhost`\n+would allow proxying to `https://dev.mycorp.com` or `https://localhost:8443`\n+despite their having invalid certificate chains in some way.\n`--no-request-journal`: Disable the request journal, which records\nincoming requests for later verification. This allows WireMock to be run\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Document HTTPS proxy behaviour better
686,981
05.06.2020 14:14:50
-3,600
9f77ef5c742fd2f479dd05b8bf78afa94cb97758
Fix Java 1.7 compile error The method doesn't exist on the super class until Java 1.8. All the tests still pass, so I guess it was never called, as the super class in Java 1.8 throws `UnsupportedOperationException`.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/HostVerifyingSSLSocketFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/HostVerifyingSSLSocketFactory.java", "diff": "@@ -29,10 +29,6 @@ public class HostVerifyingSSLSocketFactory extends SSLSocketFactory {\nreturn verifyHosts(delegate.createSocket(s, host, port, autoClose));\n}\n- public Socket createSocket(Socket s, InputStream consumed, boolean autoClose) throws IOException {\n- return verifyHosts(delegate.createSocket(s, consumed, autoClose));\n- }\n-\npublic Socket createSocket() throws IOException {\nreturn verifyHosts(delegate.createSocket());\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fix Java 1.7 compile error The method doesn't exist on the super class until Java 1.8. All the tests still pass, so I guess it was never called, as the super class in Java 1.8 throws `UnsupportedOperationException`.
686,981
05.06.2020 21:47:52
-3,600
68ed1ad22f616af7e9d96c6d81b1925dd6007f17
Downgrade mockito to a Java 7 compatible version
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -113,7 +113,7 @@ allprojects {\nexclude group: \"org.hamcrest\", module: \"hamcrest-core\"\nexclude group: \"org.hamcrest\", module: \"hamcrest-library\"\n}\n- testCompile 'org.mockito:mockito-core:3.3.3'\n+ testCompile 'org.mockito:mockito-core:2.28.2'\ntestCompile \"org.skyscreamer:jsonassert:1.2.3\"\ntestCompile 'com.toomuchcoding.jsonassert:jsonassert:0.4.12'\ntestCompile 'org.awaitility:awaitility:2.0.0'\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Downgrade mockito to a Java 7 compatible version
686,981
10.06.2020 11:59:44
-3,600
0f10f7cdbfff901406afeb9c89df653632de6e41
Add acceptance test for trusting certs in trust store Adds the public certificate from test-keystore to test-truststore.jks/pkcs12 so that a proxy WireMock with test-truststore.pkcs12 as its trust store will trust the certificate from a target WireMock with test-keystore as its keystore.
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -40,6 +40,8 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PASSWORD;\n+import static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PATH;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n@@ -143,6 +145,51 @@ public class HttpsBrowserProxyAcceptanceTest {\nassertThat(testClient.getViaProxy(recordedEndpoint, proxy.port()).content(), is(\"Target response\"));\n}\n+ @Test\n+ public void rejectsUntrustedTarget() {\n+\n+ WireMockServer scepticalProxy = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .enableBrowserProxying(true)\n+ );\n+\n+ try {\n+ scepticalProxy.start();\n+\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ WireMockResponse response = testClient.getViaProxy(target.url(\"/whatever\"), scepticalProxy.port());\n+\n+ assertThat(response.statusCode(), is(500));\n+ } finally {\n+ scepticalProxy.stop();\n+ }\n+ }\n+\n+ @Test\n+ public void trustsTargetIfTrustStoreContainsItsCertificate() {\n+\n+ WireMockServer scepticalProxy = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .enableBrowserProxying(true)\n+ .trustStorePath(TRUST_STORE_PATH)\n+ .trustStorePassword(TRUST_STORE_PASSWORD)\n+ );\n+\n+ try {\n+ scepticalProxy.start();\n+\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ WireMockResponse response = testClient.getViaProxy(target.url(\"/whatever\"), scepticalProxy.port());\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(response.content(), is(\"Got it\"));\n+ } finally {\n+ scepticalProxy.stop();\n+ }\n+ }\n+\nprivate static File setupTempFileRoot() {\ntry {\nFile root = java.nio.file.Files.createTempDirectory(\"wiremock\").toFile();\n" }, { "change_type": "MODIFY", "old_path": "src/test/resources/test-truststore.jks", "new_path": "src/test/resources/test-truststore.jks", "diff": "Binary files a/src/test/resources/test-truststore.jks and b/src/test/resources/test-truststore.jks differ\n" }, { "change_type": "MODIFY", "old_path": "src/test/resources/test-truststore.pkcs12", "new_path": "src/test/resources/test-truststore.pkcs12", "diff": "Binary files a/src/test/resources/test-truststore.pkcs12 and b/src/test/resources/test-truststore.pkcs12 differ\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add acceptance test for trusting certs in trust store Adds the public certificate from test-keystore to test-truststore.jks/pkcs12 so that a proxy WireMock with test-truststore.pkcs12 as its trust store will trust the certificate from a target WireMock with test-keystore as its keystore.
686,981
10.06.2020 12:01:56
-3,600
d66d809ef3373702a337afe6695b9a072960eaa3
Add acceptance test for trusting targets by host name
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -190,6 +190,29 @@ public class HttpsBrowserProxyAcceptanceTest {\n}\n}\n+ @Test\n+ public void canTrustSpecificTargetHosts() {\n+\n+ WireMockServer scepticalProxy = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .enableBrowserProxying(true)\n+ .trustedProxyTargets(\"localhost\")\n+ );\n+\n+ try {\n+ scepticalProxy.start();\n+\n+ target.stubFor(get(urlEqualTo(\"/whatever\")).willReturn(aResponse().withBody(\"Got it\")));\n+\n+ WireMockResponse response = testClient.getViaProxy(target.url(\"/whatever\"), scepticalProxy.port());\n+\n+ assertThat(response.statusCode(), is(200));\n+ assertThat(response.content(), is(\"Got it\"));\n+ } finally {\n+ scepticalProxy.stop();\n+ }\n+ }\n+\nprivate static File setupTempFileRoot() {\ntry {\nFile root = java.nio.file.Files.createTempDirectory(\"wiremock\").toFile();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add acceptance test for trusting targets by host name
686,981
10.06.2020 12:15:40
-3,600
bb9153f4f79490b1e58a806c3674a2d1061cc28e
More detailed documentation of WireMock trust store configuration
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/configuration.md", "new_path": "docs-v2/_docs/configuration.md", "diff": "@@ -86,7 +86,13 @@ WireMock can accept HTTPS connections from clients, require a client to present\n.trustStorePassword(\"trustme\")\n```\n-The client certificate in the trust store defined in the last two options will also be used when proxying to another service that requires a client certificate for authentication.\n+WireMock uses the trust store for three purposes:\n+1. As a server, when requiring client auth, WireMock will trust the client if it\n+ presents a public certificate in this trust store\n+2. As a proxy, WireMock will use the private key & certificate in this key store\n+ to authenticate its http client with target servers that require client auth\n+3. As a proxy, WireMock will trust a target server if it presents a public\n+ certificate in this trust store\n## Proxy settings\n@@ -102,6 +108,12 @@ The client certificate in the trust store defined in the last two options will a\n// When reverse proxying, also route via the specified forward proxy (useful inside corporate firewalls)\n.proxyVia(\"my.corporate.proxy\", 8080)\n+\n+// When proxying, path to a security store containing client private keys and trusted public certificates for communicating with a target server\n+.trustStorePath(\"/path/to/trust-store.jks\")\n+\n+// The password to the trust store\n+.trustStorePassword(\"trustme\")\n```\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -143,8 +143,8 @@ $ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-br\nAdditional trusted public certificates can also be added to the keystore\nspecified via the `--https-truststore`, and should then be trusted without\n-needing the `--trust-proxy-target` parameter (so long as match the requested\n-host).\n+needing the `--trust-proxy-target` parameter (so long as they match the\n+requested host).\nAs WireMock is here running as a man-in-the-middle, the resulting traffic will\nappear to the client encrypted with WireMock's (configurable) private key &\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -44,8 +44,12 @@ certificate.\n`--keystore-password`: Password to the keystore, if something other than\n\"password\".\n-`--https-truststore`: Path to a keystore file containing client\n-certificates. See https and proxy-client-certs for details.\n+`--https-truststore`: Path to a keystore file containing client public\n+certificates, proxy target public certificates & private keys to use when\n+authenticate with a proxy target that require client authentication. See\n+[HTTPS configuration](/docs/configuration/#https-configuration)\n+and [Running as a browser proxy](/docs/proxying#running-as-a-browser-proxy) for\n+details.\n`--truststore-password`: Optional password to the trust store. Defaults\nto \"password\" if not specified.\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
More detailed documentation of WireMock trust store configuration
686,981
11.06.2020 10:09:57
-3,600
d96d6838163b19646624a526ba1e62c6b789861a
Add failing acceptance test for generating certs This test will prove that an http client that trusts a root CA certificate in WireMock's key store will be able to use WireMock as an HTTPS browser proxy to any remote service, because WireMock will serve a certificate signed by that root CA certificate.
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "package com.github.tomakehurst.wiremock;\nimport com.github.tomakehurst.wiremock.common.SingleRootFileSource;\n+import com.github.tomakehurst.wiremock.http.ssl.HostVerifyingSSLSocketFactory;\n+import com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\nimport com.github.tomakehurst.wiremock.junit.WireMockClassRule;\nimport com.github.tomakehurst.wiremock.testsupport.TestFiles;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\n+import org.apache.http.HttpHost;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.conn.DnsResolver;\n+import org.apache.http.conn.ssl.NoopHostnameVerifier;\n+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClients;\n+import org.apache.http.impl.conn.SystemDefaultDnsResolver;\nimport org.eclipse.jetty.client.HttpClient;\nimport org.eclipse.jetty.client.HttpProxy;\nimport org.eclipse.jetty.client.Origin;\n@@ -32,8 +42,15 @@ import org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\n+import javax.net.ssl.SSLContext;\nimport java.io.File;\nimport java.io.IOException;\n+import java.net.InetAddress;\n+import java.net.UnknownHostException;\n+import java.security.KeyManagementException;\n+import java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -47,12 +64,13 @@ import static org.hamcrest.Matchers.is;\npublic class HttpsBrowserProxyAcceptanceTest {\n- private static final String CERTIFICATE_NOT_TRUSTED_BY_TEST_CLIENT = TestFiles.KEY_STORE_PATH;\n+ private static final String TARGET_KEYSTORE_WITH_CUSTOM_CERT = TestFiles.KEY_STORE_PATH;\n+ private static final String PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT = TestFiles.KEY_STORE_WITH_CA_PATH;\n@ClassRule\npublic static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n.httpDisabled(true)\n- .keystorePath(CERTIFICATE_NOT_TRUSTED_BY_TEST_CLIENT)\n+ .keystorePath(TARGET_KEYSTORE_WITH_CUSTOM_CERT)\n.dynamicHttpsPort()\n);\n@@ -72,6 +90,7 @@ public class HttpsBrowserProxyAcceptanceTest {\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n.enableBrowserProxying(true)\n.trustAllProxyTargets(true)\n+ .keystorePath(PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT)\n);\nproxy.start();\n}\n@@ -213,6 +232,43 @@ public class HttpsBrowserProxyAcceptanceTest {\n}\n}\n+ @Test @Ignore(\"not yet implemented\")\n+ public void certificatesSignedWithUsersRootCertificate() throws Exception {\n+\n+ KeyStore trustStore = HttpsAcceptanceTest.readKeyStore(PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT, \"password\");\n+\n+ // given\n+ CloseableHttpClient httpClient = HttpClients.custom()\n+ .setDnsResolver(new CustomLocalTldDnsResolver(\"internal\"))\n+ .setSSLSocketFactory(sslSocketFactoryThatTrusts(trustStore))\n+ .setProxy(new HttpHost(\"localhost\", proxy.port()))\n+ .build();\n+\n+ // when\n+ httpClient.execute(\n+ new HttpGet(\"https://fake1.nowildcards1.internal:\" + target.httpsPort() + \"/whatever\")\n+ );\n+\n+ // then no exception is thrown\n+\n+ // when\n+ httpClient.execute(\n+ new HttpGet(\"https://fake2.nowildcards2.internal:\" + target.httpsPort() + \"/whatever\")\n+ );\n+\n+ // then no exception is thrown\n+ }\n+\n+ private SSLConnectionSocketFactory sslSocketFactoryThatTrusts(KeyStore trustStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {\n+ SSLContext sslContext = SSLContextBuilder.create()\n+ .loadTrustMaterial(trustStore)\n+ .build();\n+ return new SSLConnectionSocketFactory(\n+ new HostVerifyingSSLSocketFactory(sslContext.getSocketFactory()),\n+ new NoopHostnameVerifier() // using Java's hostname verification\n+ );\n+ }\n+\nprivate static File setupTempFileRoot() {\ntry {\nFile root = java.nio.file.Files.createTempDirectory(\"wiremock\").toFile();\n@@ -223,4 +279,23 @@ public class HttpsBrowserProxyAcceptanceTest {\nreturn throwUnchecked(e, File.class);\n}\n}\n+\n+ private static class CustomLocalTldDnsResolver implements DnsResolver {\n+\n+ private final String tldToSendToLocalhost;\n+\n+ public CustomLocalTldDnsResolver(String tldToSendToLocalhost) {\n+ this.tldToSendToLocalhost = tldToSendToLocalhost;\n+ }\n+\n+ @Override\n+ public InetAddress[] resolve(String host) throws UnknownHostException {\n+\n+ if (host.endsWith(\".\" + tldToSendToLocalhost)) {\n+ return new InetAddress[] { InetAddress.getLocalHost() };\n+ } else {\n+ return new SystemDefaultDnsResolver().resolve(host);\n+ }\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/SSLContextBuilder.java", "diff": "@@ -36,6 +36,10 @@ public class SSLContextBuilder {\nreturn new SSLContextBuilder();\n}\n+ public SSLContextBuilder loadTrustMaterial(final KeyStore truststore) throws KeyStoreException, NoSuchAlgorithmException {\n+ return loadTrustMaterial(truststore, null);\n+ }\n+\npublic SSLContextBuilder loadTrustMaterial(\nfinal KeyStore truststore,\nfinal TrustStrategy trustStrategy\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/TestFiles.java", "diff": "@@ -30,6 +30,7 @@ public class TestFiles {\npublic static final String TRUST_STORE_NAME = getTrustStoreRelativeName();\npublic static final String TRUST_STORE_PATH = filePath(TRUST_STORE_NAME);\npublic static final String KEY_STORE_PATH = filePath(\"test-keystore\");\n+ public static final String KEY_STORE_WITH_CA_PATH = filePath(\"test-keystore-with-ca\");\nprivate static String getTrustStoreRelativeName() {\nreturn System.getProperty(\"java.specification.version\").equals(\"1.7\") ?\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java", "diff": "@@ -333,7 +333,7 @@ public class WireMockTestClient {\nreturn SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\n@Override\npublic boolean isTrusted(X509Certificate[] chain, String authType) {\n- return \"CN=Tom Akehurst, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown\".equals(chain[0].getSubjectDN().getName());\n+ return chain[0].getSubjectDN().getName().startsWith(\"CN=Tom Akehurst\");\n}\n}).build();\n} catch (Exception e) {\n" }, { "change_type": "ADD", "old_path": "src/test/resources/test-keystore-with-ca", "new_path": "src/test/resources/test-keystore-with-ca", "diff": "Binary files /dev/null and b/src/test/resources/test-keystore-with-ca differ\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add failing acceptance test for generating certs This test will prove that an http client that trusts a root CA certificate in WireMock's key store will be able to use WireMock as an HTTPS browser proxy to any remote service, because WireMock will serve a certificate signed by that root CA certificate.
686,981
11.06.2020 17:51:47
-3,600
7da7bfbbd3773c13ab14343a69e2e3114cf21cb8
Set SAN on the generated certificates Modern browsers only trust a certificate if the Subject Alternative Names (rather than the CN) contains the requested host.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -2,6 +2,11 @@ package com.github.tomakehurst.wiremock.http.ssl;\nimport sun.security.tools.keytool.CertAndKeyGen;\nimport sun.security.util.HostnameChecker;\n+import sun.security.x509.CertificateExtensions;\n+import sun.security.x509.DNSName;\n+import sun.security.x509.GeneralName;\n+import sun.security.x509.GeneralNames;\n+import sun.security.x509.SubjectAlternativeNameExtension;\nimport sun.security.x509.X500Name;\nimport sun.security.x509.X509CertImpl;\nimport sun.security.x509.X509CertInfo;\n@@ -29,6 +34,7 @@ import java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\nimport java.util.Collections;\n+import java.util.Date;\nimport java.util.Enumeration;\nimport java.util.List;\n@@ -214,7 +220,13 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nCertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\"+keyType, null);\nnewCertAndKey.generate(2048);\nPrivateKey newKey = newCertAndKey.getPrivateKey();\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(new X500Name(\"CN=\" + requestedNameString), (long) 365 * 24 * 60 * 60);\n+\n+ X509Certificate certificate = newCertAndKey.getSelfCertificate(\n+ new X500Name(\"CN=\" + requestedNameString),\n+ new Date(),\n+ (long) 365 * 24 * 60 * 60,\n+ subjectAlternativeName(requestedNameString)\n+ );\nCertChainAndKey authority = findExistingCertificateAuthority();\nif (authority != null) {\n@@ -237,6 +249,17 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n+ private CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\n+ GeneralName name = new GeneralName(new DNSName(requestedNameString));\n+ GeneralNames names = new GeneralNames();\n+ names.add(name);\n+ SubjectAlternativeNameExtension subjectAlternativeNameExtension = new SubjectAlternativeNameExtension(names);\n+\n+ CertificateExtensions extensions = new CertificateExtensions();\n+ extensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);\n+ return extensions;\n+ }\n+\nprivate CertChainAndKey findExistingCertificateAuthority() {\nEnumeration<String> aliases;\ntry {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Set SAN on the generated certificates Modern browsers only trust a certificate if the Subject Alternative Names (rather than the CN) contains the requested host.
686,981
12.06.2020 10:05:46
-3,600
b0b635a7223dd9596645031cb2648cdf14722a14
Move risky compile options into java8 module These compile options are needed to make it possible to compile against `sun.security.tools.keytool`. Forking the logic in `sun.security.tools.keytool.CertAndKeyGen` would allow getting rid of most of these options.
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -139,14 +139,6 @@ allprojects {\noptions.compilerArgs += '-XDenableSunApiLintControl'\n}\n- compileJava {\n- options.encoding = 'UTF-8'\n- options.fork = true\n- options.forkOptions.executable = 'javac'\n- options.compilerArgs += '-XDenableSunApiLintControl'\n- options.compilerArgs += '-XDignore.symbol.file'\n- }\n-\ntest {\n// Set the timezone for testing somewhere other than my machine to increase the chances of catching timezone bugs\nsystemProperty 'user.timezone', 'Australia/Sydney'\n" }, { "change_type": "MODIFY", "old_path": "java8/build.gradle", "new_path": "java8/build.gradle", "diff": "@@ -16,3 +16,15 @@ dependencies {\ntestCompile \"org.eclipse.jetty:jetty-client:$jettyVersion\"\ntestCompile \"org.eclipse.jetty.http2:http2-http-client-transport:$jettyVersion\"\n}\n+\n+compileJava {\n+ options.encoding = 'UTF-8'\n+\n+ // silences warnings about compiling against `sun` packages\n+ options.compilerArgs += '-XDenableSunApiLintControl'\n+\n+ // makes it possible to compile against `sun.security.tools.keytool`\n+ options.fork = true\n+ options.forkOptions.executable = 'javac'\n+ options.compilerArgs += '-XDignore.symbol.file'\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Move risky compile options into java8 module These compile options are needed to make it possible to compile against `sun.security.tools.keytool`. Forking the logic in `sun.security.tools.keytool.CertAndKeyGen` would allow getting rid of most of these options.
686,981
12.06.2020 10:06:36
-3,600
72f3f1819f675c93fcd54a331f24e17a9eba9bd5
Quieten sun api warnings
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -40,6 +40,7 @@ import java.util.List;\nimport static java.util.Collections.emptyList;\n+@SuppressWarnings(\"sunapi\")\npublic class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509ExtendedKeyManager {\nprivate final KeyStore keyStore;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Quieten sun api warnings
686,981
12.06.2020 10:41:09
-3,600
0bae9f3808f337b046280023142ddcbc5f23b081
Group related methods together
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -52,39 +52,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nthis.password = keyPassword;\n}\n- @Override\n- public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {\n- String defaultAlias = super.chooseServerAlias(keyType, issuers, socket);\n- ExtendedSSLSession handshakeSession = getHandshakeSession(socket);\n- return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n- }\n-\n- private ExtendedSSLSession getHandshakeSession(Socket socket) {\n- if (socket instanceof SSLSocket) {\n- SSLSocket sslSocket = (SSLSocket) socket;\n- SSLSession sslSession = getHandshakeSessionIfSupported(sslSocket);\n- return getHandshakeSession(sslSession);\n- } else {\n- return null;\n- }\n- }\n-\n- private SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {\n- try {\n- return sslSocket.getHandshakeSession();\n- } catch (UnsupportedOperationException e) {\n- // TODO log that dynamically generating is not supported\n- return null;\n- }\n- }\n-\n- @Override\n- public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {\n- String defaultAlias = super.chooseEngineServerAlias(keyType, issuers, engine);\n- ExtendedSSLSession handshakeSession = getHandshakeSession(engine);\n- return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n- }\n-\n@Override\npublic PrivateKey getPrivateKey(String alias) {\nPrivateKey original = super.getPrivateKey(alias);\n@@ -138,6 +105,40 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn result;\n}\n+\n+ @Override\n+ public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {\n+ String defaultAlias = super.chooseServerAlias(keyType, issuers, socket);\n+ ExtendedSSLSession handshakeSession = getHandshakeSession(socket);\n+ return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n+ }\n+\n+ private ExtendedSSLSession getHandshakeSession(Socket socket) {\n+ if (socket instanceof SSLSocket) {\n+ SSLSocket sslSocket = (SSLSocket) socket;\n+ SSLSession sslSession = getHandshakeSessionIfSupported(sslSocket);\n+ return getHandshakeSession(sslSession);\n+ } else {\n+ return null;\n+ }\n+ }\n+\n+ private SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {\n+ try {\n+ return sslSocket.getHandshakeSession();\n+ } catch (UnsupportedOperationException e) {\n+ // TODO log that dynamically generating is not supported\n+ return null;\n+ }\n+ }\n+\n+ @Override\n+ public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {\n+ String defaultAlias = super.chooseEngineServerAlias(keyType, issuers, engine);\n+ ExtendedSSLSession handshakeSession = getHandshakeSession(engine);\n+ return tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n+ }\n+\nprivate ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {\nSSLSession sslSession = getHandshakeSessionIfSupported(sslEngine);\nreturn getHandshakeSession(sslSession);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Group related methods together
686,981
12.06.2020 10:46:41
-3,600
87cec52d0638445cffbbf77fc3d480b8acbee77c
Make private methods static Marks them as not needing to be on this class
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -93,7 +93,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private boolean areX509Certificates(Certificate[] fromKeyStore) {\n+ private static boolean areX509Certificates(Certificate[] fromKeyStore) {\nreturn fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;\n}\n@@ -113,7 +113,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n}\n- private ExtendedSSLSession getHandshakeSession(Socket socket) {\n+ private static ExtendedSSLSession getHandshakeSession(Socket socket) {\nif (socket instanceof SSLSocket) {\nSSLSocket sslSocket = (SSLSocket) socket;\nSSLSession sslSession = getHandshakeSessionIfSupported(sslSocket);\n@@ -123,7 +123,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {\n+ private static SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {\ntry {\nreturn sslSocket.getHandshakeSession();\n} catch (UnsupportedOperationException e) {\n@@ -139,12 +139,12 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n}\n- private ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {\n+ private static ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {\nSSLSession sslSession = getHandshakeSessionIfSupported(sslEngine);\nreturn getHandshakeSession(sslSession);\n}\n- private SSLSession getHandshakeSessionIfSupported(SSLEngine sslEngine) {\n+ private static SSLSession getHandshakeSessionIfSupported(SSLEngine sslEngine) {\ntry {\nreturn sslEngine.getHandshakeSession();\n} catch (UnsupportedOperationException | NullPointerException e) {\n@@ -153,7 +153,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private ExtendedSSLSession getHandshakeSession(SSLSession handshakeSession) {\n+ private static ExtendedSSLSession getHandshakeSession(SSLSession handshakeSession) {\nif (handshakeSession instanceof ExtendedSSLSession) {\nreturn (ExtendedSSLSession) handshakeSession;\n} else {\n@@ -188,7 +188,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {\n+ private static List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {\nList<SNIServerName> requestedServerNames = getRequestedServerNames(handshakeSession);\nList<SNIHostName> requestedHostNames = new ArrayList<>(requestedServerNames.size());\nfor (SNIServerName serverName: requestedServerNames) {\n@@ -199,7 +199,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn requestedHostNames;\n}\n- private List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {\n+ private static List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {\ntry {\nreturn handshakeSession.getRequestedServerNames();\n} catch (UnsupportedOperationException e) {\n@@ -268,7 +268,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\n+ private static CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\nGeneralName name = new GeneralName(new DNSName(requestedNameString));\nGeneralNames names = new GeneralNames();\nnames.add(name);\n@@ -305,7 +305,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private boolean isCertificateAuthority(X509Certificate certificate) {\n+ private static boolean isCertificateAuthority(X509Certificate certificate) {\nboolean[] keyUsage = certificate.getKeyUsage();\nreturn keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n}\n@@ -339,7 +339,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn null;\n}\n- private boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\n+ private static boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\nfor (SNIHostName serverName : requestedServerNames) {\nif (matches(x509Certificate, serverName)) {\nreturn true;\n@@ -348,7 +348,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn false;\n}\n- private boolean matches(X509Certificate x509Certificate, SNIHostName hostName) {\n+ private static boolean matches(X509Certificate x509Certificate, SNIHostName hostName) {\ntry {\nHostnameChecker instance = HostnameChecker.getInstance(HostnameChecker.TYPE_TLS);\ninstance.match(hostName.getAsciiName(), x509Certificate);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Make private methods static Marks them as not needing to be on this class
686,981
12.06.2020 11:06:11
-3,600
e0e085a3071e5d6c2467cc37ffd35d569c1593cc
Move existingCertificateAuthority to be a field
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -45,21 +45,19 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate final KeyStore keyStore;\nprivate final char[] password;\n+ private final CertChainAndKey existingCertificateAuthority;\npublic CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) {\nsuper(keyManager);\nthis.keyStore = keyStore;\nthis.password = keyPassword;\n+ existingCertificateAuthority = findExistingCertificateAuthority();\n}\n@Override\npublic PrivateKey getPrivateKey(String alias) {\nPrivateKey original = super.getPrivateKey(alias);\n- if (original == null) {\n- return getDynamicPrivateKey(alias);\n- } else {\n- return original;\n- }\n+ return original == null ? getDynamicPrivateKey(alias) : original;\n}\nprivate PrivateKey getDynamicPrivateKey(String alias) {\n@@ -247,10 +245,9 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nsubjectAlternativeName(requestedNameString)\n);\n- CertChainAndKey authority = findExistingCertificateAuthority();\n- if (authority != null) {\n- X509Certificate[] signingChain = authority.certificateChain;\n- PrivateKey signingKey = authority.key;\n+ if (existingCertificateAuthority != null) {\n+ X509Certificate[] signingChain = existingCertificateAuthority.certificateChain;\n+ PrivateKey signingKey = existingCertificateAuthority.key;\nX509Certificate signed = createSignedCertificate(certificate, signingChain[0], signingKey);\nX509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];\n@@ -292,7 +289,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nif (key != null) return key;\n}\nreturn null;\n-\n}\nprivate CertChainAndKey getCertChainAndKey(String alias) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Move existingCertificateAuthority to be a field
686,981
12.06.2020 11:16:54
-3,600
78c5b80c044627f04a2f76421674426d05195627
Move check for existingCertificateAuthority being null up Start pulling apart `generateCertificate` - it has too many responsibilities
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -165,7 +165,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n* @param handshakeSession nullable\n*/\nprivate String tryToChooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {\n- if (defaultAlias != null && handshakeSession != null) {\n+ if (defaultAlias != null && handshakeSession != null && existingCertificateAuthority != null) {\nreturn chooseServerAlias(keyType, defaultAlias, handshakeSession);\n} else {\nreturn defaultAlias;\n@@ -245,7 +245,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nsubjectAlternativeName(requestedNameString)\n);\n- if (existingCertificateAuthority != null) {\nX509Certificate[] signingChain = existingCertificateAuthority.certificateChain;\nPrivateKey signingKey = existingCertificateAuthority.key;\n@@ -256,9 +255,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nkeyStore.setKeyEntry(requestedNameString, newKey, password, fullChain);\nreturn requestedNameString;\n- } else {\n- return defaultAlias;\n- }\n} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | IOException | SignatureException e) {\n// TODO log?\nreturn defaultAlias;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Move check for existingCertificateAuthority being null up Start pulling apart `generateCertificate` - it has too many responsibilities
686,981
12.06.2020 11:27:57
-3,600
25ff6cbcda9453ccfd9a8bf3b0747c33e0650bfd
Split concerns of `generateCertificate` Between: * generating the certificate * putting it in a keystore and * returning the default alias if it all goes wrong
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -216,24 +216,36 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nif (matches(certificateChain[0], requestedServerNames)) {\nreturn defaultAlias;\n} else {\n- return generateCertificate(keyType, defaultAlias, requestedServerNames.get(0));\n+ try {\n+ return generateCertificate(keyType, requestedServerNames.get(0));\n+ } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | IOException | SignatureException e) {\n+ // TODO log?\n+ return defaultAlias;\n+ }\n}\n}\n/**\n* @param keyType non null, guaranteed to be valid\n- * @param defaultAlias non null, guaranteed to match a private key entry\n* @param requestedServerName non null\n* @return an alias to a new private key & certificate for the first requested server name\n*/\nprivate String generateCertificate(\nString keyType,\n- String defaultAlias,\nSNIHostName requestedServerName\n- ) {\n- try {\n+ ) throws CertificateException, NoSuchAlgorithmException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\nString requestedNameString = requestedServerName.getAsciiName();\n+ CertChainAndKey newCertChainAndKey = generateCertificate(keyType, requestedNameString);\n+\n+ keyStore.setKeyEntry(requestedNameString, newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\n+ return requestedNameString;\n+ }\n+\n+ private CertChainAndKey generateCertificate(\n+ String keyType,\n+ String requestedNameString\n+ ) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException, IOException {\nCertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\"+keyType, null);\nnewCertAndKey.generate(2048);\nPrivateKey newKey = newCertAndKey.getPrivateKey();\n@@ -252,13 +264,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nX509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];\nfullChain[0] = signed;\nSystem.arraycopy(signingChain, 0, fullChain, 1, signingChain.length);\n-\n- keyStore.setKeyEntry(requestedNameString, newKey, password, fullChain);\n- return requestedNameString;\n- } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | IOException | SignatureException e) {\n- // TODO log?\n- return defaultAlias;\n- }\n+ return new CertChainAndKey(fullChain, newKey);\n}\nprivate static CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Split concerns of `generateCertificate` Between: * generating the certificate * putting it in a keystore and * returning the default alias if it all goes wrong
686,981
12.06.2020 11:33:18
-3,600
5399b1331697ea4449230fe9d4444e6a4e04a7c1
Move CertChainAndKey to upper level
[ { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertChainAndKey.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import java.security.PrivateKey;\n+import java.security.cert.X509Certificate;\n+\n+class CertChainAndKey {\n+ final X509Certificate[] certificateChain;\n+ final PrivateKey key;\n+\n+ CertChainAndKey(X509Certificate[] certificateChain, PrivateKey key) {\n+ this.certificateChain = certificateChain;\n+ this.key = key;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -308,16 +308,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n}\n- private static class CertChainAndKey {\n- private final X509Certificate[] certificateChain;\n- private final PrivateKey key;\n-\n- private CertChainAndKey(X509Certificate[] certificateChain, PrivateKey key) {\n- this.certificateChain = certificateChain;\n- this.key = key;\n- }\n- }\n-\nprivate static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) {\ntry {\nPrincipal issuer = issuerCertificate.getSubjectDN();\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Move CertChainAndKey to upper level
686,981
12.06.2020 11:40:08
-3,600
0dfa729c4243c7703160a5994db2077540300b01
Extract a CertificateAuthority class To encapsulate generating new signed certificates
[ { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import sun.security.tools.keytool.CertAndKeyGen;\n+import sun.security.x509.CertificateExtensions;\n+import sun.security.x509.DNSName;\n+import sun.security.x509.GeneralName;\n+import sun.security.x509.GeneralNames;\n+import sun.security.x509.SubjectAlternativeNameExtension;\n+import sun.security.x509.X500Name;\n+import sun.security.x509.X509CertImpl;\n+import sun.security.x509.X509CertInfo;\n+\n+import java.io.IOException;\n+import java.security.InvalidKeyException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.NoSuchProviderException;\n+import java.security.Principal;\n+import java.security.PrivateKey;\n+import java.security.SignatureException;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.Date;\n+\n+import static java.util.Objects.requireNonNull;\n+\n+class CertificateAuthority {\n+\n+ private final X509Certificate[] certificateChain;\n+ private final PrivateKey key;\n+\n+ CertificateAuthority(X509Certificate[] certificateChain, PrivateKey key) {\n+ this.certificateChain = requireNonNull(certificateChain);\n+ if (certificateChain.length == 0) {\n+ throw new IllegalArgumentException(\"Chain must have entries\");\n+ }\n+ this.key = requireNonNull(key);\n+ }\n+\n+ CertChainAndKey generateCertificate(\n+ String keyType,\n+ String requestedNameString\n+ ) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException, IOException {\n+ CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\"+keyType, null);\n+ newCertAndKey.generate(2048);\n+ PrivateKey newKey = newCertAndKey.getPrivateKey();\n+\n+ X509Certificate certificate = newCertAndKey.getSelfCertificate(\n+ new X500Name(\"CN=\" + requestedNameString),\n+ new Date(),\n+ (long) 365 * 24 * 60 * 60,\n+ subjectAlternativeName(requestedNameString)\n+ );\n+\n+ X509Certificate[] signingChain = certificateChain;\n+ PrivateKey signingKey = key;\n+\n+ X509Certificate signed = createSignedCertificate(certificate, signingChain[0], signingKey);\n+ X509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];\n+ fullChain[0] = signed;\n+ System.arraycopy(signingChain, 0, fullChain, 1, signingChain.length);\n+ return new CertChainAndKey(fullChain, newKey);\n+ }\n+\n+ private static CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\n+ GeneralName name = new GeneralName(new DNSName(requestedNameString));\n+ GeneralNames names = new GeneralNames();\n+ names.add(name);\n+ SubjectAlternativeNameExtension subjectAlternativeNameExtension = new SubjectAlternativeNameExtension(names);\n+\n+ CertificateExtensions extensions = new CertificateExtensions();\n+ extensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);\n+ return extensions;\n+ }\n+\n+ private static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) {\n+ try {\n+ Principal issuer = issuerCertificate.getSubjectDN();\n+ String issuerSigAlg = issuerCertificate.getSigAlgName();\n+\n+ byte[] inCertBytes = certificate.getTBSCertificate();\n+ X509CertInfo info = new X509CertInfo(inCertBytes);\n+ info.set(X509CertInfo.ISSUER, issuer);\n+\n+ X509CertImpl outCert = new X509CertImpl(info);\n+ outCert.sign(issuerPrivateKey, issuerSigAlg);\n+\n+ return outCert;\n+ } catch (Exception ex) {\n+ // TODO log failure to generate certificate\n+ }\n+ return null;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import sun.security.tools.keytool.CertAndKeyGen;\nimport sun.security.util.HostnameChecker;\n-import sun.security.x509.CertificateExtensions;\n-import sun.security.x509.DNSName;\n-import sun.security.x509.GeneralName;\n-import sun.security.x509.GeneralNames;\n-import sun.security.x509.SubjectAlternativeNameExtension;\n-import sun.security.x509.X500Name;\n-import sun.security.x509.X509CertImpl;\n-import sun.security.x509.X509CertInfo;\nimport javax.net.ssl.ExtendedSSLSession;\nimport javax.net.ssl.SNIHostName;\n@@ -34,7 +25,6 @@ import java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\nimport java.util.Collections;\n-import java.util.Date;\nimport java.util.Enumeration;\nimport java.util.List;\n@@ -45,7 +35,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate final KeyStore keyStore;\nprivate final char[] password;\n- private final CertChainAndKey existingCertificateAuthority;\n+ private final CertificateAuthority existingCertificateAuthority;\npublic CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) {\nsuper(keyManager);\n@@ -236,49 +226,13 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n) throws CertificateException, NoSuchAlgorithmException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\nString requestedNameString = requestedServerName.getAsciiName();\n- CertChainAndKey newCertChainAndKey = generateCertificate(keyType, requestedNameString);\n+ CertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedNameString);\nkeyStore.setKeyEntry(requestedNameString, newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\nreturn requestedNameString;\n}\n- private CertChainAndKey generateCertificate(\n- String keyType,\n- String requestedNameString\n- ) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException, IOException {\n- CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\"+keyType, null);\n- newCertAndKey.generate(2048);\n- PrivateKey newKey = newCertAndKey.getPrivateKey();\n-\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(\n- new X500Name(\"CN=\" + requestedNameString),\n- new Date(),\n- (long) 365 * 24 * 60 * 60,\n- subjectAlternativeName(requestedNameString)\n- );\n-\n- X509Certificate[] signingChain = existingCertificateAuthority.certificateChain;\n- PrivateKey signingKey = existingCertificateAuthority.key;\n-\n- X509Certificate signed = createSignedCertificate(certificate, signingChain[0], signingKey);\n- X509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];\n- fullChain[0] = signed;\n- System.arraycopy(signingChain, 0, fullChain, 1, signingChain.length);\n- return new CertChainAndKey(fullChain, newKey);\n- }\n-\n- private static CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\n- GeneralName name = new GeneralName(new DNSName(requestedNameString));\n- GeneralNames names = new GeneralNames();\n- names.add(name);\n- SubjectAlternativeNameExtension subjectAlternativeNameExtension = new SubjectAlternativeNameExtension(names);\n-\n- CertificateExtensions extensions = new CertificateExtensions();\n- extensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);\n- return extensions;\n- }\n-\n- private CertChainAndKey findExistingCertificateAuthority() {\n+ private CertificateAuthority findExistingCertificateAuthority() {\nEnumeration<String> aliases;\ntry {\naliases = keyStore.aliases();\n@@ -287,17 +241,17 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\nwhile (aliases.hasMoreElements()) {\nString alias = aliases.nextElement();\n- CertChainAndKey key = getCertChainAndKey(alias);\n+ CertificateAuthority key = getCertChainAndKey(alias);\nif (key != null) return key;\n}\nreturn null;\n}\n- private CertChainAndKey getCertChainAndKey(String alias) {\n+ private CertificateAuthority getCertChainAndKey(String alias) {\nX509Certificate[] chain = getCertificateChain(alias);\nPrivateKey key = getPrivateKey(alias);\nif (isCertificateAuthority(chain[0]) && key != null) {\n- return new CertChainAndKey(chain, key);\n+ return new CertificateAuthority(chain, key);\n} else {\nreturn null;\n}\n@@ -308,25 +262,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n}\n- private static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) {\n- try {\n- Principal issuer = issuerCertificate.getSubjectDN();\n- String issuerSigAlg = issuerCertificate.getSigAlgName();\n-\n- byte[] inCertBytes = certificate.getTBSCertificate();\n- X509CertInfo info = new X509CertInfo(inCertBytes);\n- info.set(X509CertInfo.ISSUER, issuer);\n-\n- X509CertImpl outCert = new X509CertImpl(info);\n- outCert.sign(issuerPrivateKey, issuerSigAlg);\n-\n- return outCert;\n- } catch (Exception ex) {\n- // TODO log failure to generate certificate\n- }\n- return null;\n- }\n-\nprivate static boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\nfor (SNIHostName serverName : requestedServerNames) {\nif (matches(x509Certificate, serverName)) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Extract a CertificateAuthority class To encapsulate generating new signed certificates
686,981
12.06.2020 11:42:38
-3,600
8d11b437824f0ba7ce96cd7c136a94cfd234198e
Simplify CertificateAuthority
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -52,9 +52,8 @@ class CertificateAuthority {\n);\nX509Certificate[] signingChain = certificateChain;\n- PrivateKey signingKey = key;\n- X509Certificate signed = createSignedCertificate(certificate, signingChain[0], signingKey);\n+ X509Certificate signed = sign(certificate);\nX509Certificate[] fullChain = new X509Certificate[signingChain.length + 1];\nfullChain[0] = signed;\nSystem.arraycopy(signingChain, 0, fullChain, 1, signingChain.length);\n@@ -72,8 +71,9 @@ class CertificateAuthority {\nreturn extensions;\n}\n- private static X509Certificate createSignedCertificate(X509Certificate certificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) {\n+ private X509Certificate sign(X509Certificate certificate) {\ntry {\n+ X509Certificate issuerCertificate = certificateChain[0];\nPrincipal issuer = issuerCertificate.getSubjectDN();\nString issuerSigAlg = issuerCertificate.getSigAlgName();\n@@ -82,7 +82,7 @@ class CertificateAuthority {\ninfo.set(X509CertInfo.ISSUER, issuer);\nX509CertImpl outCert = new X509CertImpl(info);\n- outCert.sign(issuerPrivateKey, issuerSigAlg);\n+ outCert.sign(key, issuerSigAlg);\nreturn outCert;\n} catch (Exception ex) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Simplify CertificateAuthority
686,981
12.06.2020 12:08:00
-3,600
a672379693b24b6f26dd7bcd059aa1d2e344d513
Simplify array prepending and exception handling
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -21,6 +21,8 @@ import java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.Date;\n+import static com.github.tomakehurst.wiremock.common.ArrayFunctions.prepend;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.util.Objects.requireNonNull;\nclass CertificateAuthority {\n@@ -39,26 +41,34 @@ class CertificateAuthority {\nCertChainAndKey generateCertificate(\nString keyType,\nString requestedNameString\n- ) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException, IOException {\n+ ) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException {\nCertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\"+keyType, null);\nnewCertAndKey.generate(2048);\nPrivateKey newKey = newCertAndKey.getPrivateKey();\nX509Certificate certificate = newCertAndKey.getSelfCertificate(\n- new X500Name(\"CN=\" + requestedNameString),\n+ x500Name(requestedNameString),\nnew Date(),\n(long) 365 * 24 * 60 * 60,\nsubjectAlternativeName(requestedNameString)\n);\nX509Certificate signed = sign(certificate);\n- X509Certificate[] fullChain = new X509Certificate[certificateChain.length + 1];\n- fullChain[0] = signed;\n- System.arraycopy(certificateChain, 0, fullChain, 1, certificateChain.length);\n+ X509Certificate[] fullChain = prepend(signed, certificateChain);\nreturn new CertChainAndKey(fullChain, newKey);\n}\n- private static CertificateExtensions subjectAlternativeName(String requestedNameString) throws IOException {\n+ private X500Name x500Name(String requestedNameString) {\n+ try {\n+ return new X500Name(\"CN=\" + requestedNameString);\n+ } catch (IOException e) {\n+ // it's an in memory op, should be impossible...\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private static CertificateExtensions subjectAlternativeName(String requestedNameString) {\n+ try {\nGeneralName name = new GeneralName(new DNSName(requestedNameString));\nGeneralNames names = new GeneralNames();\nnames.add(name);\n@@ -67,25 +77,28 @@ class CertificateAuthority {\nCertificateExtensions extensions = new CertificateExtensions();\nextensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);\nreturn extensions;\n+ } catch (IOException e) {\n+ // it's an in memory op, should be impossible...\n+ return throwUnchecked(e, null);\n+ }\n}\n- private X509Certificate sign(X509Certificate certificate) {\n- try {\n+ private X509Certificate sign(X509Certificate certificate) throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {\nX509Certificate issuerCertificate = certificateChain[0];\nPrincipal issuer = issuerCertificate.getSubjectDN();\nString issuerSigAlg = issuerCertificate.getSigAlgName();\nbyte[] inCertBytes = certificate.getTBSCertificate();\nX509CertInfo info = new X509CertInfo(inCertBytes);\n+ try {\ninfo.set(X509CertInfo.ISSUER, issuer);\n+ } catch (IOException e) {\n+ return throwUnchecked(e, null);\n+ }\nX509CertImpl outCert = new X509CertImpl(info);\noutCert.sign(key, issuerSigAlg);\nreturn outCert;\n- } catch (Exception ex) {\n- // TODO log failure to generate certificate\n- }\n- return null;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -9,7 +9,6 @@ import javax.net.ssl.SSLEngine;\nimport javax.net.ssl.SSLSession;\nimport javax.net.ssl.SSLSocket;\nimport javax.net.ssl.X509ExtendedKeyManager;\n-import java.io.IOException;\nimport java.net.Socket;\nimport java.security.InvalidKeyException;\nimport java.security.KeyStore;\n@@ -208,7 +207,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n} else {\ntry {\nreturn generateCertificate(keyType, requestedServerNames.get(0));\n- } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | IOException | SignatureException e) {\n+ } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {\n// TODO log?\nreturn defaultAlias;\n}\n@@ -223,7 +222,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate String generateCertificate(\nString keyType,\nSNIHostName requestedServerName\n- ) throws CertificateException, NoSuchAlgorithmException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n+ ) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\nString requestedNameString = requestedServerName.getAsciiName();\nCertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedNameString);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ArrayFunctions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ArrayFunctions.java", "diff": "package com.github.tomakehurst.wiremock.common;\n+import java.lang.reflect.Array;\n+\nimport static java.util.Arrays.copyOf;\npublic final class ArrayFunctions {\n@@ -13,6 +15,14 @@ public final class ArrayFunctions {\nreturn both;\n}\n+ public static <T> T[] prepend(T t, T[] original) {\n+ @SuppressWarnings(\"unchecked\")\n+ T[] newArray = (T[]) Array.newInstance(original.getClass().getComponentType(), original.length + 1);\n+ newArray[0]= t;\n+ System.arraycopy(original, 0, newArray, 1, original.length);\n+ return newArray;\n+ }\n+\nprivate ArrayFunctions() {\nthrow new UnsupportedOperationException(\"not instantiable\");\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/ArrayFunctionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ArrayFunctionsTest.java", "diff": "@@ -3,6 +3,7 @@ package com.github.tomakehurst.wiremock.common;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.common.ArrayFunctions.concat;\n+import static com.github.tomakehurst.wiremock.common.ArrayFunctions.prepend;\nimport static org.junit.Assert.*;\npublic class ArrayFunctionsTest {\n@@ -48,4 +49,37 @@ public class ArrayFunctionsTest {\nsecond[0] = 30;\nassertArrayEquals(new Integer[] { 1, 2, 3, 4 }, result);\n}\n+\n+ @Test\n+ public void prependNullAndEmpty() {\n+ assertArrayEquals(new Integer[] { null }, prepend(null, empty));\n+ }\n+\n+ @Test\n+ public void prependSomeAndEmpty() {\n+ Integer[] result = prepend(1, empty);\n+ assertArrayEquals(new Integer[] { 1 }, result);\n+ }\n+\n+ @Test\n+ public void prependNullAndNonEmpty() {\n+ Integer[] second = {1, 2};\n+\n+ Integer[] result = prepend(null, second);\n+ assertArrayEquals(new Integer[] { null, 1, 2 }, result);\n+\n+ second[0] = 10;\n+ assertArrayEquals(new Integer[] { null, 1, 2 }, result);\n+ }\n+\n+ @Test\n+ public void prependSomeAndNonEmpty() {\n+ Integer[] second = {2, 3};\n+\n+ Integer[] result = prepend(1, second);\n+ assertArrayEquals(new Integer[] { 1, 2, 3 }, result);\n+\n+ second[0] = 30;\n+ assertArrayEquals(new Integer[] { 1, 2, 3 }, result);\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Simplify array prepending and exception handling
686,981
12.06.2020 12:33:30
-3,600
7163aa766e54f65e770a588ec35b8770db00ce31
Better exception handling logic
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -10,6 +10,7 @@ import sun.security.x509.X500Name;\nimport sun.security.x509.X509CertImpl;\nimport sun.security.x509.X509CertInfo;\n+import javax.net.ssl.SNIHostName;\nimport java.io.IOException;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\n@@ -25,6 +26,7 @@ import static com.github.tomakehurst.wiremock.common.ArrayFunctions.prepend;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.util.Objects.requireNonNull;\n+@SuppressWarnings(\"sunapi\")\nclass CertificateAuthority {\nprivate final X509Certificate[] certificateChain;\n@@ -40,17 +42,17 @@ class CertificateAuthority {\nCertChainAndKey generateCertificate(\nString keyType,\n- String requestedNameString\n+ SNIHostName hostName\n) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException {\nCertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\"+keyType, null);\nnewCertAndKey.generate(2048);\nPrivateKey newKey = newCertAndKey.getPrivateKey();\nX509Certificate certificate = newCertAndKey.getSelfCertificate(\n- x500Name(requestedNameString),\n+ x500Name(hostName),\nnew Date(),\n(long) 365 * 24 * 60 * 60,\n- subjectAlternativeName(requestedNameString)\n+ subjectAlternativeName(hostName)\n);\nX509Certificate signed = sign(certificate);\n@@ -58,24 +60,23 @@ class CertificateAuthority {\nreturn new CertChainAndKey(fullChain, newKey);\n}\n- private X500Name x500Name(String requestedNameString) {\n+ private X500Name x500Name(SNIHostName hostName) {\ntry {\n- return new X500Name(\"CN=\" + requestedNameString);\n+ return new X500Name(\"CN=\" + hostName.getAsciiName());\n} catch (IOException e) {\n- // it's an in memory op, should be impossible...\n+ // X500Name throws IOException for a parse error (which isn't an IO problem...)\n+ // An SNIHostName should be guaranteed not to have a parse issue\nreturn throwUnchecked(e, null);\n}\n}\n- private static CertificateExtensions subjectAlternativeName(String requestedNameString) {\n- try {\n- GeneralName name = new GeneralName(new DNSName(requestedNameString));\n+ private static CertificateExtensions subjectAlternativeName(SNIHostName hostName) {\n+ GeneralName name = new GeneralName(dnsName(hostName));\nGeneralNames names = new GeneralNames();\nnames.add(name);\n- SubjectAlternativeNameExtension subjectAlternativeNameExtension = new SubjectAlternativeNameExtension(names);\n-\n+ try {\nCertificateExtensions extensions = new CertificateExtensions();\n- extensions.set(SubjectAlternativeNameExtension.NAME, subjectAlternativeNameExtension);\n+ extensions.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(names));\nreturn extensions;\n} catch (IOException e) {\n// it's an in memory op, should be impossible...\n@@ -83,6 +84,16 @@ class CertificateAuthority {\n}\n}\n+ private static DNSName dnsName(SNIHostName name) {\n+ try {\n+ return new DNSName(name.getAsciiName());\n+ } catch (IOException e) {\n+ // DNSName throws IOException for a parse error (which isn't an IO problem...)\n+ // An SNIHostName should be guaranteed not to have a parse issue\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\nprivate X509Certificate sign(X509Certificate certificate) throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {\nX509Certificate issuerCertificate = certificateChain[0];\nPrincipal issuer = issuerCertificate.getSubjectDN();\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -223,10 +223,10 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nString keyType,\nSNIHostName requestedServerName\n) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n- String requestedNameString = requestedServerName.getAsciiName();\n- CertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedNameString);\n+ CertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedServerName);\n+ String requestedNameString = requestedServerName.getAsciiName();\nkeyStore.setKeyEntry(requestedNameString, newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\nreturn requestedNameString;\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Better exception handling logic
686,981
12.06.2020 13:56:13
-3,600
84f250839fa60f81059994a62ee50833be5fc5fb
Extract DynamicKeyStore To encapsulate a Key Store that can add new certificates to itself
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -18,13 +18,9 @@ import java.security.NoSuchProviderException;\nimport java.security.Principal;\nimport java.security.PrivateKey;\nimport java.security.SignatureException;\n-import java.security.UnrecoverableKeyException;\n-import java.security.cert.Certificate;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.ArrayList;\n-import java.util.Collections;\n-import java.util.Enumeration;\nimport java.util.List;\nimport static java.util.Collections.emptyList;\n@@ -32,67 +28,29 @@ import static java.util.Collections.emptyList;\n@SuppressWarnings(\"sunapi\")\npublic class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509ExtendedKeyManager {\n- private final KeyStore keyStore;\n- private final char[] password;\n- private final CertificateAuthority existingCertificateAuthority;\n+ private final DynamicKeyStore dynamicKeyStore;\npublic CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) {\nsuper(keyManager);\n- this.keyStore = keyStore;\n- this.password = keyPassword;\n- existingCertificateAuthority = findExistingCertificateAuthority();\n+ dynamicKeyStore = new DynamicKeyStore(keyStore, keyPassword);\n}\n@Override\npublic PrivateKey getPrivateKey(String alias) {\nPrivateKey original = super.getPrivateKey(alias);\n- return original == null ? getDynamicPrivateKey(alias) : original;\n- }\n-\n- private PrivateKey getDynamicPrivateKey(String alias) {\n- try {\n- return (PrivateKey) keyStore.getKey(alias, password);\n- } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {\n- return null;\n- }\n+ return original == null ? dynamicKeyStore.getPrivateKey(alias) : original;\n}\n@Override\npublic X509Certificate[] getCertificateChain(String alias) {\nX509Certificate[] original = super.getCertificateChain(alias);\nif (original == null) {\n- return getDynamicCertificateChain(alias);\n+ return dynamicKeyStore.getCertificateChain(alias);\n} else {\nreturn original;\n}\n}\n- private X509Certificate[] getDynamicCertificateChain(String alias) {\n- try {\n- Certificate[] fromKeyStore = keyStore.getCertificateChain(alias);\n- if (fromKeyStore != null && areX509Certificates(fromKeyStore)) {\n- return convertToX509(fromKeyStore);\n- } else {\n- return null;\n- }\n- } catch (KeyStoreException e) {\n- return null;\n- }\n- }\n-\n- private static boolean areX509Certificates(Certificate[] fromKeyStore) {\n- return fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;\n- }\n-\n- private static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {\n- X509Certificate[] result = new X509Certificate[fromKeyStore.length];\n- for (int i = 0; i < fromKeyStore.length; i++) {\n- result[i] = (X509Certificate) fromKeyStore[i];\n- }\n- return result;\n- }\n-\n-\n@Override\npublic String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {\nString defaultAlias = super.chooseServerAlias(keyType, issuers, socket);\n@@ -154,7 +112,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n* @param handshakeSession nullable\n*/\nprivate String tryToChooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {\n- if (defaultAlias != null && handshakeSession != null && existingCertificateAuthority != null) {\n+ if (defaultAlias != null && handshakeSession != null && dynamicKeyStore.hasCertificateAuthority()) {\nreturn chooseServerAlias(keyType, defaultAlias, handshakeSession);\n} else {\nreturn defaultAlias;\n@@ -206,7 +164,9 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn defaultAlias;\n} else {\ntry {\n- return generateCertificate(keyType, requestedServerNames.get(0));\n+ SNIHostName requestedServerName = requestedServerNames.get(0);\n+ dynamicKeyStore.generateCertificate(keyType, requestedServerName);\n+ return requestedServerName.getAsciiName();\n} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {\n// TODO log?\nreturn defaultAlias;\n@@ -214,53 +174,6 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- /**\n- * @param keyType non null, guaranteed to be valid\n- * @param requestedServerName non null\n- * @return an alias to a new private key & certificate for the first requested server name\n- */\n- private String generateCertificate(\n- String keyType,\n- SNIHostName requestedServerName\n- ) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n-\n- CertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedServerName);\n-\n- String requestedNameString = requestedServerName.getAsciiName();\n- keyStore.setKeyEntry(requestedNameString, newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\n- return requestedNameString;\n- }\n-\n- private CertificateAuthority findExistingCertificateAuthority() {\n- Enumeration<String> aliases;\n- try {\n- aliases = keyStore.aliases();\n- } catch (KeyStoreException e) {\n- aliases = Collections.emptyEnumeration();\n- }\n- while (aliases.hasMoreElements()) {\n- String alias = aliases.nextElement();\n- CertificateAuthority key = getCertChainAndKey(alias);\n- if (key != null) return key;\n- }\n- return null;\n- }\n-\n- private CertificateAuthority getCertChainAndKey(String alias) {\n- X509Certificate[] chain = getCertificateChain(alias);\n- PrivateKey key = getPrivateKey(alias);\n- if (isCertificateAuthority(chain[0]) && key != null) {\n- return new CertificateAuthority(chain, key);\n- } else {\n- return null;\n- }\n- }\n-\n- private static boolean isCertificateAuthority(X509Certificate certificate) {\n- boolean[] keyUsage = certificate.getKeyUsage();\n- return keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n- }\n-\nprivate static boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\nfor (SNIHostName serverName : requestedServerNames) {\nif (matches(x509Certificate, serverName)) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SNIHostName;\n+import java.security.InvalidKeyException;\n+import java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.NoSuchProviderException;\n+import java.security.PrivateKey;\n+import java.security.SignatureException;\n+import java.security.UnrecoverableKeyException;\n+import java.security.cert.Certificate;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.Collections;\n+import java.util.Enumeration;\n+\n+import static java.util.Objects.requireNonNull;\n+\n+class DynamicKeyStore {\n+\n+ private final KeyStore keyStore;\n+ private final char[] password;\n+ private final CertificateAuthority existingCertificateAuthority;\n+\n+ DynamicKeyStore(KeyStore keyStore, char[] password) {\n+ this.keyStore = requireNonNull(keyStore);\n+ this.password = requireNonNull(password);\n+ this.existingCertificateAuthority = findExistingCertificateAuthority();\n+ }\n+\n+ PrivateKey getPrivateKey(String alias) {\n+ try {\n+ return (PrivateKey) keyStore.getKey(alias, password);\n+ } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {\n+ return null;\n+ }\n+ }\n+\n+ X509Certificate[] getCertificateChain(String alias) {\n+ try {\n+ Certificate[] fromKeyStore = keyStore.getCertificateChain(alias);\n+ if (fromKeyStore != null && areX509Certificates(fromKeyStore)) {\n+ return convertToX509(fromKeyStore);\n+ } else {\n+ return null;\n+ }\n+ } catch (KeyStoreException e) {\n+ return null;\n+ }\n+ }\n+\n+ private static boolean areX509Certificates(Certificate[] fromKeyStore) {\n+ return fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;\n+ }\n+\n+ private static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {\n+ X509Certificate[] result = new X509Certificate[fromKeyStore.length];\n+ for (int i = 0; i < fromKeyStore.length; i++) {\n+ result[i] = (X509Certificate) fromKeyStore[i];\n+ }\n+ return result;\n+ }\n+\n+ /**\n+ * @param keyType non null, guaranteed to be valid\n+ * @param requestedServerName non null\n+ */\n+ void generateCertificate(\n+ String keyType,\n+ SNIHostName requestedServerName\n+ ) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n+ CertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedServerName);\n+ keyStore.setKeyEntry(requestedServerName.getAsciiName(), newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\n+ }\n+\n+ boolean hasCertificateAuthority() {\n+ return existingCertificateAuthority != null;\n+ }\n+\n+ private CertificateAuthority findExistingCertificateAuthority() {\n+ Enumeration<String> aliases;\n+ try {\n+ aliases = keyStore.aliases();\n+ } catch (KeyStoreException e) {\n+ aliases = Collections.emptyEnumeration();\n+ }\n+ while (aliases.hasMoreElements()) {\n+ String alias = aliases.nextElement();\n+ CertificateAuthority key = getCertChainAndKey(alias);\n+ if (key != null) return key;\n+ }\n+ return null;\n+ }\n+\n+ private CertificateAuthority getCertChainAndKey(String alias) {\n+ X509Certificate[] chain = getCertificateChain(alias);\n+ PrivateKey key = getPrivateKey(alias);\n+ if (isCertificateAuthority(chain[0]) && key != null) {\n+ return new CertificateAuthority(chain, key);\n+ } else {\n+ return null;\n+ }\n+ }\n+\n+ private static boolean isCertificateAuthority(X509Certificate certificate) {\n+ boolean[] keyUsage = certificate.getKeyUsage();\n+ return keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Extract DynamicKeyStore To encapsulate a Key Store that can add new certificates to itself
686,981
12.06.2020 14:23:39
-3,600
3c0463a11b22c22ce4a7fa6e787f0e0b09ae6953
Extract X509KeyStore To encapsulate a Key Store that returns PrivateKey and X509Certificate[] chains
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -30,9 +30,9 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate final DynamicKeyStore dynamicKeyStore;\n- public CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) {\n+ public CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) throws KeyStoreException {\nsuper(keyManager);\n- dynamicKeyStore = new DynamicKeyStore(keyStore, keyPassword);\n+ dynamicKeyStore = new DynamicKeyStore(new JavaX509KeyStore(keyStore, keyPassword));\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "@@ -2,64 +2,34 @@ package com.github.tomakehurst.wiremock.http.ssl;\nimport javax.net.ssl.SNIHostName;\nimport java.security.InvalidKeyException;\n-import java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.NoSuchProviderException;\nimport java.security.PrivateKey;\nimport java.security.SignatureException;\n-import java.security.UnrecoverableKeyException;\n-import java.security.cert.Certificate;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\n-import java.util.Collections;\n-import java.util.Enumeration;\nimport static java.util.Objects.requireNonNull;\n-class DynamicKeyStore {\n+class DynamicKeyStore implements X509KeyStore {\n- private final KeyStore keyStore;\n- private final char[] password;\n+ private final X509KeyStore keyStore;\nprivate final CertificateAuthority existingCertificateAuthority;\n- DynamicKeyStore(KeyStore keyStore, char[] password) {\n+ DynamicKeyStore(X509KeyStore keyStore) {\nthis.keyStore = requireNonNull(keyStore);\n- this.password = requireNonNull(password);\n- this.existingCertificateAuthority = findExistingCertificateAuthority();\n+ this.existingCertificateAuthority = keyStore.getCertificateAuthority();\n}\n- PrivateKey getPrivateKey(String alias) {\n- try {\n- return (PrivateKey) keyStore.getKey(alias, password);\n- } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {\n- return null;\n- }\n+ @Override\n+ public PrivateKey getPrivateKey(String alias) {\n+ return keyStore.getPrivateKey(alias);\n}\n- X509Certificate[] getCertificateChain(String alias) {\n- try {\n- Certificate[] fromKeyStore = keyStore.getCertificateChain(alias);\n- if (fromKeyStore != null && areX509Certificates(fromKeyStore)) {\n- return convertToX509(fromKeyStore);\n- } else {\n- return null;\n- }\n- } catch (KeyStoreException e) {\n- return null;\n- }\n- }\n-\n- private static boolean areX509Certificates(Certificate[] fromKeyStore) {\n- return fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;\n- }\n-\n- private static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {\n- X509Certificate[] result = new X509Certificate[fromKeyStore.length];\n- for (int i = 0; i < fromKeyStore.length; i++) {\n- result[i] = (X509Certificate) fromKeyStore[i];\n- }\n- return result;\n+ @Override\n+ public X509Certificate[] getCertificateChain(String alias) {\n+ return keyStore.getCertificateChain(alias);\n}\n/**\n@@ -71,40 +41,21 @@ class DynamicKeyStore {\nSNIHostName requestedServerName\n) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\nCertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedServerName);\n- keyStore.setKeyEntry(requestedServerName.getAsciiName(), newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\n+ setKeyEntry(requestedServerName.getAsciiName(), newCertChainAndKey);\n}\n- boolean hasCertificateAuthority() {\n+ @Override\n+ public boolean hasCertificateAuthority() {\nreturn existingCertificateAuthority != null;\n}\n- private CertificateAuthority findExistingCertificateAuthority() {\n- Enumeration<String> aliases;\n- try {\n- aliases = keyStore.aliases();\n- } catch (KeyStoreException e) {\n- aliases = Collections.emptyEnumeration();\n- }\n- while (aliases.hasMoreElements()) {\n- String alias = aliases.nextElement();\n- CertificateAuthority key = getCertChainAndKey(alias);\n- if (key != null) return key;\n- }\n- return null;\n- }\n-\n- private CertificateAuthority getCertChainAndKey(String alias) {\n- X509Certificate[] chain = getCertificateChain(alias);\n- PrivateKey key = getPrivateKey(alias);\n- if (isCertificateAuthority(chain[0]) && key != null) {\n- return new CertificateAuthority(chain, key);\n- } else {\n- return null;\n- }\n+ @Override\n+ public CertificateAuthority getCertificateAuthority() {\n+ return keyStore.getCertificateAuthority();\n}\n- private static boolean isCertificateAuthority(X509Certificate certificate) {\n- boolean[] keyUsage = certificate.getKeyUsage();\n- return keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n+ @Override\n+ public void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException {\n+ keyStore.setKeyEntry(alias, newCertChainAndKey);\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/JavaX509KeyStore.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import java.security.Key;\n+import java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.PrivateKey;\n+import java.security.UnrecoverableKeyException;\n+import java.security.cert.Certificate;\n+import java.security.cert.X509Certificate;\n+import java.util.Collections;\n+import java.util.List;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.util.Objects.requireNonNull;\n+\n+/**\n+ * Wrapper class to make it easy to retrieve X509 PrivateKey and certificate\n+ * chains\n+ */\n+public class JavaX509KeyStore implements X509KeyStore {\n+\n+ private final KeyStore keyStore;\n+ private final char[] password;\n+ private final List<String> aliases;\n+\n+ /**\n+ *\n+ * @param keyStore {@link KeyStore} to delegate to\n+ * @param password used to manage all keys stored in this key store\n+ * @throws KeyStoreException if the keystore has not been loaded\n+ */\n+ public JavaX509KeyStore(KeyStore keyStore, char[] password) throws KeyStoreException {\n+ this.keyStore = requireNonNull(keyStore);\n+ this.password = requireNonNull(password);\n+ this.aliases = Collections.list(keyStore.aliases());\n+ }\n+\n+ @Override\n+ public PrivateKey getPrivateKey(String alias) {\n+ try {\n+ Key key = keyStore.getKey(alias, password);\n+ if (key instanceof PrivateKey) {\n+ return (PrivateKey) key;\n+ } else {\n+ return null;\n+ }\n+ } catch (NoSuchAlgorithmException | UnrecoverableKeyException e) {\n+ return null;\n+ } catch (KeyStoreException e) {\n+ // impossible, class could not have been constructed\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ @Override\n+ public X509Certificate[] getCertificateChain(String alias) {\n+ try {\n+ Certificate[] fromKeyStore = keyStore.getCertificateChain(alias);\n+ if (fromKeyStore != null && areX509Certificates(fromKeyStore)) {\n+ return convertToX509(fromKeyStore);\n+ } else {\n+ return null;\n+ }\n+ } catch (KeyStoreException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private static boolean areX509Certificates(Certificate[] fromKeyStore) {\n+ return fromKeyStore.length == 0 || fromKeyStore[0] instanceof X509Certificate;\n+ }\n+\n+ private static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {\n+ X509Certificate[] result = new X509Certificate[fromKeyStore.length];\n+ for (int i = 0; i < fromKeyStore.length; i++) {\n+ result[i] = (X509Certificate) fromKeyStore[i];\n+ }\n+ return result;\n+ }\n+\n+ @Override\n+ public boolean hasCertificateAuthority() {\n+ return getCertificateAuthority() != null;\n+ }\n+\n+ @Override\n+ public CertificateAuthority getCertificateAuthority() {\n+ for (String alias : aliases) {\n+ X509Certificate[] chain = getCertificateChain(alias);\n+ PrivateKey key = getPrivateKey(alias);\n+ if (isCertificateAuthority(chain[0]) && key != null) {\n+ return new CertificateAuthority(chain, key);\n+ }\n+ }\n+ return null;\n+ }\n+\n+ private static boolean isCertificateAuthority(X509Certificate certificate) {\n+ boolean[] keyUsage = certificate.getKeyUsage();\n+ return keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n+ }\n+\n+ @Override\n+ public void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException {\n+ keyStore.setKeyEntry(alias, newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/X509KeyStore.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import java.security.KeyStoreException;\n+import java.security.PrivateKey;\n+import java.security.cert.X509Certificate;\n+\n+public interface X509KeyStore {\n+\n+ PrivateKey getPrivateKey(String alias);\n+\n+ X509Certificate[] getCertificateChain(String alias);\n+\n+ boolean hasCertificateAuthority();\n+\n+ /**\n+ * @return the first key & chain that represent a certificate authority\n+ * or null if none found\n+ */\n+ CertificateAuthority getCertificateAuthority();\n+\n+ void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException;\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -14,14 +14,22 @@ import org.eclipse.jetty.http.HttpVersion;\nimport org.eclipse.jetty.http2.HTTP2Cipher;\nimport org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\n-import org.eclipse.jetty.server.*;\n+import org.eclipse.jetty.server.ConnectionFactory;\n+import org.eclipse.jetty.server.HttpConfiguration;\n+import org.eclipse.jetty.server.HttpConnectionFactory;\n+import org.eclipse.jetty.server.SecureRequestCustomizer;\n+import org.eclipse.jetty.server.Server;\n+import org.eclipse.jetty.server.ServerConnector;\n+import org.eclipse.jetty.server.SslConnectionFactory;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.X509ExtendedKeyManager;\nimport java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.util.Arrays.stream;\npublic class Jetty94HttpServer extends JettyHttpServer {\n@@ -141,7 +149,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn stream(managers).map(manager -> {\nif (manager instanceof X509ExtendedKeyManager) {\nchar[] keyStorePassword = httpsSettings.keyStorePassword() == null ? null : httpsSettings.keyStorePassword().toCharArray();\n- return new CertificateGeneratingX509ExtendedKeyManager((X509ExtendedKeyManager) manager, keyStore, keyStorePassword);\n+ return certificateGeneratingX509ExtendedKeyManager(keyStore, (X509ExtendedKeyManager) manager, keyStorePassword);\n} else {\nreturn manager;\n}\n@@ -151,4 +159,13 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn configure(sslContextFactory, httpsSettings);\n}\n+\n+ private KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword) {\n+ try {\n+ return new CertificateGeneratingX509ExtendedKeyManager(manager, keyStore, keyStorePassword);\n+ } catch (KeyStoreException e) {\n+ // KeyStore must be loaded here, should never happen\n+ return throwUnchecked(e, null);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "diff": "@@ -127,4 +127,6 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nwhen(certificate.getSubjectX500Principal()).thenReturn(new X500Principal(cn));\nreturn certificate;\n}\n+\n+ public CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest() throws Exception {}\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "diff": "@@ -139,4 +139,6 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nwhen(certificate.getSubjectX500Principal()).thenReturn(new X500Principal(cn));\nreturn certificate;\n}\n+\n+ public CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest() throws Exception {}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Extract X509KeyStore To encapsulate a Key Store that returns PrivateKey and X509Certificate[] chains
686,981
12.06.2020 14:51:18
-3,600
98f2e230f1fe3b00a5108f787cf9c7f03ea6aa87
Stop generating a new key on every request!
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -165,7 +165,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n} else {\ntry {\nSNIHostName requestedServerName = requestedServerNames.get(0);\n- dynamicKeyStore.generateCertificate(keyType, requestedServerName);\n+ dynamicKeyStore.generateCertificateIfNecessary(keyType, requestedServerName);\nreturn requestedServerName.getAsciiName();\n} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {\n// TODO log?\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "@@ -32,6 +32,19 @@ class DynamicKeyStore implements X509KeyStore {\nreturn keyStore.getCertificateChain(alias);\n}\n+ /**\n+ * @param keyType non null, guaranteed to be valid\n+ * @param requestedServerName non null\n+ */\n+ void generateCertificateIfNecessary(\n+ String keyType,\n+ SNIHostName requestedServerName\n+ ) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n+ if (getPrivateKey(requestedServerName.getAsciiName()) == null) {\n+ generateCertificate(keyType, requestedServerName);\n+ }\n+ }\n+\n/**\n* @param keyType non null, guaranteed to be valid\n* @param requestedServerName non null\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "@@ -15,17 +15,18 @@ import java.security.KeyFactory;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n+import java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.UnrecoverableKeyException;\nimport java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\nimport java.security.interfaces.RSAPrivateCrtKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.RSAPublicKeySpec;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.KEY_STORE_WITH_CA_PATH;\nimport static java.util.Collections.singletonList;\n-import static org.junit.Assert.assertEquals;\n-import static org.junit.Assert.assertNull;\n+import static org.junit.Assert.*;\nimport static org.mockito.BDDMockito.given;\nimport static org.mockito.Mockito.mock;\n@@ -59,6 +60,34 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nassertEquals(myPublicKey, generatingKeyManager.getCertificateChain(keyAlias)[0].getPublicKey());\n}\n+ @Test\n+ public void returnsSameGeneratedPricateKeyOnSubsequencCalls() throws Exception {\n+\n+ KeyStore keyStore = readKeyStore(KEY_STORE_WITH_CA_PATH, \"password\");\n+ String hostname = \"example.com\";\n+\n+ // given\n+ CertificateGeneratingX509ExtendedKeyManager generatingKeyManager = keyManagerFor(keyStore, \"password\".toCharArray());\n+\n+ // when\n+ SSLEngine sslEngineMock = getSslEngineWithSessionFor(hostname);\n+ String keyAlias = generatingKeyManager.chooseEngineServerAlias(\"RSA\", null, sslEngineMock);\n+\n+ // and\n+ X509Certificate[] certificateChain = generatingKeyManager.getCertificateChain(keyAlias);\n+ PrivateKey privateKey = generatingKeyManager.getPrivateKey(keyAlias);\n+\n+ // when\n+ String sameKeyAlias = generatingKeyManager.chooseEngineServerAlias(\"RSA\", null, sslEngineMock);\n+\n+ // then\n+ assertEquals(keyAlias, sameKeyAlias);\n+\n+ // and same keys returned\n+ assertEquals(privateKey, generatingKeyManager.getPrivateKey(sameKeyAlias));\n+ assertArrayEquals(certificateChain, generatingKeyManager.getCertificateChain(sameKeyAlias));\n+ }\n+\nprivate PublicKey getPublicKey(RSAPrivateCrtKey privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {\nRSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent());\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Stop generating a new key on every request!
686,981
12.06.2020 14:51:42
-3,600
d920a915939a52a55f87451e735b962e0bce2e9b
Be more efficient when checking existing keystore
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -159,8 +159,8 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n* @param requestedServerNames non null, non empty\n*/\nprivate String chooseServerAlias(String keyType, String defaultAlias, List<SNIHostName> requestedServerNames) {\n- X509Certificate[] certificateChain = getCertificateChain(defaultAlias);\n- if (matches(certificateChain[0], requestedServerNames)) {\n+ X509Certificate[] certificateChain = super.getCertificateChain(defaultAlias);\n+ if (certificateChain != null && matches(certificateChain[0], requestedServerNames)) {\nreturn defaultAlias;\n} else {\ntry {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Be more efficient when checking existing keystore
686,981
12.06.2020 15:05:07
-3,600
899dca33afa7798604da90b78211e84911cd545a
Use stream api as we're in Java 8
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -20,8 +20,8 @@ import java.security.PrivateKey;\nimport java.security.SignatureException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\n-import java.util.ArrayList;\nimport java.util.List;\n+import java.util.stream.Collectors;\nimport static java.util.Collections.emptyList;\n@@ -135,13 +135,10 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate static List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {\nList<SNIServerName> requestedServerNames = getRequestedServerNames(handshakeSession);\n- List<SNIHostName> requestedHostNames = new ArrayList<>(requestedServerNames.size());\n- for (SNIServerName serverName: requestedServerNames) {\n- if (serverName instanceof SNIHostName) {\n- requestedHostNames.add((SNIHostName) serverName);\n- }\n- }\n- return requestedHostNames;\n+ return requestedServerNames.stream()\n+ .filter(SNIHostName.class::isInstance)\n+ .map(SNIHostName.class::cast)\n+ .collect(Collectors.toList());\n}\nprivate static List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {\n@@ -175,12 +172,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\nprivate static boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\n- for (SNIHostName serverName : requestedServerNames) {\n- if (matches(x509Certificate, serverName)) {\n- return true;\n- }\n- }\n- return false;\n+ return requestedServerNames.stream().anyMatch(sniHostName -> matches(x509Certificate, sniHostName));\n}\nprivate static boolean matches(X509Certificate x509Certificate, SNIHostName hostName) {\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/JavaX509KeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/JavaX509KeyStore.java", "diff": "@@ -12,6 +12,7 @@ import java.util.Collections;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.util.Arrays.stream;\nimport static java.util.Objects.requireNonNull;\n/**\n@@ -72,11 +73,7 @@ public class JavaX509KeyStore implements X509KeyStore {\n}\nprivate static X509Certificate[] convertToX509(Certificate[] fromKeyStore) {\n- X509Certificate[] result = new X509Certificate[fromKeyStore.length];\n- for (int i = 0; i < fromKeyStore.length; i++) {\n- result[i] = (X509Certificate) fromKeyStore[i];\n- }\n- return result;\n+ return stream(fromKeyStore).map(X509Certificate.class::cast).toArray(X509Certificate[]::new);\n}\n@Override\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Use stream api as we're in Java 8
686,981
12.06.2020 15:51:57
-3,600
1c548bfa84a0e74d76a45d294f2e7442dd427342
Isolate usages of Sun API We're using the Sun API to generate certificates & to check if a name matches a certificate. This commit isolates this usage and handles the possibility of the classes not being present or being altered in an incompatible way, by disabling the certificate generation behaviour.
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -43,7 +43,9 @@ class CertificateAuthority {\nCertChainAndKey generateCertificate(\nString keyType,\nSNIHostName hostName\n- ) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateException, SignatureException {\n+ ) throws CertificateGenerationUnsupportedException {\n+ try {\n+ // TODO inline CertAndKeyGen logic so we don't depend on sun.security.tools.keytool\nCertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\" + keyType, null);\nnewCertAndKey.generate(2048);\nPrivateKey newKey = newCertAndKey.getPrivateKey();\n@@ -58,6 +60,12 @@ class CertificateAuthority {\nX509Certificate signed = sign(certificate);\nX509Certificate[] fullChain = prepend(signed, certificateChain);\nreturn new CertChainAndKey(fullChain, newKey);\n+ } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError e) {\n+ throw new CertificateGenerationUnsupportedException(\n+ \"Your runtime does not support generating certificates at runtime\",\n+ e\n+ );\n+ }\n}\nprivate X500Name x500Name(SNIHostName hostName) {\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import sun.security.util.HostnameChecker;\n-\nimport javax.net.ssl.ExtendedSSLSession;\nimport javax.net.ssl.SNIHostName;\nimport javax.net.ssl.SNIServerName;\n@@ -10,29 +8,30 @@ import javax.net.ssl.SSLSession;\nimport javax.net.ssl.SSLSocket;\nimport javax.net.ssl.X509ExtendedKeyManager;\nimport java.net.Socket;\n-import java.security.InvalidKeyException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n-import java.security.NoSuchAlgorithmException;\n-import java.security.NoSuchProviderException;\nimport java.security.Principal;\nimport java.security.PrivateKey;\n-import java.security.SignatureException;\n-import java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport static java.util.Collections.emptyList;\n-@SuppressWarnings(\"sunapi\")\npublic class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509ExtendedKeyManager {\nprivate final DynamicKeyStore dynamicKeyStore;\n-\n- public CertificateGeneratingX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, KeyStore keyStore, char[] keyPassword) throws KeyStoreException {\n+ private final HostNameMatcher hostNameMatcher;\n+\n+ public CertificateGeneratingX509ExtendedKeyManager(\n+ X509ExtendedKeyManager keyManager,\n+ KeyStore keyStore,\n+ char[] keyPassword,\n+ HostNameMatcher hostNameMatcher\n+ ) throws KeyStoreException {\nsuper(keyManager);\n- dynamicKeyStore = new DynamicKeyStore(new JavaX509KeyStore(keyStore, keyPassword));\n+ this.hostNameMatcher = hostNameMatcher;\n+ this.dynamicKeyStore = new DynamicKeyStore(new JavaX509KeyStore(keyStore, keyPassword));\n}\n@Override\n@@ -164,24 +163,14 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nSNIHostName requestedServerName = requestedServerNames.get(0);\ndynamicKeyStore.generateCertificateIfNecessary(keyType, requestedServerName);\nreturn requestedServerName.getAsciiName();\n- } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {\n+ } catch (KeyStoreException | CertificateGenerationUnsupportedException e) {\n// TODO log?\nreturn defaultAlias;\n}\n}\n}\n- private static boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\n- return requestedServerNames.stream().anyMatch(sniHostName -> matches(x509Certificate, sniHostName));\n- }\n-\n- private static boolean matches(X509Certificate x509Certificate, SNIHostName hostName) {\n- try {\n- HostnameChecker instance = HostnameChecker.getInstance(HostnameChecker.TYPE_TLS);\n- instance.match(hostName.getAsciiName(), x509Certificate);\n- return true;\n- } catch (CertificateException e) {\n- return false;\n- }\n+ private boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\n+ return requestedServerNames.stream().anyMatch(sniHostName -> hostNameMatcher.matches(x509Certificate, sniHostName));\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGenerationUnsupportedException.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+public class CertificateGenerationUnsupportedException extends Exception {\n+ public CertificateGenerationUnsupportedException(String message, Throwable cause) {\n+ super(message, cause);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "@@ -39,7 +39,7 @@ class DynamicKeyStore implements X509KeyStore {\nvoid generateCertificateIfNecessary(\nString keyType,\nSNIHostName requestedServerName\n- ) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n+ ) throws CertificateGenerationUnsupportedException, KeyStoreException {\nif (getPrivateKey(requestedServerName.getAsciiName()) == null) {\ngenerateCertificate(keyType, requestedServerName);\n}\n@@ -52,7 +52,7 @@ class DynamicKeyStore implements X509KeyStore {\nvoid generateCertificate(\nString keyType,\nSNIHostName requestedServerName\n- ) throws CertificateException, NoSuchAlgorithmException, SignatureException, NoSuchProviderException, InvalidKeyException, KeyStoreException {\n+ ) throws CertificateGenerationUnsupportedException, KeyStoreException {\nCertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedServerName);\nsetKeyEntry(requestedServerName.getAsciiName(), newCertChainAndKey);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/HostNameMatcher.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import javax.net.ssl.SNIHostName;\n+import java.security.cert.X509Certificate;\n+\n+@FunctionalInterface\n+public interface HostNameMatcher {\n+ Boolean matches(X509Certificate x509Certificate, SNIHostName sniHostName);\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/SunHostNameMatcher.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import sun.security.util.HostnameChecker;\n+\n+import javax.net.ssl.SNIHostName;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+\n+import static sun.security.util.HostnameChecker.TYPE_TLS;\n+\n+@SuppressWarnings(\"sunapi\")\n+public class SunHostNameMatcher implements HostNameMatcher {\n+ @Override\n+ public Boolean matches(X509Certificate x509Certificate, SNIHostName sniHostName) {\n+ try {\n+ HostnameChecker instance = HostnameChecker.getInstance(TYPE_TLS);\n+ instance.match(sniHostName.getAsciiName(), x509Certificate);\n+ return true;\n+ } catch (CertificateException | NoSuchMethodError | VerifyError | NoClassDefFoundError e) {\n+ return false;\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -6,6 +6,7 @@ import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\n+import com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\nimport com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\n@@ -162,7 +163,13 @@ public class Jetty94HttpServer extends JettyHttpServer {\nprivate KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword) {\ntry {\n- return new CertificateGeneratingX509ExtendedKeyManager(manager, keyStore, keyStorePassword);\n+ return new CertificateGeneratingX509ExtendedKeyManager(\n+ manager,\n+ keyStore,\n+ keyStorePassword,\n+ // TODO write a version of this that doesn't depend on sun internal classes\n+ new SunHostNameMatcher()\n+ );\n} catch (KeyStoreException e) {\n// KeyStore must be loaded here, should never happen\nreturn throwUnchecked(e, null);\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "diff": "@@ -34,7 +34,8 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\nnew InMemoryKeyStore(JKS, new Secret(\"whatever\")).getKeyStore(),\n- \"password\".toCharArray()\n+ \"password\".toCharArray(),\n+ new SunHostNameMatcher()\n);\nprivate final Principal[] nullPrincipals = null;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "@@ -109,7 +109,12 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nkeyManagerFactory.init(keyStore, keyStorePassword);\nX509ExtendedKeyManager keyManager = findExtendedKeyManager(keyManagerFactory.getKeyManagers());\n- return new CertificateGeneratingX509ExtendedKeyManager(keyManager, keyStore, keyStorePassword);\n+ return new CertificateGeneratingX509ExtendedKeyManager(\n+ keyManager,\n+ keyStore,\n+ keyStorePassword,\n+ new SunHostNameMatcher()\n+ );\n}\nprivate X509ExtendedKeyManager findExtendedKeyManager(KeyManager[] keyManagers) {\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "diff": "@@ -37,7 +37,8 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\nnew InMemoryKeyStore(JKS, new Secret(\"whatever\")).getKeyStore(),\n- \"password\".toCharArray()\n+ \"password\".toCharArray(),\n+ new SunHostNameMatcher()\n);\nprivate final Principal[] nullPrincipals = null;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Isolate usages of Sun API We're using the Sun API to generate certificates & to check if a name matches a certificate. This commit isolates this usage and handles the possibility of the classes not being present or being altered in an incompatible way, by disabling the certificate generation behaviour.
686,981
12.06.2020 16:17:26
-3,600
61a6d7d0787896cce4e9a448e616096e1effce36
Pull deciding whether a key store has a certificate authority up Means that you know the `CertificateGeneratingX509ExtendedKeyManager` will always be able to generate certificates. If the sun classes are present, of course... Also removed the X509KeyStore interface - it was unnecessary, making unused methods be implemented and others made public.
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -27,7 +27,7 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.util.Objects.requireNonNull;\n@SuppressWarnings(\"sunapi\")\n-class CertificateAuthority {\n+public class CertificateAuthority {\nprivate final X509Certificate[] certificateChain;\nprivate final PrivateKey key;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -8,7 +8,6 @@ import javax.net.ssl.SSLSession;\nimport javax.net.ssl.SSLSocket;\nimport javax.net.ssl.X509ExtendedKeyManager;\nimport java.net.Socket;\n-import java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.Principal;\nimport java.security.PrivateKey;\n@@ -17,6 +16,7 @@ import java.util.List;\nimport java.util.stream.Collectors;\nimport static java.util.Collections.emptyList;\n+import static java.util.Objects.requireNonNull;\npublic class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509ExtendedKeyManager {\n@@ -25,13 +25,12 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\npublic CertificateGeneratingX509ExtendedKeyManager(\nX509ExtendedKeyManager keyManager,\n- KeyStore keyStore,\n- char[] keyPassword,\n+ DynamicKeyStore dynamicKeyStore,\nHostNameMatcher hostNameMatcher\n- ) throws KeyStoreException {\n+ ) {\nsuper(keyManager);\n- this.hostNameMatcher = hostNameMatcher;\n- this.dynamicKeyStore = new DynamicKeyStore(new JavaX509KeyStore(keyStore, keyPassword));\n+ this.dynamicKeyStore = requireNonNull(dynamicKeyStore);\n+ this.hostNameMatcher = requireNonNull(hostNameMatcher);\n}\n@Override\n@@ -111,7 +110,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n* @param handshakeSession nullable\n*/\nprivate String tryToChooseServerAlias(String keyType, String defaultAlias, ExtendedSSLSession handshakeSession) {\n- if (defaultAlias != null && handshakeSession != null && dynamicKeyStore.hasCertificateAuthority()) {\n+ if (defaultAlias != null && handshakeSession != null) {\nreturn chooseServerAlias(keyType, defaultAlias, handshakeSession);\n} else {\nreturn defaultAlias;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\nimport javax.net.ssl.SNIHostName;\n-import java.security.InvalidKeyException;\nimport java.security.KeyStoreException;\n-import java.security.NoSuchAlgorithmException;\n-import java.security.NoSuchProviderException;\nimport java.security.PrivateKey;\n-import java.security.SignatureException;\n-import java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport static java.util.Objects.requireNonNull;\n-class DynamicKeyStore implements X509KeyStore {\n+public class DynamicKeyStore {\n- private final X509KeyStore keyStore;\n+ private final JavaX509KeyStore keyStore;\nprivate final CertificateAuthority existingCertificateAuthority;\n- DynamicKeyStore(X509KeyStore keyStore) {\n+ public DynamicKeyStore(JavaX509KeyStore keyStore, CertificateAuthority existingCertificateAuthority) {\nthis.keyStore = requireNonNull(keyStore);\n- this.existingCertificateAuthority = keyStore.getCertificateAuthority();\n+ this.existingCertificateAuthority = requireNonNull(existingCertificateAuthority);\n}\n- @Override\n- public PrivateKey getPrivateKey(String alias) {\n+ PrivateKey getPrivateKey(String alias) {\nreturn keyStore.getPrivateKey(alias);\n}\n- @Override\n- public X509Certificate[] getCertificateChain(String alias) {\n+ X509Certificate[] getCertificateChain(String alias) {\nreturn keyStore.getCertificateChain(alias);\n}\n@@ -49,26 +42,11 @@ class DynamicKeyStore implements X509KeyStore {\n* @param keyType non null, guaranteed to be valid\n* @param requestedServerName non null\n*/\n- void generateCertificate(\n+ private void generateCertificate(\nString keyType,\nSNIHostName requestedServerName\n) throws CertificateGenerationUnsupportedException, KeyStoreException {\nCertChainAndKey newCertChainAndKey = existingCertificateAuthority.generateCertificate(keyType, requestedServerName);\n- setKeyEntry(requestedServerName.getAsciiName(), newCertChainAndKey);\n- }\n-\n- @Override\n- public boolean hasCertificateAuthority() {\n- return existingCertificateAuthority != null;\n- }\n-\n- @Override\n- public CertificateAuthority getCertificateAuthority() {\n- return keyStore.getCertificateAuthority();\n- }\n-\n- @Override\n- public void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException {\n- keyStore.setKeyEntry(alias, newCertChainAndKey);\n+ keyStore.setKeyEntry(requestedServerName.getAsciiName(), newCertChainAndKey);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/JavaX509KeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/JavaX509KeyStore.java", "diff": "@@ -19,7 +19,7 @@ import static java.util.Objects.requireNonNull;\n* Wrapper class to make it easy to retrieve X509 PrivateKey and certificate\n* chains\n*/\n-public class JavaX509KeyStore implements X509KeyStore {\n+public class JavaX509KeyStore {\nprivate final KeyStore keyStore;\nprivate final char[] password;\n@@ -37,8 +37,7 @@ public class JavaX509KeyStore implements X509KeyStore {\nthis.aliases = Collections.list(keyStore.aliases());\n}\n- @Override\n- public PrivateKey getPrivateKey(String alias) {\n+ PrivateKey getPrivateKey(String alias) {\ntry {\nKey key = keyStore.getKey(alias, password);\nif (key instanceof PrivateKey) {\n@@ -54,8 +53,7 @@ public class JavaX509KeyStore implements X509KeyStore {\n}\n}\n- @Override\n- public X509Certificate[] getCertificateChain(String alias) {\n+ X509Certificate[] getCertificateChain(String alias) {\ntry {\nCertificate[] fromKeyStore = keyStore.getCertificateChain(alias);\nif (fromKeyStore != null && areX509Certificates(fromKeyStore)) {\n@@ -76,12 +74,10 @@ public class JavaX509KeyStore implements X509KeyStore {\nreturn stream(fromKeyStore).map(X509Certificate.class::cast).toArray(X509Certificate[]::new);\n}\n- @Override\n- public boolean hasCertificateAuthority() {\n- return getCertificateAuthority() != null;\n- }\n-\n- @Override\n+ /**\n+ * @return the first key & chain that represent a certificate authority\n+ * or null if none found\n+ */\npublic CertificateAuthority getCertificateAuthority() {\nfor (String alias : aliases) {\nX509Certificate[] chain = getCertificateChain(alias);\n@@ -98,8 +94,7 @@ public class JavaX509KeyStore implements X509KeyStore {\nreturn keyUsage != null && keyUsage.length > 5 && keyUsage[5];\n}\n- @Override\n- public void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException {\n+ void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException {\nkeyStore.setKeyEntry(alias, newCertChainAndKey.key, password, newCertChainAndKey.certificateChain);\n}\n}\n" }, { "change_type": "DELETE", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/X509KeyStore.java", "new_path": null, "diff": "-package com.github.tomakehurst.wiremock.http.ssl;\n-\n-import java.security.KeyStoreException;\n-import java.security.PrivateKey;\n-import java.security.cert.X509Certificate;\n-\n-public interface X509KeyStore {\n-\n- PrivateKey getPrivateKey(String alias);\n-\n- X509Certificate[] getCertificateChain(String alias);\n-\n- boolean hasCertificateAuthority();\n-\n- /**\n- * @return the first key & chain that represent a certificate authority\n- * or null if none found\n- */\n- CertificateAuthority getCertificateAuthority();\n-\n- void setKeyEntry(String alias, CertChainAndKey newCertChainAndKey) throws KeyStoreException;\n-}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -5,7 +5,10 @@ import com.github.tomakehurst.wiremock.common.JettySettings;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\n+import com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\n+import com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\n+import com.github.tomakehurst.wiremock.http.ssl.JavaX509KeyStore;\nimport com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\n@@ -163,13 +166,18 @@ public class Jetty94HttpServer extends JettyHttpServer {\nprivate KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword) {\ntry {\n+ JavaX509KeyStore x509KeyStore = new JavaX509KeyStore(keyStore, keyStorePassword);\n+ CertificateAuthority certificateAuthority = x509KeyStore.getCertificateAuthority();\n+ if (certificateAuthority != null) {\nreturn new CertificateGeneratingX509ExtendedKeyManager(\nmanager,\n- keyStore,\n- keyStorePassword,\n+ new DynamicKeyStore(x509KeyStore, certificateAuthority),\n// TODO write a version of this that doesn't depend on sun internal classes\nnew SunHostNameMatcher()\n);\n+ } else {\n+ return manager;\n+ }\n} catch (KeyStoreException e) {\n// KeyStore must be loaded here, should never happen\nreturn throwUnchecked(e, null);\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\n-import com.github.tomakehurst.wiremock.crypto.Secret;\nimport org.junit.Test;\nimport javax.net.ssl.ExtendedSSLSession;\n@@ -15,7 +13,6 @@ import java.security.Principal;\nimport java.security.cert.X509Certificate;\nimport java.util.Collections;\n-import static com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore.KeyStoreType.JKS;\nimport static java.util.Arrays.asList;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\n@@ -33,8 +30,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\n- new InMemoryKeyStore(JKS, new Secret(\"whatever\")).getKeyStore(),\n- \"password\".toCharArray(),\n+ mock(DynamicKeyStore.class),\nnew SunHostNameMatcher()\n);\nprivate final Principal[] nullPrincipals = null;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "@@ -108,11 +108,11 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nKeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\nkeyManagerFactory.init(keyStore, keyStorePassword);\nX509ExtendedKeyManager keyManager = findExtendedKeyManager(keyManagerFactory.getKeyManagers());\n+ JavaX509KeyStore x509KeyStore = new JavaX509KeyStore(keyStore, keyStorePassword);\nreturn new CertificateGeneratingX509ExtendedKeyManager(\nkeyManager,\n- keyStore,\n- keyStorePassword,\n+ new DynamicKeyStore(x509KeyStore, x509KeyStore.getCertificateAuthority()),\nnew SunHostNameMatcher()\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "diff": "@@ -36,8 +36,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\n- new InMemoryKeyStore(JKS, new Secret(\"whatever\")).getKeyStore(),\n- \"password\".toCharArray(),\n+ mock(DynamicKeyStore.class),\nnew SunHostNameMatcher()\n);\nprivate final Principal[] nullPrincipals = null;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Pull deciding whether a key store has a certificate authority up Means that you know the `CertificateGeneratingX509ExtendedKeyManager` will always be able to generate certificates. If the sun classes are present, of course... Also removed the X509KeyStore interface - it was unnecessary, making unused methods be implemented and others made public.
686,981
12.06.2020 16:22:33
-3,600
148e585acd00e6a3dd576dbbb003e47d9ff5cc17
Lose redundant Java prefix
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "@@ -9,10 +9,10 @@ import static java.util.Objects.requireNonNull;\npublic class DynamicKeyStore {\n- private final JavaX509KeyStore keyStore;\n+ private final X509KeyStore keyStore;\nprivate final CertificateAuthority existingCertificateAuthority;\n- public DynamicKeyStore(JavaX509KeyStore keyStore, CertificateAuthority existingCertificateAuthority) {\n+ public DynamicKeyStore(X509KeyStore keyStore, CertificateAuthority existingCertificateAuthority) {\nthis.keyStore = requireNonNull(keyStore);\nthis.existingCertificateAuthority = requireNonNull(existingCertificateAuthority);\n}\n" }, { "change_type": "RENAME", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/JavaX509KeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/X509KeyStore.java", "diff": "@@ -19,7 +19,7 @@ import static java.util.Objects.requireNonNull;\n* Wrapper class to make it easy to retrieve X509 PrivateKey and certificate\n* chains\n*/\n-public class JavaX509KeyStore {\n+public class X509KeyStore {\nprivate final KeyStore keyStore;\nprivate final char[] password;\n@@ -31,7 +31,7 @@ public class JavaX509KeyStore {\n* @param password used to manage all keys stored in this key store\n* @throws KeyStoreException if the keystore has not been loaded\n*/\n- public JavaX509KeyStore(KeyStore keyStore, char[] password) throws KeyStoreException {\n+ public X509KeyStore(KeyStore keyStore, char[] password) throws KeyStoreException {\nthis.keyStore = requireNonNull(keyStore);\nthis.password = requireNonNull(password);\nthis.aliases = Collections.list(keyStore.aliases());\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -8,7 +8,7 @@ import com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\nimport com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\n-import com.github.tomakehurst.wiremock.http.ssl.JavaX509KeyStore;\n+import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\n@@ -166,7 +166,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nprivate KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword) {\ntry {\n- JavaX509KeyStore x509KeyStore = new JavaX509KeyStore(keyStore, keyStorePassword);\n+ X509KeyStore x509KeyStore = new X509KeyStore(keyStore, keyStorePassword);\nCertificateAuthority certificateAuthority = x509KeyStore.getCertificateAuthority();\nif (certificateAuthority != null) {\nreturn new CertificateGeneratingX509ExtendedKeyManager(\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "@@ -108,7 +108,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nKeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\nkeyManagerFactory.init(keyStore, keyStorePassword);\nX509ExtendedKeyManager keyManager = findExtendedKeyManager(keyManagerFactory.getKeyManagers());\n- JavaX509KeyStore x509KeyStore = new JavaX509KeyStore(keyStore, keyStorePassword);\n+ X509KeyStore x509KeyStore = new X509KeyStore(keyStore, keyStorePassword);\nreturn new CertificateGeneratingX509ExtendedKeyManager(\nkeyManager,\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Lose redundant Java prefix
686,981
12.06.2020 17:05:17
-3,600
3a634df9e5ebce55c66c2dcc34e628d6427623d4
Add useful logging if certificates cannot be generated
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+\nimport javax.net.ssl.ExtendedSSLSession;\nimport javax.net.ssl.SNIHostName;\nimport javax.net.ssl.SNIServerName;\n@@ -13,8 +15,10 @@ import java.security.Principal;\nimport java.security.PrivateKey;\nimport java.security.cert.X509Certificate;\nimport java.util.List;\n+import java.util.concurrent.atomic.AtomicBoolean;\nimport java.util.stream.Collectors;\n+import static java.lang.System.lineSeparator;\nimport static java.util.Collections.emptyList;\nimport static java.util.Objects.requireNonNull;\n@@ -22,15 +26,18 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate final DynamicKeyStore dynamicKeyStore;\nprivate final HostNameMatcher hostNameMatcher;\n+ private final OnceOnlyNotifier notifier;\npublic CertificateGeneratingX509ExtendedKeyManager(\nX509ExtendedKeyManager keyManager,\nDynamicKeyStore dynamicKeyStore,\n- HostNameMatcher hostNameMatcher\n+ HostNameMatcher hostNameMatcher,\n+ Notifier notifier\n) {\nsuper(keyManager);\nthis.dynamicKeyStore = requireNonNull(dynamicKeyStore);\nthis.hostNameMatcher = requireNonNull(hostNameMatcher);\n+ this.notifier = new OnceOnlyNotifier(notifier);\n}\n@Override\n@@ -56,7 +63,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n}\n- private static ExtendedSSLSession getHandshakeSession(Socket socket) {\n+ private ExtendedSSLSession getHandshakeSession(Socket socket) {\nif (socket instanceof SSLSocket) {\nSSLSocket sslSocket = (SSLSocket) socket;\nSSLSession sslSession = getHandshakeSessionIfSupported(sslSocket);\n@@ -66,11 +73,11 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private static SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {\n+ private SSLSession getHandshakeSessionIfSupported(SSLSocket sslSocket) {\ntry {\nreturn sslSocket.getHandshakeSession();\n} catch (UnsupportedOperationException e) {\n- // TODO log that dynamically generating is not supported\n+ notify(\"your SSL Provider does not support SSLSocket.getHandshakeSession()\", e);\nreturn null;\n}\n}\n@@ -82,16 +89,16 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nreturn tryToChooseServerAlias(keyType, defaultAlias, handshakeSession);\n}\n- private static ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {\n+ private ExtendedSSLSession getHandshakeSession(SSLEngine sslEngine) {\nSSLSession sslSession = getHandshakeSessionIfSupported(sslEngine);\nreturn getHandshakeSession(sslSession);\n}\n- private static SSLSession getHandshakeSessionIfSupported(SSLEngine sslEngine) {\n+ private SSLSession getHandshakeSessionIfSupported(SSLEngine sslEngine) {\ntry {\nreturn sslEngine.getHandshakeSession();\n} catch (UnsupportedOperationException | NullPointerException e) {\n- // TODO log that dynamically generating is not supported\n+ notify(\"your SSL Provider does not support SSLEngine.getHandshakeSession()\", e);\nreturn null;\n}\n}\n@@ -131,7 +138,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n- private static List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {\n+ private List<SNIHostName> getSNIHostNames(ExtendedSSLSession handshakeSession) {\nList<SNIServerName> requestedServerNames = getRequestedServerNames(handshakeSession);\nreturn requestedServerNames.stream()\n.filter(SNIHostName.class::isInstance)\n@@ -139,11 +146,11 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n.collect(Collectors.toList());\n}\n- private static List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {\n+ private List<SNIServerName> getRequestedServerNames(ExtendedSSLSession handshakeSession) {\ntry {\nreturn handshakeSession.getRequestedServerNames();\n} catch (UnsupportedOperationException e) {\n- // TODO log that dynamically generating is not supported\n+ notify(\"your SSL Provider does not support ExtendedSSLSession.getRequestedServerNames()\", e);\nreturn emptyList();\n}\n}\n@@ -163,7 +170,7 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\ndynamicKeyStore.generateCertificateIfNecessary(keyType, requestedServerName);\nreturn requestedServerName.getAsciiName();\n} catch (KeyStoreException | CertificateGenerationUnsupportedException e) {\n- // TODO log?\n+ notify(\"certificates cannot be generated; perhaps the sun internal classes are not available?\", e);\nreturn defaultAlias;\n}\n}\n@@ -172,4 +179,48 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\nprivate boolean matches(X509Certificate x509Certificate, List<SNIHostName> requestedServerNames) {\nreturn requestedServerNames.stream().anyMatch(sniHostName -> hostNameMatcher.matches(x509Certificate, sniHostName));\n}\n+\n+ private void notify(String reason, Exception e) {\n+ notifier.error(\"Dynamic certificate generation is not supported because \" + reason + lineSeparator() +\n+ \"All sites will be served using the normal WireMock HTTPS certificate.\", e);\n+ }\n+\n+ private static class OnceOnlyNotifier implements Notifier {\n+\n+ private final Notifier notifier;\n+ private final OnceOnly onceOnly = new OnceOnly();\n+\n+ private OnceOnlyNotifier(Notifier notifier) {\n+ this.notifier = notifier;\n+ }\n+\n+ @Override\n+ public void info(String message) {\n+ if (onceOnly.unused()) {\n+ notifier.info(message);\n+ }\n+ }\n+\n+ @Override\n+ public void error(String message) {\n+ if (onceOnly.unused()) {\n+ notifier.error(message);\n+ }\n+ }\n+\n+ @Override\n+ public void error(String message, Throwable t) {\n+ if (onceOnly.unused()) {\n+ notifier.error(message, t);\n+ }\n+ }\n+ }\n+\n+ private static class OnceOnly {\n+ private final AtomicBoolean used = new AtomicBoolean(false);\n+\n+ boolean unused() {\n+ return used.compareAndSet(false, true);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -2,6 +2,7 @@ package com.github.tomakehurst.wiremock.jetty94;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\nimport com.github.tomakehurst.wiremock.common.JettySettings;\n+import com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\n@@ -114,7 +115,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nManInTheMiddleSslConnectHandler manInTheMiddleSslConnectHandler = new ManInTheMiddleSslConnectHandler(\nnew SslConnectionFactory(\n- buildManInTheMiddleSslContextFactory(options.httpsSettings()),\n+ buildManInTheMiddleSslContextFactory(options.httpsSettings(), options.notifier()),\n/*\nIf the proxy CONNECT request is made over HTTPS, and the\nactual content request is made using HTTP/2 tunneled over\n@@ -145,7 +146,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn handler;\n}\n- private SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings) {\n+ private SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, final Notifier notifier) {\nSslContextFactory.Server sslContextFactory = new SslContextFactory.Server() {\n@Override\nprotected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {\n@@ -153,7 +154,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn stream(managers).map(manager -> {\nif (manager instanceof X509ExtendedKeyManager) {\nchar[] keyStorePassword = httpsSettings.keyStorePassword() == null ? null : httpsSettings.keyStorePassword().toCharArray();\n- return certificateGeneratingX509ExtendedKeyManager(keyStore, (X509ExtendedKeyManager) manager, keyStorePassword);\n+ return certificateGeneratingX509ExtendedKeyManager(keyStore, (X509ExtendedKeyManager) manager, keyStorePassword, notifier);\n} else {\nreturn manager;\n}\n@@ -164,7 +165,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn configure(sslContextFactory, httpsSettings);\n}\n- private KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword) {\n+ private KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword, Notifier notifier) {\ntry {\nX509KeyStore x509KeyStore = new X509KeyStore(keyStore, keyStorePassword);\nCertificateAuthority certificateAuthority = x509KeyStore.getCertificateAuthority();\n@@ -173,7 +174,8 @@ public class Jetty94HttpServer extends JettyHttpServer {\nmanager,\nnew DynamicKeyStore(x509KeyStore, certificateAuthority),\n// TODO write a version of this that doesn't depend on sun internal classes\n- new SunHostNameMatcher()\n+ new SunHostNameMatcher(),\n+ notifier\n);\n} else {\nreturn manager;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n+import com.github.tomakehurst.wiremock.testsupport.TestNotifier;\nimport org.junit.Test;\nimport javax.net.ssl.ExtendedSSLSession;\n@@ -13,7 +14,10 @@ import java.security.Principal;\nimport java.security.cert.X509Certificate;\nimport java.util.Collections;\n+import static java.lang.System.lineSeparator;\nimport static java.util.Arrays.asList;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.contains;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.BDDMockito.given;\n@@ -27,11 +31,13 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nprivate final SSLEngine nullSslEngine = null;\nprivate final SSLSession nonExtendedSslSessionMock = mock(SSLSession.class);\nprivate final ExtendedSSLSession extendedSslSessionMock = mock(ExtendedSSLSession.class);\n+ private final TestNotifier testNotifier = new TestNotifier();\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\nmock(DynamicKeyStore.class),\n- new SunHostNameMatcher()\n+ new SunHostNameMatcher(),\n+ testNotifier\n);\nprivate final Principal[] nullPrincipals = null;\n@@ -65,6 +71,10 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nString alias = certificateGeneratingKeyManager.chooseEngineServerAlias(\"RSA\", nullPrincipals, sslEngineMock);\nassertEquals(\"default_alias\", alias);\n+ assertThat(testNotifier.getErrorMessages(), contains(\n+ \"Dynamic certificate generation is not supported because your SSL Provider does not support SSLEngine.getHandshakeSession()\" + lineSeparator() +\n+ \"All sites will be served using the normal WireMock HTTPS certificate.\"\n+ ));\n}\n@Test\n@@ -83,6 +93,10 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nString alias = certificateGeneratingKeyManager.chooseEngineServerAlias(\"RSA\", nullPrincipals, sslEngineMock);\nassertEquals(\"default_alias\", alias);\n+ assertThat(testNotifier.getErrorMessages(), contains(\n+ \"Dynamic certificate generation is not supported because your SSL Provider does not support ExtendedSSLSession.getRequestedServerNames()\" + lineSeparator() +\n+ \"All sites will be served using the normal WireMock HTTPS certificate.\"\n+ ));\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n+import com.github.tomakehurst.wiremock.testsupport.TestNotifier;\nimport org.junit.Test;\nimport javax.net.ssl.ExtendedSSLSession;\n@@ -113,7 +114,8 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nreturn new CertificateGeneratingX509ExtendedKeyManager(\nkeyManager,\nnew DynamicKeyStore(x509KeyStore, x509KeyStore.getCertificateAuthority()),\n- new SunHostNameMatcher()\n+ new SunHostNameMatcher(),\n+ new TestNotifier()\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\n-import com.github.tomakehurst.wiremock.crypto.Secret;\n+import com.github.tomakehurst.wiremock.testsupport.TestNotifier;\nimport org.junit.Test;\nimport javax.net.ssl.ExtendedSSLSession;\n@@ -16,9 +15,11 @@ import java.security.Principal;\nimport java.security.cert.X509Certificate;\nimport java.util.Collections;\n-import static com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore.KeyStoreType.JKS;\n+import static java.lang.System.lineSeparator;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.singletonList;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.contains;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNull;\nimport static org.mockito.BDDMockito.given;\n@@ -33,11 +34,13 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nprivate final SSLSocket sslSocketMock = mock(SSLSocket.class);\nprivate final SSLSession nonExtendedSslSessionMock = mock(SSLSession.class);\nprivate final ExtendedSSLSession extendedSslSessionMock = mock(ExtendedSSLSession.class);\n+ private final TestNotifier testNotifier = new TestNotifier();\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\nmock(DynamicKeyStore.class),\n- new SunHostNameMatcher()\n+ new SunHostNameMatcher(),\n+ testNotifier\n);\nprivate final Principal[] nullPrincipals = null;\n@@ -80,6 +83,10 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nString alias = certificateGeneratingKeyManager.chooseServerAlias(\"RSA\", nullPrincipals, sslSocketMock);\nassertEquals(\"default_alias\", alias);\n+ assertThat(testNotifier.getErrorMessages(), contains(\n+ \"Dynamic certificate generation is not supported because your SSL Provider does not support SSLSocket.getHandshakeSession()\" + lineSeparator() +\n+ \"All sites will be served using the normal WireMock HTTPS certificate.\"\n+ ));\n}\n@Test\n@@ -98,6 +105,10 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nString alias = certificateGeneratingKeyManager.chooseServerAlias(\"RSA\", nullPrincipals, sslSocketMock);\nassertEquals(\"default_alias\", alias);\n+ assertThat(testNotifier.getErrorMessages(), contains(\n+ \"Dynamic certificate generation is not supported because your SSL Provider does not support ExtendedSSLSession.getRequestedServerNames()\" + lineSeparator() +\n+ \"All sites will be served using the normal WireMock HTTPS certificate.\"\n+ ));\n}\n@Test\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add useful logging if certificates cannot be generated
686,981
12.06.2020 17:48:10
-3,600
6d9080bea2d5940c7ad9533382defdef45aca1e7
Document certificate generation When you provide your own certificate.
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -150,6 +150,29 @@ As WireMock is here running as a man-in-the-middle, the resulting traffic will\nappear to the client encrypted with WireMock's (configurable) private key &\ncertificate, and so will not be trusted by default by clients.\n+Adding WireMock's certificate to your trusted certs (whether those of the O/S or\n+the browser) will not solve this[1], as clients should verify that the\n+certificate is for the requested hostname. To work around this, you can generate\n+your own keystore containing a private key and certificate that are able to act\n+as a root certificate for signing other certificates. When WireMock is started\n+with a JKS keystore (via `WireMockConfiguration.keystorePath()` or\n+`--https-keystore` when running standalone) containing such a certificate, it\n+will serve browser proxied https traffic using a newly generated certificate per\n+requested hostname, valid for that hostname. You can then trust that root\n+certificate and be able to browse all sites proxied via WireMock.\n+\n+A few caveats:\n+* The keystore must be in JKS format\n+* This depends on internal sun classes; it works with OepnJDK 1.8 -> 14, but may\n+ stop working in future versions or on other runtimes\n+* It's your responsibility to keep that private key & keystore secure - if you\n+ add it to your trusted certs then anyone getting hold of it could potentially\n+ get access to any service you use on the web.\n+\n+TODO: Document how to generate such a keystore, and how to trust its\n+certificate, on Linux, OS/X & Windows.\n+\n+\nProxying of HTTPS traffic when the proxy endpoint is also HTTPS is problematic;\nPostman seems not to cope with an HTTPS proxy even to proxy HTTP traffic. Older\nversions of curl fail trying to do the CONNECT call because they try to do so\n@@ -166,6 +189,8 @@ docker run --rm -it -p 44300:44300 wernight/spdyproxy\ncurl --proxy-insecure -x https://localhost:44300 -k 'https://www.example.com/'\n```\n+[1] It would also be a security risk as the private key is in the public domain\n+\n## Proxying via another proxy server\nIf you're inside a network that only permits HTTP traffic out to the\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Document certificate generation When you provide your own certificate.
686,981
15.06.2020 16:11:55
-3,600
7411a6206951d6e4d0bd1fb5e2ff08bcff019abd
Allow specifying https-keystore without https-port WireMock can now proxy HTTPS over its HTTP port. This means it's valid to provide a keystore to configure how that HTTPS is encrypted despite not listening for HTTPS directly.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -171,9 +171,6 @@ public class CommandLineOptions implements Options {\nif (!optionSet.has(HTTPS_PORT) && optionSet.has(DISABLE_HTTP)) {\nthrow new IllegalArgumentException(\"HTTPS must be enabled if HTTP is not.\");\n}\n- if (optionSet.has(HTTPS_KEYSTORE) && !optionSet.has(HTTPS_PORT)) {\n- throw new IllegalArgumentException(\"HTTPS port number must be specified if specifying the keystore path\");\n- }\nif (optionSet.has(RECORD_MAPPINGS) && optionSet.has(DISABLE_REQUEST_JOURNAL)) {\nthrow new IllegalArgumentException(\"Request journal must be enabled to record stubs\");\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -127,11 +127,6 @@ public class CommandLineOptionsTest {\nassertThat(options.httpsSettings().keyStorePassword(), is(\"someotherpwd\"));\n}\n- @Test(expected=IllegalArgumentException.class)\n- public void throwsExceptionIfKeyStoreSpecifiedWithoutHttpsPort() {\n- new CommandLineOptions(\"--https-keystore\", \"/my/keystore\");\n- }\n-\n@Test(expected=Exception.class)\npublic void throwsExceptionWhenPortNumberSpecifiedWithoutNumber() {\nnew CommandLineOptions(\"--port\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Allow specifying https-keystore without https-port WireMock can now proxy HTTPS over its HTTP port. This means it's valid to provide a keystore to configure how that HTTPS is encrypted despite not listening for HTTPS directly.
686,981
15.06.2020 17:51:20
-3,600
396e4c870775f37e4ff2efe80c8e6af91ca7ef8e
Document generating & trusting a root cert on OS/X
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -169,9 +169,14 @@ A few caveats:\nadd it to your trusted certs then anyone getting hold of it could potentially\nget access to any service you use on the web.\n-TODO: Document how to generate such a keystore, and how to trust its\n-certificate, on Linux, OS/X & Windows.\n-\n+> See [this script](https://github.com/tomakehurst/wiremock/blob/master/scripts/create-ca-cert.sh)\n+> for an example of how to build a valid self-signed root certificate called\n+> ca-cert.crt already imported into a keystore called ca-cert.jks.\n+>\n+> On OS/X it can be trusted by dragging ca-cert.crt onto Keychain Access,\n+> double clicking on the certificate and setting SSL to \"always trust\".\n+>\n+> Please raise PRs to add documentation for other platforms.\nProxying of HTTPS traffic when the proxy endpoint is also HTTPS is problematic;\nPostman seems not to cope with an HTTPS proxy even to proxy HTTP traffic. Older\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/ca-cert.conf", "diff": "+[req]\n+default_bits = 4096\n+prompt = no\n+default_md = sha256\n+distinguished_name = req_distinguished_name\n+x509_extensions = v3_ca\n+default_days = 36525\n+\n+[req_distinguished_name]\n+C = GB\n+ST = London\n+O = WireMock\n+CN = WireMock Local Self Signed Root Certificate\n+\n+[v3_ca]\n+subjectKeyIdentifier = hash\n+authorityKeyIdentifier = keyid:always\n+basicConstraints = critical, CA:TRUE\n+keyUsage = critical, keyCertSign, cRLSign\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/create-ca-keystore.sh", "diff": "+#!/usr/bin/env bash\n+\n+set -euo pipefail\n+read -r -s -p \"Please enter a password for the key & keystore (default: password):\" PASSWORD\n+PASSWORD=${PASSWORD:=password}\n+openssl req -x509 -newkey rsa:2048 -utf8 -days 3650 -nodes -config ca-cert.conf -keyout ca-cert.key -out ca-cert.crt\n+openssl pkcs12 -export -inkey ca-cert.key -in ca-cert.crt -out ca-cert.p12 -password \"pass:$PASSWORD\"\n+keytool -importkeystore -deststorepass \"$PASSWORD\" -destkeypass \"$PASSWORD\" -srckeystore ca-cert.p12 -srcstorepass \"$PASSWORD\" -deststoretype jks -destkeystore ca-cert.jks\n+rm ca-cert.key ca-cert.p12\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Document generating & trusting a root cert on OS/X
686,981
16.06.2020 12:08:12
-3,600
aa08d34ea203e53893ea955e4630759c796e5822
Document gotchas when running an HTTPS browser proxy
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -186,6 +186,15 @@ of writing it works using `curl 7.64.1 (x86_64-apple-darwin19.0) libcurl/7.64.1\n```bash\ncurl --proxy-insecure -x https://localhost:8443 -k 'https://www.example.com/'\n```\n+You can force HTTP/1.1 in curl as so:\n+```bash\n+curl --http1.1 --proxy-insecure -x https://localhost:8443 -k 'https://www.example.com/'\n+```\n+\n+Many client proxy settings which distinguish between secure and insecure are\n+actually referring to the target site's protocol, not the protocol of the proxy,\n+and assume the proxy will be listening for an HTTP CONNECT request when proxying\n+an HTTPS site.\nPlease check your client's behaviour proxying via another https proxy such as\nhttps://hub.docker.com/r/wernight/spdyproxy to see if it is a client problem:\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Document gotchas when running an HTTPS browser proxy
686,981
16.06.2020 21:34:57
-3,600
cf488ba1ffc88b40fa3b4c0be1dcb74cf9c47373
Use the WireMockClassRule tp setup the test proxy Don't know why I didn't do that in the first place...
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -77,14 +77,8 @@ public class HttpsBrowserProxyAcceptanceTest {\n@Rule\npublic WireMockClassRule instanceRule = target;\n- private WireMockServer proxy;\n- private WireMockTestClient testClient;\n-\n- @Before\n- public void addAResourceToProxy() {\n- testClient = new WireMockTestClient(target.httpsPort());\n-\n- proxy = new WireMockServer(wireMockConfig()\n+ @ClassRule\n+ public static WireMockClassRule proxy = new WireMockClassRule(wireMockConfig()\n.dynamicPort()\n.dynamicHttpsPort()\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n@@ -92,14 +86,15 @@ public class HttpsBrowserProxyAcceptanceTest {\n.trustAllProxyTargets(true)\n.keystorePath(PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT)\n);\n- proxy.start();\n- }\n- @After\n- public void stopServer() {\n- if (proxy.isRunning()) {\n- proxy.stop();\n- }\n+ @Rule\n+ public WireMockClassRule instanceProxyRule = target;\n+\n+ private WireMockTestClient testClient;\n+\n+ @Before\n+ public void addAResourceToProxy() {\n+ testClient = new WireMockTestClient(target.httpsPort());\n}\n@Test\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Use the WireMockClassRule tp setup the test proxy Don't know why I didn't do that in the first place...
686,981
16.06.2020 21:42:55
-3,600
077fb875401df18f45d33a668f5e0b57675da2e9
Use a specific proxy for the unusual case The general case is the one where we don't configure a specific CA keystore
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -35,7 +35,6 @@ import org.eclipse.jetty.client.HttpProxy;\nimport org.eclipse.jetty.client.Origin;\nimport org.eclipse.jetty.client.ProxyConfiguration;\nimport org.eclipse.jetty.client.api.ContentResponse;\n-import org.junit.After;\nimport org.junit.Before;\nimport org.junit.ClassRule;\nimport org.junit.Ignore;\n@@ -84,11 +83,10 @@ public class HttpsBrowserProxyAcceptanceTest {\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n.enableBrowserProxying(true)\n.trustAllProxyTargets(true)\n- .keystorePath(PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT)\n);\n@Rule\n- public WireMockClassRule instanceProxyRule = target;\n+ public WireMockClassRule instanceProxyRule = proxy;\nprivate WireMockTestClient testClient;\n@@ -230,13 +228,22 @@ public class HttpsBrowserProxyAcceptanceTest {\n@Test\npublic void certificatesSignedWithUsersRootCertificate() throws Exception {\n+ WireMockServer proxyWithCustomCaKeyStore = new WireMockServer(wireMockConfig()\n+ .dynamicPort()\n+ .enableBrowserProxying(true)\n+ .trustAllProxyTargets(true)\n+ .caKeystorePath(PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT)\n+ );\n+\n+ try {\n+ proxyWithCustomCaKeyStore.start();\nKeyStore trustStore = HttpsAcceptanceTest.readKeyStore(PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT, \"password\");\n// given\nCloseableHttpClient httpClient = HttpClients.custom()\n.setDnsResolver(new CustomLocalTldDnsResolver(\"internal\"))\n.setSSLSocketFactory(sslSocketFactoryThatTrusts(trustStore))\n- .setProxy(new HttpHost(\"localhost\", proxy.port()))\n+ .setProxy(new HttpHost(\"localhost\", proxyWithCustomCaKeyStore.port()))\n.build();\n// when\n@@ -252,6 +259,9 @@ public class HttpsBrowserProxyAcceptanceTest {\n);\n// then no exception is thrown\n+ } finally {\n+ proxyWithCustomCaKeyStore.stop();\n+ }\n}\nprivate SSLConnectionSocketFactory sslSocketFactoryThatTrusts(KeyStore trustStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Use a specific proxy for the unusual case The general case is the one where we don't configure a specific CA keystore
686,981
16.06.2020 21:48:13
-3,600
8bfdf6b2bc6f39ca2f18951d4c06e7e783bb1135
Add failing test proving a CA keystore is generated
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -46,6 +46,7 @@ import java.io.File;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\n+import java.nio.file.Files;\nimport java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n@@ -65,6 +66,7 @@ public class HttpsBrowserProxyAcceptanceTest {\nprivate static final String TARGET_KEYSTORE_WITH_CUSTOM_CERT = TestFiles.KEY_STORE_PATH;\nprivate static final String PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT = TestFiles.KEY_STORE_WITH_CA_PATH;\n+ private static final String NO_PREEXISTING_KEYSTORE_PATH = tempFile(\"ca-keystore\", \"jks\");\n@ClassRule\npublic static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n@@ -264,6 +266,37 @@ public class HttpsBrowserProxyAcceptanceTest {\n}\n}\n+ @Test @Ignore(\"not yet implemented\")\n+ public void certificatesSignedWithGeneratedRootCertificate() throws Exception {\n+\n+ // Ensure the certificate has been generated by making a request\n+ testClient.getViaProxy(\"https://fake1.nowildcards1.internal:\" + target.httpsPort() + \"/whatever\", proxy.port());\n+\n+ // Certificate should be there now\n+ KeyStore trustStore = HttpsAcceptanceTest.readKeyStore(NO_PREEXISTING_KEYSTORE_PATH, \"password\");\n+\n+ // given\n+ CloseableHttpClient httpClient = HttpClients.custom()\n+ .setDnsResolver(new CustomLocalTldDnsResolver(\"internal\"))\n+ .setSSLSocketFactory(sslSocketFactoryThatTrusts(trustStore))\n+ .setProxy(new HttpHost(\"localhost\", proxy.port()))\n+ .build();\n+\n+ // when\n+ httpClient.execute(\n+ new HttpGet(\"https://fake1.nowildcards1.internal:\" + target.httpsPort() + \"/whatever\")\n+ );\n+\n+ // then no exception is thrown\n+\n+ // when\n+ httpClient.execute(\n+ new HttpGet(\"https://fake2.nowildcards2.internal:\" + target.httpsPort() + \"/whatever\")\n+ );\n+\n+ // then no exception is thrown\n+ }\n+\nprivate SSLConnectionSocketFactory sslSocketFactoryThatTrusts(KeyStore trustStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {\nSSLContext sslContext = SSLContextBuilder.create()\n.loadTrustMaterial(trustStore)\n@@ -303,4 +336,12 @@ public class HttpsBrowserProxyAcceptanceTest {\n}\n}\n}\n+\n+ private static String tempFile(String prefix, String jks) {\n+ try {\n+ return Files.createTempFile(prefix, jks).toFile().getAbsolutePath();\n+ } catch (IOException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add failing test proving a CA keystore is generated
686,981
17.06.2020 11:16:24
-3,600
77e8954ea9f1922d29521f0320b0e266c143f415
Make test proving a CA keystore is generated pass Code is procedural and needs refactoring
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "package com.github.tomakehurst.wiremock.jetty94;\n+import com.github.tomakehurst.wiremock.common.BrowserProxySettings;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\nimport com.github.tomakehurst.wiremock.common.JettySettings;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.Notifier;\n-import com.github.tomakehurst.wiremock.common.BrowserProxySettings;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\nimport com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\n-import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\n+import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\nimport com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\n@@ -30,11 +30,32 @@ import org.eclipse.jetty.server.ServerConnector;\nimport org.eclipse.jetty.server.SslConnectionFactory;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n+import sun.security.tools.keytool.CertAndKeyGen;\n+import sun.security.x509.AuthorityKeyIdentifierExtension;\n+import sun.security.x509.BasicConstraintsExtension;\n+import sun.security.x509.CertificateExtensions;\n+import sun.security.x509.KeyIdentifier;\n+import sun.security.x509.KeyUsageExtension;\n+import sun.security.x509.SubjectKeyIdentifierExtension;\n+import sun.security.x509.X500Name;\n+import sun.security.x509.X509Key;\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.X509ExtendedKeyManager;\n+import java.io.File;\n+import java.io.FileOutputStream;\n+import java.io.IOException;\n+import java.security.InvalidKeyException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.NoSuchProviderException;\n+import java.security.PrivateKey;\n+import java.security.SignatureException;\n+import java.security.cert.Certificate;\n+import java.security.cert.CertificateException;\n+import java.security.cert.X509Certificate;\n+import java.util.Date;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.util.Arrays.stream;\n@@ -157,11 +178,10 @@ public class Jetty94HttpServer extends JettyHttpServer {\nprivate SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, BrowserProxySettings browserProxySettings, final Notifier notifier) {\nKeyStoreSettings browserProxyCaKeyStore = browserProxySettings.caKeyStore();\n- final KeyStoreSettings keyStoreSettings;\n- if (browserProxyCaKeyStore.exists()) {\n- keyStoreSettings = browserProxyCaKeyStore;\n- } else {\n- keyStoreSettings = httpsSettings.keyStore();\n+ X509KeyStore x509KeyStore = getOrCreateX509KeyStore(browserProxyCaKeyStore);\n+ CertificateAuthority certificateAuthority = x509KeyStore.getCertificateAuthority();\n+ if (certificateAuthority == null) {\n+ throw new IllegalArgumentException(\"Keystore \"+browserProxyCaKeyStore.path()+\" does not contain a certificate that can act as a certificate authority\");\n}\nSslContextFactory.Server sslContextFactory = new SslContextFactory.Server() {\n@@ -170,7 +190,13 @@ public class Jetty94HttpServer extends JettyHttpServer {\nKeyManager[] managers = super.getKeyManagers(keyStore);\nreturn stream(managers).map(manager -> {\nif (manager instanceof X509ExtendedKeyManager) {\n- return certificateGeneratingX509ExtendedKeyManager(keyStore, (X509ExtendedKeyManager) manager, keyStoreSettings.password().toCharArray(), notifier);\n+ return new CertificateGeneratingX509ExtendedKeyManager(\n+ (X509ExtendedKeyManager) manager,\n+ new DynamicKeyStore(x509KeyStore, certificateAuthority),\n+ // TODO write a version of this that doesn't depend on sun internal classes\n+ new SunHostNameMatcher(),\n+ notifier\n+ );\n} else {\nreturn manager;\n}\n@@ -178,30 +204,81 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n};\n- setupKeyStore(sslContextFactory, keyStoreSettings);\n- sslContextFactory.setKeyStorePassword(keyStoreSettings.password());\n+ setupKeyStore(sslContextFactory, browserProxyCaKeyStore);\n+ sslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\nsetupClientAuth(sslContextFactory, httpsSettings);\nreturn sslContextFactory;\n}\n- private KeyManager certificateGeneratingX509ExtendedKeyManager(KeyStore keyStore, X509ExtendedKeyManager manager, char[] keyStorePassword, Notifier notifier) {\n- try {\n- X509KeyStore x509KeyStore = new X509KeyStore(keyStore, keyStorePassword);\n- CertificateAuthority certificateAuthority = x509KeyStore.getCertificateAuthority();\n- if (certificateAuthority != null) {\n- return new CertificateGeneratingX509ExtendedKeyManager(\n- manager,\n- new DynamicKeyStore(x509KeyStore, certificateAuthority),\n- // TODO write a version of this that doesn't depend on sun internal classes\n- new SunHostNameMatcher(),\n- notifier\n- );\n+ private X509KeyStore getOrCreateX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\n+ if (browserProxyCaKeyStore.exists()) {\n+ return toX509KeyStore(browserProxyCaKeyStore);\n} else {\n- return manager;\n+ return createX509KeyStoreWithCertificateAuthority(browserProxyCaKeyStore);\n+ }\n}\n+\n+ private X509KeyStore toX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\n+ try {\n+ return new X509KeyStore(browserProxyCaKeyStore.loadStore(), browserProxyCaKeyStore.password().toCharArray());\n} catch (KeyStoreException e) {\n// KeyStore must be loaded here, should never happen\nreturn throwUnchecked(e, null);\n}\n}\n+\n+ private X509KeyStore createX509KeyStoreWithCertificateAuthority(KeyStoreSettings browserProxyCaKeyStore) {\n+ try {\n+ KeyStore keyStore = KeyStore.getInstance(browserProxyCaKeyStore.type());\n+ char[] password = browserProxyCaKeyStore.password().toCharArray();\n+ keyStore.load(null, password);\n+ CertAndKeyGen newCertAndKey = new CertAndKeyGen(\"RSA\", \"SHA256WithRSA\");\n+ newCertAndKey.generate(2048);\n+ PrivateKey newKey = newCertAndKey.getPrivateKey();\n+\n+ X509Certificate certificate = newCertAndKey.getSelfCertificate(\n+ x500Name(\"WireMock Local Self Signed Root Certificate\"),\n+ new Date(),\n+ (long) 365 * 24 * 60 * 60 * 10,\n+ certificateAuthority(newCertAndKey.getPublicKey())\n+ );\n+ keyStore.setKeyEntry(\"wiremock-ca\", newKey, password, new Certificate[] { certificate });\n+ File file = new File(browserProxyCaKeyStore.path());\n+ file.getParentFile().mkdirs();\n+ try (FileOutputStream fos = new FileOutputStream(file)) {\n+ try {\n+ keyStore.store(fos, password);\n+ } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+ return new X509KeyStore(keyStore, password);\n+ } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | InvalidKeyException | SignatureException | NoSuchProviderException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private static X500Name x500Name(String name){\n+ try {\n+ return new X500Name(\"CN=\" + name);\n+ } catch (IOException e) {\n+ // X500Name throws IOException for a parse error (which isn't an IO problem...)\n+ // An SNIHostName should be guaranteed not to have a parse issue\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private static CertificateExtensions certificateAuthority(X509Key publicKey) throws IOException {\n+ KeyIdentifier keyId = new KeyIdentifier(publicKey);\n+ byte[] keyIdBytes = keyId.getIdentifier();\n+ CertificateExtensions extensions = new CertificateExtensions();\n+ extensions.set(AuthorityKeyIdentifierExtension.NAME, new AuthorityKeyIdentifierExtension(keyId, null, null));\n+ extensions.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(true, Integer.MAX_VALUE));\n+ KeyUsageExtension keyUsage = new KeyUsageExtension(new boolean[7]);\n+ keyUsage.set(KeyUsageExtension.KEY_CERTSIGN, true);\n+ keyUsage.set(KeyUsageExtension.CRL_SIGN, true);\n+ extensions.set(KeyUsageExtension.NAME, keyUsage);\n+ extensions.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(keyIdBytes));\n+ return extensions;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -47,6 +47,7 @@ import java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.nio.file.Files;\n+import java.nio.file.Path;\nimport java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n@@ -66,7 +67,7 @@ public class HttpsBrowserProxyAcceptanceTest {\nprivate static final String TARGET_KEYSTORE_WITH_CUSTOM_CERT = TestFiles.KEY_STORE_PATH;\nprivate static final String PROXY_KEYSTORE_WITH_CUSTOM_CA_CERT = TestFiles.KEY_STORE_WITH_CA_PATH;\n- private static final String NO_PREEXISTING_KEYSTORE_PATH = tempFile(\"ca-keystore\", \"jks\");\n+ private static final String NO_PREEXISTING_KEYSTORE_PATH = tempNonExistingPath(\"wiremock-keystores\", \"ca-keystore.jks\");\n@ClassRule\npublic static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n@@ -83,6 +84,7 @@ public class HttpsBrowserProxyAcceptanceTest {\n.dynamicPort()\n.dynamicHttpsPort()\n.fileSource(new SingleRootFileSource(setupTempFileRoot()))\n+ .caKeystorePath(NO_PREEXISTING_KEYSTORE_PATH)\n.enableBrowserProxying(true)\n.trustAllProxyTargets(true)\n);\n@@ -266,7 +268,7 @@ public class HttpsBrowserProxyAcceptanceTest {\n}\n}\n- @Test @Ignore(\"not yet implemented\")\n+ @Test\npublic void certificatesSignedWithGeneratedRootCertificate() throws Exception {\n// Ensure the certificate has been generated by making a request\n@@ -337,9 +339,10 @@ public class HttpsBrowserProxyAcceptanceTest {\n}\n}\n- private static String tempFile(String prefix, String jks) {\n+ private static String tempNonExistingPath(String prefix, String filename) {\ntry {\n- return Files.createTempFile(prefix, jks).toFile().getAbsolutePath();\n+ Path tempDirectory = Files.createTempDirectory(prefix);\n+ return tempDirectory.resolve(filename).toFile().getAbsolutePath();\n} catch (IOException e) {\nreturn throwUnchecked(e, null);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/WireMockTestClient.java", "diff": "@@ -333,7 +333,9 @@ public class WireMockTestClient {\nreturn SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {\n@Override\npublic boolean isTrusted(X509Certificate[] chain, String authType) {\n- return chain[0].getSubjectDN().getName().startsWith(\"CN=Tom Akehurst\");\n+ return chain[0].getSubjectDN().getName().startsWith(\"CN=Tom Akehurst\") ||\n+ chain[0].getSubjectDN().getName().equals(\"CN=WireMock Local Self Signed Root Certificate\") ||\n+ chain.length == 2 && chain[1].getSubjectDN().getName().equals(\"CN=WireMock Local Self Signed Root Certificate\");\n}\n}).build();\n} catch (Exception e) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Make test proving a CA keystore is generated pass Code is procedural and needs refactoring
686,981
17.06.2020 12:17:21
-3,600
b645653abe9e265ab0fa68bbc174a5d81d29135b
Make private files and directories suitably private
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -45,6 +45,9 @@ import javax.net.ssl.X509ExtendedKeyManager;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+import java.nio.file.Paths;\nimport java.security.InvalidKeyException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n@@ -56,8 +59,11 @@ import java.security.cert.Certificate;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.Date;\n+import java.util.EnumSet;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.nio.file.attribute.PosixFilePermission.*;\n+import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\nimport static java.util.Arrays.stream;\npublic class Jetty94HttpServer extends JettyHttpServer {\n@@ -243,9 +249,13 @@ public class Jetty94HttpServer extends JettyHttpServer {\ncertificateAuthority(newCertAndKey.getPublicKey())\n);\nkeyStore.setKeyEntry(\"wiremock-ca\", newKey, password, new Certificate[] { certificate });\n- File file = new File(browserProxyCaKeyStore.path());\n- file.getParentFile().mkdirs();\n- try (FileOutputStream fos = new FileOutputStream(file)) {\n+\n+ Path path = Paths.get(browserProxyCaKeyStore.path());\n+ if (!Files.exists(path.getParent())) {\n+ Files.createDirectory(path.getParent(), asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)));\n+ }\n+ Path created = Files.createFile(path, asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)));\n+ try (FileOutputStream fos = new FileOutputStream(created.toFile())) {\ntry {\nkeyStore.store(fos, password);\n} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Make private files and directories suitably private
687,008
16.06.2020 16:20:30
-7,200
41365c4b7a9cbb511ee145b0c9686e412886af2f
Added new command line parameters "--jetty-header-request-size" and "--jetty-header-response-size" for set a custom size of headers in Jetty. "--jetty-header-buffer-size" is deprecated.
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -117,9 +117,15 @@ accepting requests.\n`--jetty-accept-queue-size`: The Jetty queue size for accepted requests.\n-`--jetty-header-buffer-size`: The Jetty buffer size for request headers,\n+`--jetty-header-buffer-size`: Deprecated, use `--jetty-header-request-size`. The Jetty buffer size for request headers,\ne.g. `--jetty-header-buffer-size 16384`, defaults to 8192K.\n+`--jetty-header-request-size`: The Jetty buffer size for request headers,\n+e.g. `--jetty-header-request-size 16384`, defaults to 8192K.\n+\n+`--jetty-header-response-size`: The Jetty buffer size for response headers,\n+e.g. `--jetty-header-response-size 16384`, defaults to 8192K.\n+\n`--async-response-enabled`: Enable asynchronous request processing in Jetty.\nRecommended when using WireMock for performance testing with delays, as it allows much more efficient use of container threads and therefore higher throughput. Defaults to `false`.\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/JettySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/JettySettings.java", "diff": "@@ -24,15 +24,20 @@ public class JettySettings {\nprivate final Optional<Integer> acceptors;\nprivate final Optional<Integer> acceptQueueSize;\nprivate final Optional<Integer> requestHeaderSize;\n+ private final Optional<Integer> responseHeaderSize;\nprivate final Optional<Long> stopTimeout;\n- private JettySettings(Optional<Integer> acceptors,\n+ private JettySettings(\n+ Optional<Integer> acceptors,\nOptional<Integer> acceptQueueSize,\nOptional<Integer> requestHeaderSize,\n- Optional<Long> stopTimeout) {\n+ Optional<Integer> responseHeaderSize,\n+ Optional<Long> stopTimeout\n+ ) {\nthis.acceptors = acceptors;\nthis.acceptQueueSize = acceptQueueSize;\nthis.requestHeaderSize = requestHeaderSize;\n+ this.responseHeaderSize = responseHeaderSize;\nthis.stopTimeout = stopTimeout;\n}\n@@ -48,6 +53,10 @@ public class JettySettings {\nreturn requestHeaderSize;\n}\n+ public Optional<Integer> getResponseHeaderSize() {\n+ return responseHeaderSize;\n+ }\n+\npublic Optional<Long> getStopTimeout() {\nreturn stopTimeout;\n}\n@@ -58,6 +67,7 @@ public class JettySettings {\n\"acceptors=\" + acceptors +\n\", acceptQueueSize=\" + acceptQueueSize +\n\", requestHeaderSize=\" + requestHeaderSize +\n+ \", responseHeaderSize=\" + responseHeaderSize +\n'}';\n}\n@@ -65,6 +75,7 @@ public class JettySettings {\nprivate Integer acceptors;\nprivate Integer acceptQueueSize;\nprivate Integer requestHeaderSize;\n+ private Integer responseHeaderSize;\nprivate Long stopTimeout;\nprivate Builder() {\n@@ -89,16 +100,24 @@ public class JettySettings {\nreturn this;\n}\n+ public Builder withResponseHeaderSize(Integer responseHeaderSize) {\n+ this.responseHeaderSize = responseHeaderSize;\n+ return this;\n+ }\n+\npublic Builder withStopTimeout(Long stopTimeout) {\nthis.stopTimeout = stopTimeout;\nreturn this;\n}\npublic JettySettings build() {\n- return new JettySettings(Optional.fromNullable(acceptors),\n+ return new JettySettings(\n+ Optional.fromNullable(acceptors),\nOptional.fromNullable(acceptQueueSize),\nOptional.fromNullable(requestHeaderSize),\n- Optional.fromNullable(stopTimeout));\n+ Optional.fromNullable(responseHeaderSize),\n+ Optional.fromNullable(stopTimeout)\n+ );\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "diff": "@@ -82,6 +82,8 @@ public class WireMockConfiguration implements Options {\nprivate Integer jettyAcceptors;\nprivate Integer jettyAcceptQueueSize;\nprivate Integer jettyHeaderBufferSize;\n+ private Integer jettyHeaderRequestSize;\n+ private Integer jettyHeaderResponseSize;\nprivate Long jettyStopTimeout;\nprivate Map<String, Extension> extensions = newLinkedHashMap();\n@@ -158,11 +160,22 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ @Deprecated\npublic WireMockConfiguration jettyHeaderBufferSize(Integer jettyHeaderBufferSize) {\nthis.jettyHeaderBufferSize = jettyHeaderBufferSize;\nreturn this;\n}\n+ public WireMockConfiguration jettyHeaderRequestSize(Integer jettyHeaderRequestSize) {\n+ this.jettyHeaderRequestSize = jettyHeaderRequestSize;\n+ return this;\n+ }\n+\n+ public WireMockConfiguration jettyHeaderResponseSize(Integer jettyHeaderResponseSize) {\n+ this.jettyHeaderResponseSize = jettyHeaderResponseSize;\n+ return this;\n+ }\n+\npublic WireMockConfiguration jettyStopTimeout(Long jettyStopTimeout) {\nthis.jettyStopTimeout = jettyStopTimeout;\nreturn this;\n@@ -414,6 +427,8 @@ public class WireMockConfiguration implements Options {\n.withAcceptors(jettyAcceptors)\n.withAcceptQueueSize(jettyAcceptQueueSize)\n.withRequestHeaderSize(jettyHeaderBufferSize)\n+ .withRequestHeaderSize(jettyHeaderRequestSize)\n+ .withResponseHeaderSize(jettyHeaderResponseSize)\n.withStopTimeout(jettyStopTimeout)\n.build();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "@@ -55,6 +55,7 @@ public class JettyHttpServer implements HttpServer {\nprivate static final String FILES_URL_MATCH = String.format(\"/%s/*\", WireMockApp.FILES_ROOT);\nprivate static final String[] GZIPPABLE_METHODS = new String[] { \"POST\", \"PUT\", \"PATCH\", \"DELETE\" };\nprivate static final int DEFAULT_ACCEPTORS = 3;\n+ private static final int DEFAULT_HEADER_SIZE = 8192;\nstatic {\nSystem.setProperty(\"org.eclipse.jetty.server.HttpChannelState.DEFAULT_TIMEOUT\", \"300000\");\n@@ -314,7 +315,10 @@ public class JettyHttpServer implements HttpServer {\nprotected HttpConfiguration createHttpConfig(JettySettings jettySettings) {\nHttpConfiguration httpConfig = new HttpConfiguration();\nhttpConfig.setRequestHeaderSize(\n- jettySettings.getRequestHeaderSize().or(8192)\n+ jettySettings.getRequestHeaderSize().or(DEFAULT_HEADER_SIZE)\n+ );\n+ httpConfig.setResponseHeaderSize(\n+ jettySettings.getResponseHeaderSize().or(DEFAULT_HEADER_SIZE)\n);\nhttpConfig.setSendDateHeader(false);\nreturn httpConfig;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -81,7 +81,10 @@ public class CommandLineOptions implements Options {\nprivate static final String JETTY_ACCEPTOR_THREAD_COUNT = \"jetty-acceptor-threads\";\nprivate static final String PRINT_ALL_NETWORK_TRAFFIC = \"print-all-network-traffic\";\nprivate static final String JETTY_ACCEPT_QUEUE_SIZE = \"jetty-accept-queue-size\";\n+ @Deprecated\nprivate static final String JETTY_HEADER_BUFFER_SIZE = \"jetty-header-buffer-size\";\n+ private static final String JETTY_HEADER_REQUEST_SIZE = \"jetty-header-request-size\";\n+ private static final String JETTY_HEADER_RESPONSE_SIZE = \"jetty-header-response-size\";\nprivate static final String JETTY_STOP_TIMEOUT = \"jetty-stop-timeout\";\nprivate static final String ROOT_DIR = \"root-dir\";\nprivate static final String CONTAINER_THREADS = \"container-threads\";\n@@ -134,7 +137,9 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(MAX_ENTRIES_REQUEST_JOURNAL, \"Set maximum number of entries in request journal (if enabled) to discard old entries if the log becomes too large. Default: no discard\").withRequiredArg();\noptionParser.accepts(JETTY_ACCEPTOR_THREAD_COUNT, \"Number of Jetty acceptor threads\").withRequiredArg();\noptionParser.accepts(JETTY_ACCEPT_QUEUE_SIZE, \"The size of Jetty's accept queue size\").withRequiredArg();\n- optionParser.accepts(JETTY_HEADER_BUFFER_SIZE, \"The size of Jetty's buffer for request headers\").withRequiredArg();\n+ optionParser.accepts(JETTY_HEADER_BUFFER_SIZE, \"Deprecated. The size of Jetty's buffer for request headers\").withRequiredArg();\n+ optionParser.accepts(JETTY_HEADER_REQUEST_SIZE, \"The size of Jetty's buffer for request headers\").withRequiredArg();\n+ optionParser.accepts(JETTY_HEADER_RESPONSE_SIZE, \"The size of Jetty's buffer for response headers\").withRequiredArg();\noptionParser.accepts(JETTY_STOP_TIMEOUT, \"Timeout in milliseconds for Jetty to stop\").withRequiredArg();\noptionParser.accepts(PRINT_ALL_NETWORK_TRAFFIC, \"Print all raw incoming and outgoing network traffic to console\");\noptionParser.accepts(GLOBAL_RESPONSE_TEMPLATING, \"Preprocess all responses with Handlebars templates\");\n@@ -286,10 +291,19 @@ public class CommandLineOptions implements Options {\nbuilder = builder.withAcceptQueueSize(Integer.parseInt((String) optionSet.valueOf(JETTY_ACCEPT_QUEUE_SIZE)));\n}\n+ //@Deprecated\nif (optionSet.hasArgument(JETTY_HEADER_BUFFER_SIZE)) {\nbuilder = builder.withRequestHeaderSize(Integer.parseInt((String) optionSet.valueOf(JETTY_HEADER_BUFFER_SIZE)));\n}\n+ if (optionSet.hasArgument(JETTY_HEADER_REQUEST_SIZE)) {\n+ builder = builder.withRequestHeaderSize(Integer.parseInt((String) optionSet.valueOf(JETTY_HEADER_REQUEST_SIZE)));\n+ }\n+\n+ if (optionSet.hasArgument(JETTY_HEADER_RESPONSE_SIZE)) {\n+ builder = builder.withResponseHeaderSize(Integer.parseInt((String) optionSet.valueOf(JETTY_HEADER_RESPONSE_SIZE)));\n+ }\n+\nif (optionSet.hasArgument(JETTY_STOP_TIMEOUT)) {\nbuilder = builder.withStopTimeout(Long.parseLong((String) optionSet.valueOf(JETTY_STOP_TIMEOUT)));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/JettySettingsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/JettySettingsTest.java", "diff": "@@ -35,12 +35,14 @@ public class JettySettingsTest {\nbuilder.withAcceptors(number)\n.withAcceptQueueSize(number)\n.withRequestHeaderSize(number)\n+ .withResponseHeaderSize(number)\n.withStopTimeout(longNumber);\nJettySettings jettySettings = builder.build();\nensurePresent(jettySettings.getAcceptors());\nensurePresent(jettySettings.getAcceptQueueSize());\nensurePresent(jettySettings.getRequestHeaderSize());\n+ ensurePresent(jettySettings.getResponseHeaderSize());\nensureLongPresent(jettySettings.getStopTimeout());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -255,11 +255,24 @@ public class CommandLineOptionsTest {\n}\n@Test\n+ @Deprecated\npublic void returnsCorrectlyParsedJettyHeaderBufferSize() {\nCommandLineOptions options = new CommandLineOptions(\"--jetty-header-buffer-size\", \"16384\");\nassertThat(options.jettySettings().getRequestHeaderSize().get(), is(16384));\n}\n+ @Test\n+ public void returnsCorrectlyParsedJettyHeaderRequestSize() {\n+ CommandLineOptions options = new CommandLineOptions(\"--jetty-header-request-size\", \"16384\");\n+ assertThat(options.jettySettings().getRequestHeaderSize().get(), is(16384));\n+ }\n+\n+ @Test\n+ public void returnsCorrectlyParsedJettyHeaderResponseSize() {\n+ CommandLineOptions options = new CommandLineOptions(\"--jetty-header-response-size\", \"16384\");\n+ assertThat(options.jettySettings().getResponseHeaderSize().get(), is(16384));\n+ }\n+\n@Test\npublic void returnsCorrectlyParsedJettyStopTimeout() {\nCommandLineOptions options = new CommandLineOptions(\"--jetty-stop-timeout\", \"1000\");\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/ignored/Examples.java", "new_path": "src/test/java/ignored/Examples.java", "diff": "@@ -398,9 +398,15 @@ public class Examples extends AcceptanceTestBase {\n// Set the Jetty accept queue size. Defaults to Jetty's default of unbounded.\n.jettyAcceptQueueSize(100)\n- // Set the size of Jetty's header buffer (to avoid exceptions when very large request headers are sent). Defaults to 8192.\n+ // Deprecated. Set the size of Jetty's header buffer (to avoid exceptions when very large request headers are sent). Defaults to 8192.\n.jettyHeaderBufferSize(16834)\n+ // Set the size of Jetty's request header buffer (to avoid exceptions when very large request headers are sent). Defaults to 8192.\n+ .jettyHeaderRequestSize(16834)\n+\n+ // Set the size of Jetty's response header buffer (to avoid exceptions when very large request headers are sent). Defaults to 8192.\n+ .jettyHeaderResponseSize(16834)\n+\n// Set the timeout to wait for Jetty to stop in milliseconds. Defaults to 0 (no wait)\n.jettyStopTimeout(5000L)\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added new command line parameters "--jetty-header-request-size" and "--jetty-header-response-size" for set a custom size of headers in Jetty. "--jetty-header-buffer-size" is deprecated.
686,981
17.06.2020 14:54:11
-3,600
f2c0fd5c17a11032c9f446bffaff4120fb743d4c
Exclude classes that use sun classes from JavaDoc Otherwise can't build on a JDK >= 9
[ { "change_type": "MODIFY", "old_path": "java8/build.gradle", "new_path": "java8/build.gradle", "diff": "@@ -28,3 +28,9 @@ compileJava {\noptions.forkOptions.executable = 'javac'\noptions.compilerArgs += '-XDignore.symbol.file'\n}\n+\n+javadoc {\n+ exclude \"**/CertificateAuthority.java\"\n+ exclude \"**/Jetty94HttpServer.java\"\n+ exclude \"**/SunHostNameMatcher.java\"\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Exclude classes that use sun classes from JavaDoc Otherwise can't build on a JDK >= 9
686,981
17.06.2020 14:55:35
-3,600
750bfd246e5af5773c5ef1ca18ae69f64ed1a530
Make keystore generation work on Windows
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -42,12 +42,13 @@ import sun.security.x509.X509Key;\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.X509ExtendedKeyManager;\n-import java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\n+import java.nio.file.FileSystems;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\n+import java.nio.file.attribute.FileAttribute;\nimport java.security.InvalidKeyException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\n@@ -250,11 +251,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\n);\nkeyStore.setKeyEntry(\"wiremock-ca\", newKey, password, new Certificate[] { certificate });\n- Path path = Paths.get(browserProxyCaKeyStore.path());\n- if (!Files.exists(path.getParent())) {\n- Files.createDirectory(path.getParent(), asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)));\n- }\n- Path created = Files.createFile(path, asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)));\n+ Path created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\ntry (FileOutputStream fos = new FileOutputStream(created.toFile())) {\ntry {\nkeyStore.store(fos, password);\n@@ -268,6 +265,19 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n}\n+ private Path createCaKeystoreFile(Path path) throws IOException {\n+ FileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\n+ FileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n+ if (FileSystems.getDefault().supportedFileAttributeViews().contains(\"posix\")) {\n+ privateDirAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)) };\n+ privateFileAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)) };\n+ }\n+ if (!Files.exists(path.getParent())) {\n+ Files.createDirectories(path.getParent(), privateDirAttrs);\n+ }\n+ return Files.createFile(path, privateFileAttrs);\n+ }\n+\nprivate static X500Name x500Name(String name){\ntry {\nreturn new X500Name(\"CN=\" + name);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Make keystore generation work on Windows
686,981
18.06.2020 09:26:22
-3,600
e3d186f0014c5af141795e150ae57635d618b49c
Separate out cert generation logic
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -32,7 +32,7 @@ public class CertificateAuthority {\nprivate final X509Certificate[] certificateChain;\nprivate final PrivateKey key;\n- CertificateAuthority(X509Certificate[] certificateChain, PrivateKey key) {\n+ public CertificateAuthority(X509Certificate[] certificateChain, PrivateKey key) {\nthis.certificateChain = requireNonNull(certificateChain);\nif (certificateChain.length == 0) {\nthrow new IllegalArgumentException(\"Chain must have entries\");\n@@ -40,6 +40,14 @@ public class CertificateAuthority {\nthis.key = requireNonNull(key);\n}\n+ public X509Certificate[] certificateChain() {\n+ return certificateChain;\n+ }\n+\n+ public PrivateKey key() {\n+ return key;\n+ }\n+\nCertChainAndKey generateCertificate(\nString keyType,\nSNIHostName hostName\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -239,17 +239,8 @@ public class Jetty94HttpServer extends JettyHttpServer {\nKeyStore keyStore = KeyStore.getInstance(browserProxyCaKeyStore.type());\nchar[] password = browserProxyCaKeyStore.password().toCharArray();\nkeyStore.load(null, password);\n- CertAndKeyGen newCertAndKey = new CertAndKeyGen(\"RSA\", \"SHA256WithRSA\");\n- newCertAndKey.generate(2048);\n- PrivateKey newKey = newCertAndKey.getPrivateKey();\n-\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(\n- x500Name(\"WireMock Local Self Signed Root Certificate\"),\n- new Date(),\n- (long) 365 * 24 * 60 * 60 * 10,\n- certificateAuthorityExtensions(newCertAndKey.getPublicKey())\n- );\n- keyStore.setKeyEntry(\"wiremock-ca\", newKey, password, new Certificate[] { certificate });\n+ CertificateAuthority certificateAuthority = generateCertificateAuthority();\n+ keyStore.setKeyEntry(\"wiremock-ca\", certificateAuthority.key(), password, certificateAuthority.certificateChain());\nPath created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\ntry (FileOutputStream fos = new FileOutputStream(created.toFile())) {\n@@ -265,6 +256,20 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n}\n+ private CertificateAuthority generateCertificateAuthority() throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, SignatureException, NoSuchProviderException, IOException {\n+ CertAndKeyGen newCertAndKey = new CertAndKeyGen(\"RSA\", \"SHA256WithRSA\");\n+ newCertAndKey.generate(2048);\n+ PrivateKey newKey = newCertAndKey.getPrivateKey();\n+\n+ X509Certificate certificate = newCertAndKey.getSelfCertificate(\n+ x500Name(\"WireMock Local Self Signed Root Certificate\"),\n+ new Date(),\n+ (long) 365 * 24 * 60 * 60 * 10,\n+ certificateAuthorityExtensions(newCertAndKey.getPublicKey())\n+ );\n+ return new CertificateAuthority(new X509Certificate[]{ certificate }, newKey);\n+ }\n+\nprivate Path createCaKeystoreFile(Path path) throws IOException {\nFileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\nFileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Separate out cert generation logic
686,981
18.06.2020 09:43:32
-3,600
f9188e62cc7f774216b4494596d79d4834cbd653
Move CA generation onto CertificateAuthority Breaks dependency on sun.security in Jetty94HttpServer
[ { "change_type": "MODIFY", "old_path": "java8/build.gradle", "new_path": "java8/build.gradle", "diff": "@@ -31,6 +31,5 @@ compileJava {\njavadoc {\nexclude \"**/CertificateAuthority.java\"\n- exclude \"**/Jetty94HttpServer.java\"\nexclude \"**/SunHostNameMatcher.java\"\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\nimport sun.security.tools.keytool.CertAndKeyGen;\n+import sun.security.x509.AuthorityKeyIdentifierExtension;\n+import sun.security.x509.BasicConstraintsExtension;\nimport sun.security.x509.CertificateExtensions;\nimport sun.security.x509.DNSName;\nimport sun.security.x509.GeneralName;\nimport sun.security.x509.GeneralNames;\n+import sun.security.x509.KeyIdentifier;\n+import sun.security.x509.KeyUsageExtension;\nimport sun.security.x509.SubjectAlternativeNameExtension;\n+import sun.security.x509.SubjectKeyIdentifierExtension;\nimport sun.security.x509.X500Name;\nimport sun.security.x509.X509CertImpl;\nimport sun.security.x509.X509CertInfo;\n+import sun.security.x509.X509Key;\nimport javax.net.ssl.SNIHostName;\nimport java.io.IOException;\n@@ -40,6 +46,38 @@ public class CertificateAuthority {\nthis.key = requireNonNull(key);\n}\n+ public static CertificateAuthority generateCertificateAuthority() throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, SignatureException, NoSuchProviderException, IOException {\n+ CertAndKeyGen newCertAndKey = new CertAndKeyGen(\"RSA\", \"SHA256WithRSA\");\n+ newCertAndKey.generate(2048);\n+ PrivateKey newKey = newCertAndKey.getPrivateKey();\n+\n+ X509Certificate certificate = newCertAndKey.getSelfCertificate(\n+ x500Name(\"WireMock Local Self Signed Root Certificate\"),\n+ new Date(),\n+ (long) 365 * 24 * 60 * 60 * 10,\n+ certificateAuthorityExtensions(newCertAndKey.getPublicKey())\n+ );\n+ return new CertificateAuthority(new X509Certificate[]{ certificate }, newKey);\n+ }\n+\n+ private static CertificateExtensions certificateAuthorityExtensions(X509Key publicKey) throws IOException {\n+ KeyIdentifier keyId = new KeyIdentifier(publicKey);\n+ byte[] keyIdBytes = keyId.getIdentifier();\n+ CertificateExtensions extensions = new CertificateExtensions();\n+ extensions.set(AuthorityKeyIdentifierExtension.NAME, new AuthorityKeyIdentifierExtension(keyId, null, null));\n+\n+ extensions.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(true, Integer.MAX_VALUE));\n+\n+ KeyUsageExtension keyUsage = new KeyUsageExtension(new boolean[7]);\n+ keyUsage.set(KeyUsageExtension.KEY_CERTSIGN, true);\n+ keyUsage.set(KeyUsageExtension.CRL_SIGN, true);\n+ extensions.set(KeyUsageExtension.NAME, keyUsage);\n+\n+ extensions.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(keyIdBytes));\n+\n+ return extensions;\n+ }\n+\npublic X509Certificate[] certificateChain() {\nreturn certificateChain;\n}\n@@ -59,7 +97,7 @@ public class CertificateAuthority {\nPrivateKey newKey = newCertAndKey.getPrivateKey();\nX509Certificate certificate = newCertAndKey.getSelfCertificate(\n- x500Name(hostName),\n+ x500Name(hostName.getAsciiName()),\nnew Date(),\n(long) 365 * 24 * 60 * 60,\nsubjectAlternativeName(hostName)\n@@ -76,9 +114,9 @@ public class CertificateAuthority {\n}\n}\n- private X500Name x500Name(SNIHostName hostName) {\n+ private static X500Name x500Name(String name){\ntry {\n- return new X500Name(\"CN=\" + hostName.getAsciiName());\n+ return new X500Name(\"CN=\" + name);\n} catch (IOException e) {\n// X500Name throws IOException for a parse error (which isn't an IO problem...)\n// An SNIHostName should be guaranteed not to have a parse issue\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -30,15 +30,6 @@ import org.eclipse.jetty.server.ServerConnector;\nimport org.eclipse.jetty.server.SslConnectionFactory;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n-import sun.security.tools.keytool.CertAndKeyGen;\n-import sun.security.x509.AuthorityKeyIdentifierExtension;\n-import sun.security.x509.BasicConstraintsExtension;\n-import sun.security.x509.CertificateExtensions;\n-import sun.security.x509.KeyIdentifier;\n-import sun.security.x509.KeyUsageExtension;\n-import sun.security.x509.SubjectKeyIdentifierExtension;\n-import sun.security.x509.X500Name;\n-import sun.security.x509.X509Key;\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.X509ExtendedKeyManager;\n@@ -54,12 +45,8 @@ import java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.NoSuchProviderException;\n-import java.security.PrivateKey;\nimport java.security.SignatureException;\n-import java.security.cert.Certificate;\nimport java.security.cert.CertificateException;\n-import java.security.cert.X509Certificate;\n-import java.util.Date;\nimport java.util.EnumSet;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -239,7 +226,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\nKeyStore keyStore = KeyStore.getInstance(browserProxyCaKeyStore.type());\nchar[] password = browserProxyCaKeyStore.password().toCharArray();\nkeyStore.load(null, password);\n- CertificateAuthority certificateAuthority = generateCertificateAuthority();\n+ CertificateAuthority certificateAuthority = CertificateAuthority.generateCertificateAuthority();\nkeyStore.setKeyEntry(\"wiremock-ca\", certificateAuthority.key(), password, certificateAuthority.certificateChain());\nPath created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\n@@ -256,20 +243,6 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n}\n- private CertificateAuthority generateCertificateAuthority() throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, SignatureException, NoSuchProviderException, IOException {\n- CertAndKeyGen newCertAndKey = new CertAndKeyGen(\"RSA\", \"SHA256WithRSA\");\n- newCertAndKey.generate(2048);\n- PrivateKey newKey = newCertAndKey.getPrivateKey();\n-\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(\n- x500Name(\"WireMock Local Self Signed Root Certificate\"),\n- new Date(),\n- (long) 365 * 24 * 60 * 60 * 10,\n- certificateAuthorityExtensions(newCertAndKey.getPublicKey())\n- );\n- return new CertificateAuthority(new X509Certificate[]{ certificate }, newKey);\n- }\n-\nprivate Path createCaKeystoreFile(Path path) throws IOException {\nFileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\nFileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n@@ -282,32 +255,4 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\nreturn Files.createFile(path, privateFileAttrs);\n}\n-\n- private static X500Name x500Name(String name){\n- try {\n- return new X500Name(\"CN=\" + name);\n- } catch (IOException e) {\n- // X500Name throws IOException for a parse error (which isn't an IO problem...)\n- // An SNIHostName should be guaranteed not to have a parse issue\n- return throwUnchecked(e, null);\n- }\n- }\n-\n- private static CertificateExtensions certificateAuthorityExtensions(X509Key publicKey) throws IOException {\n- KeyIdentifier keyId = new KeyIdentifier(publicKey);\n- byte[] keyIdBytes = keyId.getIdentifier();\n- CertificateExtensions extensions = new CertificateExtensions();\n- extensions.set(AuthorityKeyIdentifierExtension.NAME, new AuthorityKeyIdentifierExtension(keyId, null, null));\n-\n- extensions.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(true, Integer.MAX_VALUE));\n-\n- KeyUsageExtension keyUsage = new KeyUsageExtension(new boolean[7]);\n- keyUsage.set(KeyUsageExtension.KEY_CERTSIGN, true);\n- keyUsage.set(KeyUsageExtension.CRL_SIGN, true);\n- extensions.set(KeyUsageExtension.NAME, keyUsage);\n-\n- extensions.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(keyIdBytes));\n-\n- return extensions;\n- }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Move CA generation onto CertificateAuthority Breaks dependency on sun.security in Jetty94HttpServer
686,981
18.06.2020 10:31:51
-3,600
a51285d5ae3c885a3bedf199ce135020828f0c4c
Reduce duplication in generating certificates
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "@@ -26,7 +26,11 @@ import java.security.PrivateKey;\nimport java.security.SignatureException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\n+import java.time.Duration;\n+import java.time.Period;\n+import java.time.ZonedDateTime;\nimport java.util.Date;\n+import java.util.function.Function;\nimport static com.github.tomakehurst.wiremock.common.ArrayFunctions.prepend;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -46,21 +50,19 @@ public class CertificateAuthority {\nthis.key = requireNonNull(key);\n}\n- public static CertificateAuthority generateCertificateAuthority() throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, SignatureException, NoSuchProviderException, IOException {\n- CertAndKeyGen newCertAndKey = new CertAndKeyGen(\"RSA\", \"SHA256WithRSA\");\n- newCertAndKey.generate(2048);\n- PrivateKey newKey = newCertAndKey.getPrivateKey();\n-\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(\n- x500Name(\"WireMock Local Self Signed Root Certificate\"),\n- new Date(),\n- (long) 365 * 24 * 60 * 60 * 10,\n- certificateAuthorityExtensions(newCertAndKey.getPublicKey())\n+ public static CertificateAuthority generateCertificateAuthority() throws CertificateGenerationUnsupportedException {\n+ CertChainAndKey certChainAndKey = generateCertChainAndKey(\n+ \"RSA\",\n+ \"SHA256WithRSA\",\n+ \"WireMock Local Self Signed Root Certificate\",\n+ Period.ofYears(10),\n+ CertificateAuthority::certificateAuthorityExtensions\n);\n- return new CertificateAuthority(new X509Certificate[]{ certificate }, newKey);\n+ return new CertificateAuthority(certChainAndKey.certificateChain, certChainAndKey.key);\n}\n- private static CertificateExtensions certificateAuthorityExtensions(X509Key publicKey) throws IOException {\n+ private static CertificateExtensions certificateAuthorityExtensions(X509Key publicKey) {\n+ try {\nKeyIdentifier keyId = new KeyIdentifier(publicKey);\nbyte[] keyIdBytes = keyId.getIdentifier();\nCertificateExtensions extensions = new CertificateExtensions();\n@@ -76,6 +78,9 @@ public class CertificateAuthority {\nextensions.set(SubjectKeyIdentifierExtension.NAME, new SubjectKeyIdentifierExtension(keyIdBytes));\nreturn extensions;\n+ } catch (IOException e) {\n+ return throwUnchecked(e, null);\n+ }\n}\npublic X509Certificate[] certificateChain() {\n@@ -91,21 +96,10 @@ public class CertificateAuthority {\nSNIHostName hostName\n) throws CertificateGenerationUnsupportedException {\ntry {\n- // TODO inline CertAndKeyGen logic so we don't depend on sun.security.tools.keytool\n- CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, \"SHA256With\" + keyType, null);\n- newCertAndKey.generate(2048);\n- PrivateKey newKey = newCertAndKey.getPrivateKey();\n-\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(\n- x500Name(hostName.getAsciiName()),\n- new Date(),\n- (long) 365 * 24 * 60 * 60,\n- subjectAlternativeName(hostName)\n- );\n-\n- X509Certificate signed = sign(certificate);\n+ CertChainAndKey certChainAndKey = generateCertChainAndKey(keyType, \"SHA256With\" + keyType, hostName.getAsciiName(), Period.ofYears(1), x509Key -> subjectAlternativeName(hostName));\n+ X509Certificate signed = sign(certChainAndKey.certificateChain[0]);\nX509Certificate[] fullChain = prepend(signed, certificateChain);\n- return new CertChainAndKey(fullChain, newKey);\n+ return new CertChainAndKey(fullChain, certChainAndKey.key);\n} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError e) {\nthrow new CertificateGenerationUnsupportedException(\n\"Your runtime does not support generating certificates at runtime\",\n@@ -114,13 +108,34 @@ public class CertificateAuthority {\n}\n}\n- private static X500Name x500Name(String name){\n+ private static CertChainAndKey generateCertChainAndKey(\n+ String keyType,\n+ String sigAlg,\n+ String subjectName,\n+ Period validity,\n+ Function<X509Key, CertificateExtensions> extensionBuilder\n+ ) throws CertificateGenerationUnsupportedException {\ntry {\n- return new X500Name(\"CN=\" + name);\n- } catch (IOException e) {\n- // X500Name throws IOException for a parse error (which isn't an IO problem...)\n- // An SNIHostName should be guaranteed not to have a parse issue\n- return throwUnchecked(e, null);\n+ // TODO inline CertAndKeyGen logic so we don't depend on sun.security.tools.keytool\n+ CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, sigAlg);\n+ newCertAndKey.generate(2048);\n+ PrivateKey newKey = newCertAndKey.getPrivateKey();\n+\n+ ZonedDateTime start = ZonedDateTime.now();\n+ ZonedDateTime end = start.plus(validity);\n+\n+ X509Certificate certificate = newCertAndKey.getSelfCertificate(\n+ new X500Name(\"CN=\" + subjectName),\n+ Date.from(start.toInstant()),\n+ Duration.between(start, end).getSeconds(),\n+ extensionBuilder.apply(newCertAndKey.getPublicKey())\n+ );\n+ return new CertChainAndKey(new X509Certificate[]{ certificate }, newKey);\n+ } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError | IOException e) {\n+ throw new CertificateGenerationUnsupportedException(\n+ \"Your runtime does not support generating certificates at runtime\",\n+ e\n+ );\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -10,6 +10,7 @@ import com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\n+import com.github.tomakehurst.wiremock.http.ssl.CertificateGenerationUnsupportedException;\nimport com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\nimport com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\nimport com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\n@@ -238,7 +239,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n}\nreturn new X509KeyStore(keyStore, password);\n- } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | InvalidKeyException | SignatureException | NoSuchProviderException e) {\n+ } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | CertificateGenerationUnsupportedException e) {\nreturn throwUnchecked(e, null);\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Reduce duplication in generating certificates
686,981
18.06.2020 13:31:27
-3,600
46be3f186634e6cb91dc29cf7eaaeff6324a2c26
More like ?:
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -43,17 +43,13 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n@Override\npublic PrivateKey getPrivateKey(String alias) {\nPrivateKey original = super.getPrivateKey(alias);\n- return original == null ? dynamicKeyStore.getPrivateKey(alias) : original;\n+ return original != null ? original : dynamicKeyStore.getPrivateKey(alias);\n}\n@Override\npublic X509Certificate[] getCertificateChain(String alias) {\nX509Certificate[] original = super.getCertificateChain(alias);\n- if (original == null) {\n- return dynamicKeyStore.getCertificateChain(alias);\n- } else {\n- return original;\n- }\n+ return original != null ? original : dynamicKeyStore.getCertificateChain(alias);\n}\n@Override\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
More like ?:
686,981
18.06.2020 17:33:55
-3,600
1b35d702e2efd6bc4ef5daf6117d455129007aad
Simplify & better error handling
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/DynamicKeyStore.java", "diff": "@@ -12,9 +12,9 @@ public class DynamicKeyStore {\nprivate final X509KeyStore keyStore;\nprivate final CertificateAuthority existingCertificateAuthority;\n- public DynamicKeyStore(X509KeyStore keyStore, CertificateAuthority existingCertificateAuthority) {\n+ public DynamicKeyStore(X509KeyStore keyStore) {\nthis.keyStore = requireNonNull(keyStore);\n- this.existingCertificateAuthority = requireNonNull(existingCertificateAuthority);\n+ this.existingCertificateAuthority = requireNonNull(keyStore.getCertificateAuthority(), \"Keystore does not contain a certificate that can act as a certificate authority\");\n}\nPrivateKey getPrivateKey(String alias) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/CertificateGeneratingSslContextFactory.java", "diff": "+package com.github.tomakehurst.wiremock.jetty94;\n+\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\n+import com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\n+import com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\n+import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\n+import org.eclipse.jetty.util.ssl.SslContextFactory;\n+\n+import javax.net.ssl.KeyManager;\n+import javax.net.ssl.X509ExtendedKeyManager;\n+import java.security.KeyStore;\n+\n+import static java.util.Arrays.stream;\n+import static java.util.Objects.requireNonNull;\n+\n+class CertificateGeneratingSslContextFactory extends SslContextFactory.Server {\n+\n+ private final X509KeyStore x509KeyStore;\n+ private final Notifier notifier;\n+\n+ CertificateGeneratingSslContextFactory(X509KeyStore x509KeyStore, Notifier notifier) {\n+ this.x509KeyStore = requireNonNull(x509KeyStore);\n+ this.notifier = requireNonNull(notifier);\n+ }\n+\n+ @Override\n+ protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {\n+ KeyManager[] managers = super.getKeyManagers(keyStore);\n+ return stream(managers).map(manager -> {\n+ if (manager instanceof X509ExtendedKeyManager) {\n+ return new CertificateGeneratingX509ExtendedKeyManager(\n+ (X509ExtendedKeyManager) manager,\n+ new DynamicKeyStore(x509KeyStore),\n+ // TODO write a version of this that doesn't depend on sun internal classes\n+ new SunHostNameMatcher(),\n+ notifier\n+ );\n+ } else {\n+ return manager;\n+ }\n+ }).toArray(KeyManager[]::new);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -9,10 +9,7 @@ import com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\n-import com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGenerationUnsupportedException;\n-import com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\n-import com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\nimport com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\n@@ -32,8 +29,6 @@ import org.eclipse.jetty.server.SslConnectionFactory;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n-import javax.net.ssl.KeyManager;\n-import javax.net.ssl.X509ExtendedKeyManager;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.nio.file.FileSystems;\n@@ -41,19 +36,15 @@ import java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.attribute.FileAttribute;\n-import java.security.InvalidKeyException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n-import java.security.NoSuchProviderException;\n-import java.security.SignatureException;\nimport java.security.cert.CertificateException;\nimport java.util.EnumSet;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.nio.file.attribute.PosixFilePermission.*;\nimport static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\n-import static java.util.Arrays.stream;\npublic class Jetty94HttpServer extends JettyHttpServer {\n@@ -104,13 +95,13 @@ public class Jetty94HttpServer extends JettyHttpServer {\n);\n}\n- private void setupKeyStore(SslContextFactory.Server sslContextFactory, KeyStoreSettings keyStoreSettings) {\n+ private static void setupKeyStore(SslContextFactory.Server sslContextFactory, KeyStoreSettings keyStoreSettings) {\nsslContextFactory.setKeyStorePath(keyStoreSettings.path());\nsslContextFactory.setKeyManagerPassword(keyStoreSettings.password());\nsslContextFactory.setKeyStoreType(keyStoreSettings.type());\n}\n- private void setupClientAuth(SslContextFactory.Server sslContextFactory, HttpsSettings httpsSettings) {\n+ private static void setupClientAuth(SslContextFactory.Server sslContextFactory, HttpsSettings httpsSettings) {\nif (httpsSettings.hasTrustStore()) {\nsslContextFactory.setTrustStorePath(httpsSettings.trustStorePath());\nsslContextFactory.setTrustStorePassword(httpsSettings.trustStorePassword());\n@@ -170,34 +161,10 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn handler;\n}\n- private SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, BrowserProxySettings browserProxySettings, final Notifier notifier) {\n+ static SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, BrowserProxySettings browserProxySettings, final Notifier notifier) {\nKeyStoreSettings browserProxyCaKeyStore = browserProxySettings.caKeyStore();\n- X509KeyStore x509KeyStore = getOrCreateX509KeyStore(browserProxyCaKeyStore);\n- CertificateAuthority certificateAuthority = x509KeyStore.getCertificateAuthority();\n- if (certificateAuthority == null) {\n- throw new IllegalArgumentException(\"Keystore \"+browserProxyCaKeyStore.path()+\" does not contain a certificate that can act as a certificate authority\");\n- }\n-\n- SslContextFactory.Server sslContextFactory = new SslContextFactory.Server() {\n- @Override\n- protected KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {\n- KeyManager[] managers = super.getKeyManagers(keyStore);\n- return stream(managers).map(manager -> {\n- if (manager instanceof X509ExtendedKeyManager) {\n- return new CertificateGeneratingX509ExtendedKeyManager(\n- (X509ExtendedKeyManager) manager,\n- new DynamicKeyStore(x509KeyStore, certificateAuthority),\n- // TODO write a version of this that doesn't depend on sun internal classes\n- new SunHostNameMatcher(),\n- notifier\n- );\n- } else {\n- return manager;\n- }\n- }).toArray(KeyManager[]::new);\n- }\n- };\n+ SslContextFactory.Server sslContextFactory = buildSslContextFactory(notifier, browserProxyCaKeyStore);\nsetupKeyStore(sslContextFactory, browserProxyCaKeyStore);\nsslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\n@@ -205,15 +172,22 @@ public class Jetty94HttpServer extends JettyHttpServer {\nreturn sslContextFactory;\n}\n- private X509KeyStore getOrCreateX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\n+ private static SslContextFactory.Server buildSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore) {\nif (browserProxyCaKeyStore.exists()) {\n- return toX509KeyStore(browserProxyCaKeyStore);\n+ X509KeyStore existingKeyStore = toX509KeyStore(browserProxyCaKeyStore);\n+ return new CertificateGeneratingSslContextFactory(existingKeyStore, notifier);\n} else {\n- return createX509KeyStoreWithCertificateAuthority(browserProxyCaKeyStore);\n+ try {\n+ X509KeyStore newKeyStore = buildKeyStore(browserProxyCaKeyStore);\n+ return new CertificateGeneratingSslContextFactory(newKeyStore, notifier);\n+ } catch (Exception e) {\n+ notifier.error(\"Unable to generate a certificate authority\", e);\n+ return new SslContextFactory.Server();\n+ }\n}\n}\n- private X509KeyStore toX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\n+ private static X509KeyStore toX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\ntry {\nreturn new X509KeyStore(browserProxyCaKeyStore.loadStore(), browserProxyCaKeyStore.password().toCharArray());\n} catch (KeyStoreException e) {\n@@ -222,12 +196,11 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n}\n- private X509KeyStore createX509KeyStoreWithCertificateAuthority(KeyStoreSettings browserProxyCaKeyStore) {\n- try {\n+ private static X509KeyStore buildKeyStore(KeyStoreSettings browserProxyCaKeyStore) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, CertificateGenerationUnsupportedException {\n+ final CertificateAuthority certificateAuthority = CertificateAuthority.generateCertificateAuthority();\nKeyStore keyStore = KeyStore.getInstance(browserProxyCaKeyStore.type());\nchar[] password = browserProxyCaKeyStore.password().toCharArray();\nkeyStore.load(null, password);\n- CertificateAuthority certificateAuthority = CertificateAuthority.generateCertificateAuthority();\nkeyStore.setKeyEntry(\"wiremock-ca\", certificateAuthority.key(), password, certificateAuthority.certificateChain());\nPath created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\n@@ -239,12 +212,9 @@ public class Jetty94HttpServer extends JettyHttpServer {\n}\n}\nreturn new X509KeyStore(keyStore, password);\n- } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | CertificateGenerationUnsupportedException e) {\n- return throwUnchecked(e, null);\n- }\n}\n- private Path createCaKeystoreFile(Path path) throws IOException {\n+ private static Path createCaKeystoreFile(Path path) throws IOException {\nFileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\nFileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\nif (FileSystems.getDefault().supportedFileAttributeViews().contains(\"posix\")) {\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "*/\npackage com.github.tomakehurst.wiremock;\n+import com.github.tomakehurst.wiremock.common.FatalStartupException;\nimport com.github.tomakehurst.wiremock.common.SingleRootFileSource;\nimport com.github.tomakehurst.wiremock.http.ssl.HostVerifyingSSLSocketFactory;\nimport com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\n@@ -42,7 +43,9 @@ import org.junit.Rule;\nimport org.junit.Test;\nimport javax.net.ssl.SSLContext;\n+import java.io.EOFException;\nimport java.io.File;\n+import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\n@@ -52,11 +55,13 @@ import java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n+import java.security.cert.CertificateException;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.FILES_ROOT;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PASSWORD;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PATH;\n@@ -299,6 +304,22 @@ public class HttpsBrowserProxyAcceptanceTest {\n// then no exception is thrown\n}\n+ @Test(expected = EOFException.class)\n+ public void failsIfCaKeystorePathIsNotAKeystore() throws IOException {\n+ new WireMockServer(options()\n+ .enableBrowserProxying(true)\n+ .caKeystorePath(Files.createTempFile(\"notakeystore\", \"jks\").toString())\n+ ).start();\n+ }\n+\n+ @Test(expected = FatalStartupException.class)\n+ public void failsIfCaKeystoreDoesNotContainACaCertificate() throws Exception {\n+ new WireMockServer(options()\n+ .enableBrowserProxying(true)\n+ .caKeystorePath(emptyKeyStore().toString())\n+ ).start();\n+ }\n+\nprivate SSLConnectionSocketFactory sslSocketFactoryThatTrusts(KeyStore trustStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {\nSSLContext sslContext = SSLContextBuilder.create()\n.loadTrustMaterial(trustStore)\n@@ -347,4 +368,15 @@ public class HttpsBrowserProxyAcceptanceTest {\nreturn throwUnchecked(e, null);\n}\n}\n+\n+ private static Path emptyKeyStore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {\n+ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());\n+ char[] password = \"password\".toCharArray();\n+ keyStore.load(null, password);\n+ Path keystoreNoCa = Files.createTempFile(\"keystore-with-no-ca\", \"jks\");\n+ try (FileOutputStream fos = new FileOutputStream(keystoreNoCa.toFile())) {\n+ keyStore.store(fos, password);\n+ }\n+ return keystoreNoCa;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "@@ -113,7 +113,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nreturn new CertificateGeneratingX509ExtendedKeyManager(\nkeyManager,\n- new DynamicKeyStore(x509KeyStore, x509KeyStore.getCertificateAuthority()),\n+ new DynamicKeyStore(x509KeyStore),\nnew SunHostNameMatcher(),\nnew TestNotifier()\n);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerFactory.java", "diff": "@@ -61,8 +61,10 @@ public class JettyHttpServerFactory implements HttpServerFactory {\n) {\ntry {\nreturn SERVER_CONSTRUCTOR.newInstance(options, adminRequestHandler, stubRequestHandler);\n- } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {\n+ } catch (InstantiationException | IllegalAccessException e) {\nreturn Exceptions.throwUnchecked(e, HttpServer.class);\n+ } catch (InvocationTargetException e) {\n+ return Exceptions.throwUnchecked(e.getCause(), null);\n}\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Simplify & better error handling
686,981
18.06.2020 23:22:43
-3,600
e531f2ad122ac0f23f0846214a2b2970002eaf04
Set up the keystore correctly if unable to generate it If the keystore cannot be generated, we need to configure the SslContextFactory using the standard https key store.
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -164,25 +164,30 @@ public class Jetty94HttpServer extends JettyHttpServer {\nstatic SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, BrowserProxySettings browserProxySettings, final Notifier notifier) {\nKeyStoreSettings browserProxyCaKeyStore = browserProxySettings.caKeyStore();\n- SslContextFactory.Server sslContextFactory = buildSslContextFactory(notifier, browserProxyCaKeyStore);\n-\n- setupKeyStore(sslContextFactory, browserProxyCaKeyStore);\n- sslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\n+ SslContextFactory.Server sslContextFactory = buildSslContextFactory(notifier, browserProxyCaKeyStore, httpsSettings.keyStore());\nsetupClientAuth(sslContextFactory, httpsSettings);\nreturn sslContextFactory;\n}\n- private static SslContextFactory.Server buildSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore) {\n+ private static SslContextFactory.Server buildSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore, KeyStoreSettings defaultHttpsKeyStore) {\nif (browserProxyCaKeyStore.exists()) {\nX509KeyStore existingKeyStore = toX509KeyStore(browserProxyCaKeyStore);\n- return new CertificateGeneratingSslContextFactory(existingKeyStore, notifier);\n+ SslContextFactory.Server sslContextFactory = new CertificateGeneratingSslContextFactory(existingKeyStore, notifier);\n+ setupKeyStore(sslContextFactory, browserProxyCaKeyStore);\n+ sslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\n+ return sslContextFactory;\n} else {\ntry {\nX509KeyStore newKeyStore = buildKeyStore(browserProxyCaKeyStore);\n- return new CertificateGeneratingSslContextFactory(newKeyStore, notifier);\n+ SslContextFactory.Server sslContextFactory = new CertificateGeneratingSslContextFactory(newKeyStore, notifier);\n+ setupKeyStore(sslContextFactory, browserProxyCaKeyStore);\n+ sslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\n+ return sslContextFactory;\n} catch (Exception e) {\nnotifier.error(\"Unable to generate a certificate authority\", e);\n- return new SslContextFactory.Server();\n+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();\n+ setupKeyStore(sslContextFactory, defaultHttpsKeyStore);\n+ return sslContextFactory;\n}\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Set up the keystore correctly if unable to generate it If the keystore cannot be generated, we need to configure the SslContextFactory using the standard https key store.
686,981
19.06.2020 10:38:50
-3,600
09ba9a7baec111224fd6cd5fa341e37ce6f1482b
Certificate is generated on startup, doesn't need a request to bootstrap it
[ { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -276,10 +276,6 @@ public class HttpsBrowserProxyAcceptanceTest {\n@Test\npublic void certificatesSignedWithGeneratedRootCertificate() throws Exception {\n- // Ensure the certificate has been generated by making a request\n- testClient.getViaProxy(\"https://fake1.nowildcards1.internal:\" + target.httpsPort() + \"/whatever\", proxy.port());\n-\n- // Certificate should be there now\nKeyStore trustStore = HttpsAcceptanceTest.readKeyStore(NO_PREEXISTING_KEYSTORE_PATH, \"password\");\n// given\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Certificate is generated on startup, doesn't need a request to bootstrap it
686,981
19.06.2020 12:57:12
-3,600
aedfa26ed59583fe77de91a2b1ca4b96c84a326e
Allow downloading the generated CA certificate Makes it easy to trust it.
[ { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "diff": "+package com.github.tomakehurst.wiremock.admin.tasks;\n+\n+import com.github.tomakehurst.wiremock.admin.AdminTask;\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\n+import com.github.tomakehurst.wiremock.common.BrowserProxySettings;\n+import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\n+\n+import java.io.PrintWriter;\n+import java.io.StringWriter;\n+import java.security.cert.X509Certificate;\n+import java.util.Base64;\n+\n+import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\n+import static java.net.HttpURLConnection.HTTP_OK;\n+\n+public class GetCaCertTask implements AdminTask {\n+\n+ private static final Base64.Encoder BASE64_ENCODER = Base64.getMimeEncoder(64, new byte[]{'\\r', '\\n'});\n+\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ BrowserProxySettings browserProxySettings = admin.getOptions().browserProxySettings();\n+ KeyStoreSettings caKeyStore = browserProxySettings.caKeyStore();\n+ try {\n+ X509KeyStore x509KeyStore = new X509KeyStore(caKeyStore.loadStore(), caKeyStore.password().toCharArray());\n+ X509Certificate certificate = x509KeyStore.getCertificateAuthority().certificateChain()[0];\n+ return new ResponseDefinitionBuilder()\n+ .withStatus(HTTP_OK)\n+ .withHeader(\"Content-Type\", \"application/x-pem-file\")\n+ .withBody(\n+ \"-----BEGIN CERTIFICATE-----\\r\\n\" +\n+ BASE64_ENCODER.encodeToString(certificate.getEncoded()) + \"\\r\\n\" +\n+ \"-----END CERTIFICATE-----\"\n+ )\n+ .build();\n+ } catch (Exception e) {\n+ StringWriter stacktrace = new StringWriter();\n+ e.printStackTrace(new PrintWriter(stacktrace));\n+ return new ResponseDefinition(\n+ HTTP_INTERNAL_ERROR,\n+ \"Failed to export certificate authority cert from \" + caKeyStore.path() + \"\\r\\n\" +\n+ stacktrace\n+ );\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyAcceptanceTest.java", "diff": "@@ -19,6 +19,7 @@ import com.github.tomakehurst.wiremock.common.FatalStartupException;\nimport com.github.tomakehurst.wiremock.common.SingleRootFileSource;\nimport com.github.tomakehurst.wiremock.http.ssl.HostVerifyingSSLSocketFactory;\nimport com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\n+import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport com.github.tomakehurst.wiremock.junit.WireMockClassRule;\nimport com.github.tomakehurst.wiremock.testsupport.TestFiles;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\n@@ -43,6 +44,7 @@ import org.junit.Rule;\nimport org.junit.Test;\nimport javax.net.ssl.SSLContext;\n+import java.io.ByteArrayInputStream;\nimport java.io.EOFException;\nimport java.io.File;\nimport java.io.FileOutputStream;\n@@ -55,7 +57,10 @@ import java.security.KeyManagementException;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\n+import java.security.cert.Certificate;\nimport java.security.cert.CertificateException;\n+import java.security.cert.CertificateFactory;\n+import java.util.Base64;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -67,6 +72,7 @@ import static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PATH;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.is;\n+import static org.junit.Assert.assertEquals;\npublic class HttpsBrowserProxyAcceptanceTest {\n@@ -316,6 +322,27 @@ public class HttpsBrowserProxyAcceptanceTest {\n).start();\n}\n+ @Test\n+ public void certificateAuthorityCertCanBeDownloaded() throws Exception {\n+ WireMockTestClient proxyTestClient = new WireMockTestClient(proxy.port());\n+\n+ WireMockResponse certResponse = proxyTestClient.get(\"/__admin/certs/wiremock-ca.crt\");\n+ assertEquals(200, certResponse.statusCode());\n+ assertEquals(\"application/x-pem-file\", certResponse.firstHeader(\"Content-Type\"));\n+\n+ Certificate cert = decode(certResponse.content());\n+ X509KeyStore keyStore = new X509KeyStore(HttpsAcceptanceTest.readKeyStore(NO_PREEXISTING_KEYSTORE_PATH, \"password\"), \"password\".toCharArray());\n+\n+ assertEquals(keyStore.getCertificateAuthority().certificateChain()[0], cert);\n+ }\n+\n+ private Certificate decode(String body) throws Exception {\n+ String base64 = body.replace(\"-----BEGIN CERTIFICATE-----\", \"\").replace(\"-----END CERTIFICATE-----\", \"\");\n+ byte[] certBytes = Base64.getMimeDecoder().decode(base64);\n+ CertificateFactory cf = CertificateFactory.getInstance(\"X.509\");\n+ return cf.generateCertificate(new ByteArrayInputStream(certBytes));\n+ }\n+\nprivate SSLConnectionSocketFactory sslSocketFactoryThatTrusts(KeyStore trustStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {\nSSLContext sslContext = SSLContextBuilder.create()\n.loadTrustMaterial(trustStore)\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/AdminRoutes.java", "diff": "@@ -111,6 +111,8 @@ public class AdminRoutes {\nrouter.add(GET, \"/docs/swagger\", GetSwaggerSpecTask.class);\nrouter.add(GET, \"/docs\", GetDocIndexTask.class);\n+\n+ router.add(GET, \"/certs/wiremock-ca.crt\", GetCaCertTask.class);\n}\nprotected void initAdditionalRoutes(Router routeBuilder) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "diff": "+package com.github.tomakehurst.wiremock.admin.tasks;\n+\n+import com.github.tomakehurst.wiremock.admin.AdminTask;\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+\n+import static java.net.HttpURLConnection.HTTP_NOT_FOUND;\n+\n+public class GetCaCertTask implements AdminTask {\n+\n+ private static final ResponseDefinition NOT_SUPPORTED_RESPONSE = new ResponseDefinition(HTTP_NOT_FOUND, \"HTTPS Browser Proxying, including CA certificate retrieval, requires wiremock-jre8\");\n+\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ return NOT_SUPPORTED_RESPONSE;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/assets/recorder/index.html", "new_path": "src/main/resources/assets/recorder/index.html", "diff": "<button id=\"startRecording\" disabled=\"disabled\">Record</button>\n<button id=\"stopRecording\" disabled=\"disabled\">Stop</button>\n+ <p>\n+ Certificate to trust when browser proxying HTTPS sites:<p>\n+ <a href=\"../certs/wiremock-ca.crt\">wiremock-ca.crt</a><p>\n+ This self-signed certificate is marked as a certificate authority, and contains the public key that is paired with the private key provided in the keystore specified using the <code>--ca-keystore-path</code> option.<p>\n+ By default this is a securely generated private key local to the system where WireMock is running.<p>\n+ WireMock will serve generated certificates signed with this private key for any HTTPS site you visit while using WireMock as your proxy server.<p>\n+ Trusting this certificate will mean your browser (or other client) will trust those generated certificates.<p>\n+ This will be secure provided nobody else ever gets hold of the private key.\n</div>\n<script type=\"text/javascript\">\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Allow downloading the generated CA certificate Makes it easy to trust it.
686,981
19.06.2020 13:41:57
-3,600
ec8543502b1d1fde0bfbd524dbdf0865a5306c26
Fix the build Exclude the GetCaCertTask from the wiremock module, and add it to the java7 module
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -194,7 +194,7 @@ subprojects {\n// main.java.srcDir(project(':').sourceSets.main.java.exclude('com/github/tomakehurst/wiremock/matching/EqualToJsonPattern*'))\n// }\n- main.java.srcDir project(':').sourceSets.main.java.exclude('com/github/tomakehurst/wiremock/matching/EqualToJsonPattern*')\n+ main.java.srcDir project(':').sourceSets.main.java.exclude('com/github/tomakehurst/wiremock/matching/EqualToJsonPattern*', 'com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java')\ntest.java.srcDir project(':').sourceSets.test.java\ntest.scala.srcDir project(':').sourceSets.test.scala\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java7/src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "diff": "+package com.github.tomakehurst.wiremock.admin.tasks;\n+\n+import com.github.tomakehurst.wiremock.admin.AdminTask;\n+import com.github.tomakehurst.wiremock.admin.model.PathParams;\n+import com.github.tomakehurst.wiremock.core.Admin;\n+import com.github.tomakehurst.wiremock.http.Request;\n+import com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+\n+import static java.net.HttpURLConnection.HTTP_NOT_FOUND;\n+\n+public class GetCaCertTask implements AdminTask {\n+\n+ private static final ResponseDefinition NOT_SUPPORTED_RESPONSE = new ResponseDefinition(HTTP_NOT_FOUND, \"HTTPS Browser Proxying, including CA certificate retrieval, requires wiremock-jre8\");\n+\n+ @Override\n+ public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n+ return NOT_SUPPORTED_RESPONSE;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "diff": "@@ -6,14 +6,13 @@ import com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n-import static java.net.HttpURLConnection.HTTP_NOT_FOUND;\n-\npublic class GetCaCertTask implements AdminTask {\n- private static final ResponseDefinition NOT_SUPPORTED_RESPONSE = new ResponseDefinition(HTTP_NOT_FOUND, \"HTTPS Browser Proxying, including CA certificate retrieval, requires wiremock-jre8\");\n-\n@Override\npublic ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {\n- return NOT_SUPPORTED_RESPONSE;\n+ throw new UnsupportedOperationException(\n+ \"This file only exists to make the compiler happy in an IDE\"+\n+ \"In the build it is excluded, and the versions in the java7 & java8 modules will be used\"\n+ );\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fix the build Exclude the GetCaCertTask from the wiremock module, and add it to the java7 module
686,981
19.06.2020 15:12:16
-3,600
2943548efd310a9b7328b57b7d34bacf82011e67
Fix bug with repeat entries in CommandLineOptions toString
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -538,15 +538,6 @@ public class CommandLineOptions implements Options {\nbuilder.put(ADMIN_API_REQUIRE_HTTPS, \"true\");\n}\n- if (browserProxySettings.trustAllProxyTargets()) {\n- builder.put(TRUST_ALL_PROXY_TARGETS, \"true\");\n- }\n-\n- List<String> trustedProxyTargets = browserProxySettings.trustedProxyTargets();\n- if (!trustedProxyTargets.isEmpty()) {\n- builder.put(TRUST_PROXY_TARGET, Joiner.on(\", \").join(trustedProxyTargets));\n- }\n-\nStringBuilder sb = new StringBuilder();\nfor (Map.Entry<String, Object> param: builder.build().entrySet()) {\nint paddingLength = 29 - param.getKey().length();\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -546,6 +546,20 @@ public class CommandLineOptionsTest {\nassertThat(dump, matchesMultiLine(\".*https-port:.*2345.*\"));\n}\n+ @Test\n+ public void toStringWithTrustAllProxyTargetsWorks() {\n+ String options = new CommandLineOptions(\"--enable-browser-proxying\", \"--trust-all-proxy-targets\").toString();\n+ assertThat(options, matchesMultiLine(\".*enable-browser-proxying: *true.*\"));\n+ assertThat(options, matchesMultiLine(\".*trust-all-proxy-targets: *true.*\"));\n+ }\n+\n+ @Test\n+ public void toStringWithTrustProxyTarget() {\n+ String options = new CommandLineOptions(\"--enable-browser-proxying\", \"--trust-proxy-target\", \"localhost\", \"--trust-proxy-target\", \"example.com\").toString();\n+ assertThat(options, matchesMultiLine(\".*enable-browser-proxying: *true.*\"));\n+ assertThat(options, matchesMultiLine(\".*trust-proxy-target: *localhost, example\\\\.com.*\"));\n+ }\n+\npublic static class ResponseDefinitionTransformerExt1 extends ResponseDefinitionTransformer {\n@Override\npublic ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource files, Parameters parameters) { return null; }\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fix bug with repeat entries in CommandLineOptions toString
686,981
19.06.2020 15:34:13
-3,600
cf859c8c61cad21d5bc71e5e6bcef94defdcc698
Log exception rather than returning it in the response Security risk giving too many details away about the implementation. Not much a user can do about it unless they are running locally in which case they can see the logs.
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "diff": "@@ -39,13 +39,9 @@ public class GetCaCertTask implements AdminTask {\n)\n.build();\n} catch (Exception e) {\n- StringWriter stacktrace = new StringWriter();\n- e.printStackTrace(new PrintWriter(stacktrace));\n- return new ResponseDefinition(\n- HTTP_INTERNAL_ERROR,\n- \"Failed to export certificate authority cert from \" + caKeyStore.path() + \"\\r\\n\" +\n- stacktrace\n- );\n+ String message = \"Failed to export certificate authority cert from \" + caKeyStore.path();\n+ admin.getOptions().notifier().error(message, e);\n+ return new ResponseDefinition(HTTP_INTERNAL_ERROR, message);\n}\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Log exception rather than returning it in the response Security risk giving too many details away about the implementation. Not much a user can do about it unless they are running locally in which case they can see the logs.
686,981
19.06.2020 16:38:56
-3,600
f1df36c1729082a3b51ee325c1b324101fe9cb39
Prove client auth can be configured when https browser proxying
[ { "change_type": "ADD", "old_path": null, "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/HttpsBrowserProxyClientAuthAcceptanceTest.java", "diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.junit.WireMockClassRule;\n+import com.github.tomakehurst.wiremock.junit.WireMockRule;\n+import org.apache.http.HttpHost;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpGet;\n+import org.apache.http.conn.ssl.NoopHostnameVerifier;\n+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClientBuilder;\n+import org.apache.http.ssl.SSLContexts;\n+import org.apache.http.util.EntityUtils;\n+import org.junit.ClassRule;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import javax.net.ssl.SSLContext;\n+import java.io.IOException;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+import java.security.KeyStore;\n+\n+import static com.github.tomakehurst.wiremock.HttpsAcceptanceTest.readKeyStore;\n+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\n+import static com.github.tomakehurst.wiremock.client.WireMock.get;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PASSWORD;\n+import static com.github.tomakehurst.wiremock.testsupport.TestFiles.TRUST_STORE_PATH;\n+import static java.net.HttpURLConnection.HTTP_OK;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+\n+public class HttpsBrowserProxyClientAuthAcceptanceTest {\n+\n+ private static final String NO_PREEXISTING_KEYSTORE_PATH = tempNonExistingPath(\"wiremock-keystores\", \"ca-keystore.jks\");\n+\n+ @ClassRule\n+ public static WireMockClassRule target = new WireMockClassRule(wireMockConfig()\n+ .httpDisabled(true)\n+ .dynamicHttpsPort()\n+ .needClientAuth(true)\n+ .trustStorePath(TRUST_STORE_PATH)\n+ .trustStorePassword(TRUST_STORE_PASSWORD)\n+ );\n+\n+ @Rule\n+ public WireMockRule proxy = new WireMockRule(wireMockConfig()\n+ .dynamicPort()\n+ .enableBrowserProxying(true)\n+ .caKeystorePath(NO_PREEXISTING_KEYSTORE_PATH)\n+ .trustedProxyTargets(\"localhost\")\n+ .needClientAuth(true) // fine to set this to false, but more \"realistic\" for it to be true\n+ .trustStorePath(TRUST_STORE_PATH)\n+ .trustStorePassword(TRUST_STORE_PASSWORD)\n+ );\n+\n+ @Test\n+ public void canDoClientAuthEndToEndWhenProxying() throws Exception {\n+ target.stubFor(get(\"/whatever\").willReturn(aResponse().withBody(\"Success\")));\n+\n+ CloseableHttpClient testClient = buildHttpClient();\n+ CloseableHttpResponse response = testClient.execute(new HttpGet(target.url(\"/whatever\")));\n+\n+ assertThat(response.getStatusLine().getStatusCode(), is(HTTP_OK));\n+ assertThat(EntityUtils.toString(response.getEntity()), is(\"Success\"));\n+ }\n+\n+ private static String tempNonExistingPath(String prefix, String filename) {\n+ try {\n+ Path tempDirectory = Files.createTempDirectory(prefix);\n+ return tempDirectory.resolve(filename).toFile().getAbsolutePath();\n+ } catch (IOException e) {\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private CloseableHttpClient buildHttpClient() throws Exception {\n+ KeyStore trustStore = readKeyStore(TRUST_STORE_PATH, TRUST_STORE_PASSWORD);\n+\n+ SSLContext sslcontext = SSLContexts.custom()\n+ .loadTrustMaterial(new TrustSelfSignedStrategy())\n+ .loadKeyMaterial(trustStore, TRUST_STORE_PASSWORD.toCharArray())\n+ .build();\n+\n+ HttpHost proxyInfo = new HttpHost(\"localhost\", proxy.port());\n+ return HttpClientBuilder.create()\n+ .disableAuthCaching()\n+ .disableAutomaticRetries()\n+ .disableCookieManagement()\n+ .disableRedirectHandling()\n+ .setSSLContext(sslcontext)\n+ .setSSLHostnameVerifier(new NoopHostnameVerifier())\n+ .setProxy(proxyInfo)\n+ .build();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java", "diff": "@@ -344,11 +344,8 @@ public class HttpsAcceptanceTest {\nstatic KeyStore readKeyStore(String path, String password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {\nKeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());\n- FileInputStream instream = new FileInputStream(path);\n- try {\n+ try (FileInputStream instream = new FileInputStream(path)) {\ntrustStore.load(instream, password.toCharArray());\n- } finally {\n- instream.close();\n}\nreturn trustStore;\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Prove client auth can be configured when https browser proxying
686,981
19.06.2020 14:25:50
-3,600
71de20ef825ce9adb04af894a279e7ad326fd182
Better error message on communication failure when proxying
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "diff": "@@ -28,20 +28,20 @@ import org.apache.http.entity.ContentType;\nimport org.apache.http.entity.InputStreamEntity;\nimport org.apache.http.entity.ByteArrayEntity;\n+import javax.net.ssl.SSLException;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\n-import java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.util.Collections;\nimport java.util.LinkedList;\nimport java.util.List;\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static com.github.tomakehurst.wiremock.common.HttpClientUtils.getEntityAsByteArrayAndCloseStream;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.POST;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.PUT;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.PATCH;\nimport static com.github.tomakehurst.wiremock.http.Response.response;\n+import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\npublic class ProxyResponseRenderer implements ResponseRenderer {\n@@ -87,9 +87,9 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nHttpUriRequest httpRequest = getHttpRequestFor(responseDefinition);\naddRequestHeaders(httpRequest, responseDefinition);\n- try {\naddBodyIfPostPutOrPatch(httpRequest, responseDefinition);\nHttpClient client = buildClient(serveEvent.getRequest().isBrowserProxyRequest());\n+ try {\nHttpResponse httpResponse = client.execute(httpRequest);\nreturn response()\n@@ -105,11 +105,21 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n)\n.chunkedDribbleDelay(responseDefinition.getChunkedDribbleDelay())\n.build();\n+ } catch (SSLException e) {\n+ return proxyResponseError(\"SSL\", httpRequest, e);\n} catch (IOException e) {\n- return throwUnchecked(e, null);\n+ return proxyResponseError(\"Network\", httpRequest, e);\n}\n}\n+\n+ private Response proxyResponseError(String type, HttpUriRequest request, Exception e) {\n+ return response()\n+ .status(HTTP_INTERNAL_ERROR)\n+ .body((type + \" failure trying to make a proxied request from WireMock to \" + request.getURI()) + \"\\r\\n\" + e.getMessage())\n+ .build();\n+ }\n+\nprivate HttpClient buildClient(boolean browserProxyRequest) {\nif (browserProxyRequest && !trustAllProxyTargets) {\nreturn scepticalClient;\n@@ -119,7 +129,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\n}\nprivate HttpHeaders headersFrom(HttpResponse httpResponse, ResponseDefinition responseDefinition) {\n- List<HttpHeader> httpHeaders = new LinkedList<HttpHeader>();\n+ List<HttpHeader> httpHeaders = new LinkedList<>();\nfor (Header header : httpResponse.getAllHeaders()) {\nif (responseHeaderShouldBeTransferred(header.getName())) {\nhttpHeaders.add(new HttpHeader(header.getName(), header.getValue()));\n@@ -174,7 +184,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nreturn !FORBIDDEN_HEADERS.contains(lowerCaseKey) && !lowerCaseKey.startsWith(\"access-control\");\n}\n- private static void addBodyIfPostPutOrPatch(HttpRequest httpRequest, ResponseDefinition response) throws UnsupportedEncodingException {\n+ private static void addBodyIfPostPutOrPatch(HttpRequest httpRequest, ResponseDefinition response) {\nRequest originalRequest = response.getOriginalRequest();\nif (originalRequest.getMethod().isOneOf(PUT, POST, PATCH)) {\nHttpEntityEnclosingRequest requestWithEntity = (HttpEntityEnclosingRequest) httpRequest;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "diff": "@@ -28,8 +28,10 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;\nimport static com.github.tomakehurst.wiremock.client.WireMock.get;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;\nimport static com.github.tomakehurst.wiremock.crypto.X509CertificateVersion.V3;\n+import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.core.StringContains.containsString;\n+import static org.hamcrest.core.StringStartsWith.startsWith;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertThrows;\n@@ -63,14 +65,11 @@ public class ProxyResponseRendererTest {\nfinal ServeEvent serveEvent = forwardProxyServeEvent(\"/proxied\");\n- SSLHandshakeException e = assertThrows(SSLHandshakeException.class, new ThrowingRunnable() {\n- @Override\n- public void run() {\n- proxyResponseRenderer.render(serveEvent);\n- }\n- });\n+ Response response = proxyResponseRenderer.render(serveEvent);\n- assertThat(e.getMessage(), containsString(\"unable to find valid certification path to requested target\"));\n+ assertEquals(HTTP_INTERNAL_ERROR, response.getStatus());\n+ assertThat(response.getBodyAsString(), startsWith(\"SSL failure trying to make a proxied request from WireMock to \"+origin.url(\"/proxied\")));\n+ assertThat(response.getBodyAsString(), containsString(\"unable to find valid certification path to requested target\"));\n}\n@Test\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Better error message on communication failure when proxying
686,981
19.06.2020 16:45:51
-3,600
8517e0075df4af10fac8968d73de65092c8ead56
Use apache host name verifier
[ { "change_type": "MODIFY", "old_path": "java8/build.gradle", "new_path": "java8/build.gradle", "diff": "@@ -31,5 +31,4 @@ compileJava {\njavadoc {\nexclude \"**/CertificateAuthority.java\"\n- exclude \"**/SunHostNameMatcher.java\"\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/ApacheHttpHostNameMatcher.java", "diff": "+package com.github.tomakehurst.wiremock.http.ssl;\n+\n+import org.apache.http.conn.ssl.DefaultHostnameVerifier;\n+\n+import javax.net.ssl.SNIHostName;\n+import javax.net.ssl.SSLException;\n+import java.security.cert.X509Certificate;\n+\n+public class ApacheHttpHostNameMatcher implements HostNameMatcher {\n+ @Override\n+ public Boolean matches(X509Certificate x509Certificate, SNIHostName sniHostName) {\n+ try {\n+ new DefaultHostnameVerifier().verify(sniHostName.getAsciiName(), x509Certificate);\n+ return true;\n+ } catch (SSLException e) {\n+ return false;\n+ }\n+ }\n+}\n" }, { "change_type": "DELETE", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/SunHostNameMatcher.java", "new_path": null, "diff": "-package com.github.tomakehurst.wiremock.http.ssl;\n-\n-import sun.security.util.HostnameChecker;\n-\n-import javax.net.ssl.SNIHostName;\n-import java.security.cert.CertificateException;\n-import java.security.cert.X509Certificate;\n-\n-import static sun.security.util.HostnameChecker.TYPE_TLS;\n-\n-@SuppressWarnings(\"sunapi\")\n-public class SunHostNameMatcher implements HostNameMatcher {\n- @Override\n- public Boolean matches(X509Certificate x509Certificate, SNIHostName sniHostName) {\n- try {\n- HostnameChecker instance = HostnameChecker.getInstance(TYPE_TLS);\n- instance.match(sniHostName.getAsciiName(), x509Certificate);\n- return true;\n- } catch (CertificateException | NoSuchMethodError | VerifyError | NoClassDefFoundError e) {\n- return false;\n- }\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/CertificateGeneratingSslContextFactory.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/CertificateGeneratingSslContextFactory.java", "diff": "@@ -3,7 +3,7 @@ package com.github.tomakehurst.wiremock.jetty94;\nimport com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGeneratingX509ExtendedKeyManager;\nimport com.github.tomakehurst.wiremock.http.ssl.DynamicKeyStore;\n-import com.github.tomakehurst.wiremock.http.ssl.SunHostNameMatcher;\n+import com.github.tomakehurst.wiremock.http.ssl.ApacheHttpHostNameMatcher;\nimport com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n@@ -32,8 +32,7 @@ class CertificateGeneratingSslContextFactory extends SslContextFactory.Server {\nreturn new CertificateGeneratingX509ExtendedKeyManager(\n(X509ExtendedKeyManager) manager,\nnew DynamicKeyStore(x509KeyStore),\n- // TODO write a version of this that doesn't depend on sun internal classes\n- new SunHostNameMatcher(),\n+ new ApacheHttpHostNameMatcher(),\nnotifier\n);\n} else {\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasDefaultsTest.java", "diff": "@@ -36,7 +36,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasD\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\nmock(DynamicKeyStore.class),\n- new SunHostNameMatcher(),\n+ new ApacheHttpHostNameMatcher(),\ntestNotifier\n);\nprivate final Principal[] nullPrincipals = null;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasTest.java", "diff": "@@ -114,7 +114,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseEngineServerAliasT\nreturn new CertificateGeneratingX509ExtendedKeyManager(\nkeyManager,\nnew DynamicKeyStore(x509KeyStore),\n- new SunHostNameMatcher(),\n+ new ApacheHttpHostNameMatcher(),\nnew TestNotifier()\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "new_path": "java8/src/test/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefaultsTest.java", "diff": "@@ -39,7 +39,7 @@ public class CertificateGeneratingX509ExtendedKeyManagerChooseServerAliasDefault\nprivate final CertificateGeneratingX509ExtendedKeyManager certificateGeneratingKeyManager = new CertificateGeneratingX509ExtendedKeyManager(\nkeyManagerMock,\nmock(DynamicKeyStore.class),\n- new SunHostNameMatcher(),\n+ new ApacheHttpHostNameMatcher(),\ntestNotifier\n);\nprivate final Principal[] nullPrincipals = null;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Use apache host name verifier
686,981
19.06.2020 19:48:21
-3,600
c22af6442575e6cc9c8ea7351df948421de5292d
Log failure to proxy a request
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateGeneratingX509ExtendedKeyManager.java", "diff": "@@ -197,6 +197,13 @@ public class CertificateGeneratingX509ExtendedKeyManager extends DelegatingX509E\n}\n}\n+ @Override\n+ public void info(String message, Throwable t) {\n+ if (onceOnly.unused()) {\n+ notifier.info(message, t);\n+ }\n+ }\n+\n@Override\npublic void error(String message) {\nif (onceOnly.unused()) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ConsoleNotifier.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ConsoleNotifier.java", "diff": "@@ -40,6 +40,14 @@ public class ConsoleNotifier implements Notifier {\n}\n}\n+ @Override\n+ public void info(String message, Throwable t) {\n+ if (verbose) {\n+ out.println(formatMessage(message));\n+ t.printStackTrace(out);\n+ }\n+ }\n+\n@Override\npublic void error(String message) {\nerr.println(formatMessage(message));\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/LocalNotifier.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/LocalNotifier.java", "diff": "@@ -38,6 +38,10 @@ public class LocalNotifier {\npublic void info(String message) {\n}\n+ @Override\n+ public void info(String message, Throwable t) {\n+ }\n+\n@Override\npublic void error(String message) {\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Notifier.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Notifier.java", "diff": "@@ -20,6 +20,7 @@ public interface Notifier {\npublic static final String KEY = \"Notifier\";\nvoid info(String message);\n+ void info(String message, Throwable t);\nvoid error(String message);\nvoid error(String message, Throwable t);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Slf4jNotifier.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Slf4jNotifier.java", "diff": "@@ -35,6 +35,13 @@ public class Slf4jNotifier implements Notifier {\n}\n}\n+ @Override\n+ public void info(String message, Throwable t) {\n+ if (verbose) {\n+ log.info(message, t);\n+ }\n+ }\n+\n@Override\npublic void error(String message) {\nlog.error(message);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "diff": "@@ -154,7 +154,8 @@ public class WireMockApp implements StubServer, Admin {\noptions.proxyHostHeader(),\nglobalSettingsHolder,\nbrowserProxySettings.trustAllProxyTargets(),\n- browserProxySettings.trustedProxyTargets()\n+ browserProxySettings.trustedProxyTargets(),\n+ options.notifier()\n),\nImmutableList.copyOf(options.extensionsOfType(ResponseTransformer.class).values())\n),\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "diff": "package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n@@ -62,6 +63,7 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate final String hostHeaderValue;\nprivate final GlobalSettingsHolder globalSettingsHolder;\nprivate final boolean trustAllProxyTargets;\n+ private final Notifier notifier;\npublic ProxyResponseRenderer(\nProxySettings proxySettings,\n@@ -70,10 +72,12 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nString hostHeaderValue,\nGlobalSettingsHolder globalSettingsHolder,\nboolean trustAllProxyTargets,\n- List<String> trustedProxyTargets\n+ List<String> trustedProxyTargets,\n+ Notifier notifier\n) {\nthis.globalSettingsHolder = globalSettingsHolder;\nthis.trustAllProxyTargets = trustAllProxyTargets;\n+ this.notifier = notifier;\nclient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, true, Collections.<String>emptyList());\nscepticalClient = HttpClientFactory.createClient(1000, 5 * MINUTES, proxySettings, trustStoreSettings, false, trustedProxyTargets);\n@@ -114,9 +118,11 @@ public class ProxyResponseRenderer implements ResponseRenderer {\nprivate Response proxyResponseError(String type, HttpUriRequest request, Exception e) {\n+ String message = type + \" failure trying to make a proxied request from WireMock to \" + request.getURI();\n+ notifier.info(message, e);\nreturn response()\n.status(HTTP_INTERNAL_ERROR)\n- .body((type + \" failure trying to make a proxied request from WireMock to \" + request.getURI()) + \"\\r\\n\" + e.getMessage())\n+ .body(message + \"\\r\\n\" + e.getMessage())\n.build();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/StubRequestLoggingAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/StubRequestLoggingAcceptanceTest.java", "diff": "@@ -58,6 +58,11 @@ public class StubRequestLoggingAcceptanceTest extends AcceptanceTestBase {\ninfoMessages.add(message);\n}\n+ @Override\n+ public void info(String message, Throwable t) {\n+\n+ }\n+\n@Override\npublic void error(String message) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "diff": "@@ -10,6 +10,7 @@ import com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\nimport com.github.tomakehurst.wiremock.junit.WireMockRule;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n+import com.github.tomakehurst.wiremock.testsupport.TestNotifier;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport org.junit.Rule;\nimport org.junit.Test;\n@@ -30,6 +31,7 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options\nimport static com.github.tomakehurst.wiremock.crypto.X509CertificateVersion.V3;\nimport static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;\nimport static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.contains;\nimport static org.hamcrest.core.StringContains.containsString;\nimport static org.hamcrest.core.StringStartsWith.startsWith;\nimport static org.junit.Assert.assertEquals;\n@@ -44,6 +46,7 @@ public class ProxyResponseRendererTest {\n.keystorePath(generateKeystore().getAbsolutePath())\n);\n+ private final TestNotifier notifier = new TestNotifier();\nprivate final ProxyResponseRenderer proxyResponseRenderer = buildProxyResponseRenderer(false);\n@Test\n@@ -70,6 +73,7 @@ public class ProxyResponseRendererTest {\nassertEquals(HTTP_INTERNAL_ERROR, response.getStatus());\nassertThat(response.getBodyAsString(), startsWith(\"SSL failure trying to make a proxied request from WireMock to \"+origin.url(\"/proxied\")));\nassertThat(response.getBodyAsString(), containsString(\"unable to find valid certification path to requested target\"));\n+ assertThat(notifier.getInfoMessages(), contains(\"SSL failure trying to make a proxied request from WireMock to \"+origin.url(\"/proxied\")));\n}\n@Test\n@@ -152,7 +156,8 @@ public class ProxyResponseRendererTest {\n/* hostHeaderValue = */ null,\nnew GlobalSettingsHolder(),\ntrustAllProxyTargets,\n- Collections.<String>emptyList()\n+ Collections.<String>emptyList(),\n+ notifier\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/TestNotifier.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/testsupport/TestNotifier.java", "diff": "@@ -53,6 +53,12 @@ public class TestNotifier implements Notifier {\nconsoleNotifier.info(message);\n}\n+ @Override\n+ public void info(String message, Throwable t) {\n+ this.info.add(message);\n+ consoleNotifier.info(message, t);\n+ }\n+\n@Override\npublic void error(String message) {\nthis.error.add(message);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Log failure to proxy a request
686,981
19.06.2020 18:48:16
-3,600
9f20057d493007100b1aac3c0dc57476d976f0a6
Don't use keytool It's even more verboten than using sun.security
[ { "change_type": "MODIFY", "old_path": "java8/build.gradle", "new_path": "java8/build.gradle", "diff": "@@ -22,11 +22,6 @@ compileJava {\n// silences warnings about compiling against `sun` packages\noptions.compilerArgs += '-XDenableSunApiLintControl'\n-\n- // makes it possible to compile against `sun.security.tools.keytool`\n- options.fork = true\n- options.forkOptions.executable = 'javac'\n- options.compilerArgs += '-XDignore.symbol.file'\n}\njavadoc {\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/http/ssl/CertificateAuthority.java", "diff": "package com.github.tomakehurst.wiremock.http.ssl;\n-import sun.security.tools.keytool.CertAndKeyGen;\n+import sun.security.x509.AlgorithmId;\nimport sun.security.x509.AuthorityKeyIdentifierExtension;\nimport sun.security.x509.BasicConstraintsExtension;\n+import sun.security.x509.CertificateAlgorithmId;\nimport sun.security.x509.CertificateExtensions;\n+import sun.security.x509.CertificateSerialNumber;\n+import sun.security.x509.CertificateValidity;\n+import sun.security.x509.CertificateVersion;\n+import sun.security.x509.CertificateX509Key;\nimport sun.security.x509.DNSName;\nimport sun.security.x509.GeneralName;\nimport sun.security.x509.GeneralNames;\n@@ -14,23 +19,23 @@ import sun.security.x509.SubjectKeyIdentifierExtension;\nimport sun.security.x509.X500Name;\nimport sun.security.x509.X509CertImpl;\nimport sun.security.x509.X509CertInfo;\n-import sun.security.x509.X509Key;\nimport javax.net.ssl.SNIHostName;\nimport java.io.IOException;\nimport java.security.InvalidKeyException;\n+import java.security.KeyPair;\n+import java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.NoSuchProviderException;\n-import java.security.Principal;\nimport java.security.PrivateKey;\n+import java.security.PublicKey;\n+import java.security.SecureRandom;\nimport java.security.SignatureException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\n-import java.time.Duration;\nimport java.time.Period;\nimport java.time.ZonedDateTime;\nimport java.util.Date;\n-import java.util.function.Function;\nimport static com.github.tomakehurst.wiremock.common.ArrayFunctions.prepend;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -51,17 +56,29 @@ public class CertificateAuthority {\n}\npublic static CertificateAuthority generateCertificateAuthority() throws CertificateGenerationUnsupportedException {\n- CertChainAndKey certChainAndKey = generateCertChainAndKey(\n- \"RSA\",\n- \"SHA256WithRSA\",\n- \"WireMock Local Self Signed Root Certificate\",\n- Period.ofYears(10),\n- CertificateAuthority::certificateAuthorityExtensions\n+ try {\n+ KeyPair pair = generateKeyPair(\"RSA\");\n+ String sigAlg = \"SHA256WithRSA\";\n+ X509CertInfo info = makeX509CertInfo(sigAlg, \"WireMock Local Self Signed Root Certificate\", Period.ofYears(10), pair.getPublic(), certificateAuthorityExtensions(pair.getPublic()));\n+\n+ X509CertImpl certificate = selfSign(info, pair.getPrivate(), sigAlg);\n+\n+ return new CertificateAuthority(new X509Certificate[] { certificate }, pair.getPrivate());\n+ } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError | IOException e) {\n+ throw new CertificateGenerationUnsupportedException(\n+ \"Your runtime does not support generating certificates at runtime\",\n+ e\n);\n- return new CertificateAuthority(certChainAndKey.certificateChain, certChainAndKey.key);\n+ }\n+ }\n+\n+ private static X509CertImpl selfSign(X509CertInfo info, PrivateKey privateKey, String sigAlg) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {\n+ X509CertImpl certificate = new X509CertImpl(info);\n+ certificate.sign(privateKey, sigAlg);\n+ return certificate;\n}\n- private static CertificateExtensions certificateAuthorityExtensions(X509Key publicKey) {\n+ private static CertificateExtensions certificateAuthorityExtensions(PublicKey publicKey) {\ntry {\nKeyIdentifier keyId = new KeyIdentifier(publicKey);\nbyte[] keyIdBytes = keyId.getIdentifier();\n@@ -96,11 +113,15 @@ public class CertificateAuthority {\nSNIHostName hostName\n) throws CertificateGenerationUnsupportedException {\ntry {\n- CertChainAndKey certChainAndKey = generateCertChainAndKey(keyType, \"SHA256With\" + keyType, hostName.getAsciiName(), Period.ofYears(1), x509Key -> subjectAlternativeName(hostName));\n- X509Certificate signed = sign(certChainAndKey.certificateChain[0]);\n- X509Certificate[] fullChain = prepend(signed, certificateChain);\n- return new CertChainAndKey(fullChain, certChainAndKey.key);\n- } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError e) {\n+ KeyPair pair = generateKeyPair(keyType);\n+ String sigAlg = \"SHA256With\" + keyType;\n+ X509CertInfo info = makeX509CertInfo(sigAlg, hostName.getAsciiName(), Period.ofYears(1), pair.getPublic(), subjectAlternativeName(hostName));\n+\n+ X509CertImpl certificate = sign(info);\n+\n+ X509Certificate[] fullChain = prepend(certificate, certificateChain);\n+ return new CertChainAndKey(fullChain, pair.getPrivate());\n+ } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError | IOException e) {\nthrow new CertificateGenerationUnsupportedException(\n\"Your runtime does not support generating certificates at runtime\",\ne\n@@ -108,35 +129,43 @@ public class CertificateAuthority {\n}\n}\n- private static CertChainAndKey generateCertChainAndKey(\n- String keyType,\n+ private X509CertImpl sign(X509CertInfo info) throws CertificateException, IOException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {\n+ X509Certificate issuerCertificate = certificateChain[0];\n+ info.set(X509CertInfo.ISSUER, issuerCertificate.getSubjectDN());\n+\n+ X509CertImpl certificate = new X509CertImpl(info);\n+ certificate.sign(key, issuerCertificate.getSigAlgName());\n+ return certificate;\n+ }\n+\n+ private static KeyPair generateKeyPair(String keyType) throws NoSuchAlgorithmException {\n+ KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType);\n+ keyGen.initialize(2048, new SecureRandom());\n+ return keyGen.generateKeyPair();\n+ }\n+\n+ private static X509CertInfo makeX509CertInfo(\nString sigAlg,\nString subjectName,\nPeriod validity,\n- Function<X509Key, CertificateExtensions> extensionBuilder\n- ) throws CertificateGenerationUnsupportedException {\n- try {\n- // TODO inline CertAndKeyGen logic so we don't depend on sun.security.tools.keytool\n- CertAndKeyGen newCertAndKey = new CertAndKeyGen(keyType, sigAlg);\n- newCertAndKey.generate(2048);\n- PrivateKey newKey = newCertAndKey.getPrivateKey();\n-\n+ PublicKey publicKey,\n+ CertificateExtensions certificateExtensions\n+ ) throws IOException, CertificateException, NoSuchAlgorithmException {\nZonedDateTime start = ZonedDateTime.now();\nZonedDateTime end = start.plus(validity);\n- X509Certificate certificate = newCertAndKey.getSelfCertificate(\n- new X500Name(\"CN=\" + subjectName),\n- Date.from(start.toInstant()),\n- Duration.between(start, end).getSeconds(),\n- extensionBuilder.apply(newCertAndKey.getPublicKey())\n- );\n- return new CertChainAndKey(new X509Certificate[]{ certificate }, newKey);\n- } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | CertificateException | SignatureException | NoSuchMethodError | VerifyError | NoClassDefFoundError | IOException e) {\n- throw new CertificateGenerationUnsupportedException(\n- \"Your runtime does not support generating certificates at runtime\",\n- e\n- );\n- }\n+ X500Name myname = new X500Name(\"CN=\" + subjectName);\n+ X509CertInfo info = new X509CertInfo();\n+ // Add all mandatory attributes\n+ info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));\n+ info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new java.util.Random().nextInt() & 0x7fffffff));\n+ info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(AlgorithmId.get(sigAlg)));\n+ info.set(X509CertInfo.SUBJECT, myname);\n+ info.set(X509CertInfo.KEY, new CertificateX509Key(publicKey));\n+ info.set(X509CertInfo.VALIDITY, new CertificateValidity(Date.from(start.toInstant()), Date.from(end.toInstant())));\n+ info.set(X509CertInfo.ISSUER, myname);\n+ info.set(X509CertInfo.EXTENSIONS, certificateExtensions);\n+ return info;\n}\nprivate static CertificateExtensions subjectAlternativeName(SNIHostName hostName) {\n@@ -162,23 +191,4 @@ public class CertificateAuthority {\nreturn throwUnchecked(e, null);\n}\n}\n-\n- private X509Certificate sign(X509Certificate certificate) throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {\n- X509Certificate issuerCertificate = certificateChain[0];\n- Principal issuer = issuerCertificate.getSubjectDN();\n- String issuerSigAlg = issuerCertificate.getSigAlgName();\n-\n- byte[] inCertBytes = certificate.getTBSCertificate();\n- X509CertInfo info = new X509CertInfo(inCertBytes);\n- try {\n- info.set(X509CertInfo.ISSUER, issuer);\n- } catch (IOException e) {\n- return throwUnchecked(e, null);\n- }\n-\n- X509CertImpl outCert = new X509CertImpl(info);\n- outCert.sign(key, issuerSigAlg);\n-\n- return outCert;\n- }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Don't use keytool It's even more verboten than using sun.security
686,981
22.06.2020 11:13:02
-3,600
e33b67329451a113d32d21789cba26f90dd7405a
Improve HTTPS browser proxying documentation
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/configuration.md", "new_path": "docs-v2/_docs/configuration.md", "diff": "@@ -114,6 +114,15 @@ WireMock uses the trust store for three purposes:\n// The password to the trust store\n.trustStorePassword(\"trustme\")\n+\n+// When proxying, a key store containing a root Certificate Authority private key and certificate that can be used to sign generated certificates\n+.caKeystorePath(\"/path/to/ca-key-store.jks\")\n+\n+// The password to the CA key store\n+.caKeystorePassword(\"trustme\")\n+\n+// The type of the CA key store\n+.caKeystoreType(\"JKS\")\n```\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -132,55 +132,78 @@ stubFor(get(urlEqualTo(\"/users/12345.json\"))\n.withStatus(503)));\n```\n-wiremock-jre8 allows forward proxying, stubbing & recording of HTTPS traffic. By default, this will verify the origin certificates; this behaviour can be turned to trusting all as follows:\n+### Browser proxying of HTTPS\n+\n+wiremock-jre8 allows forward proxying, stubbing & recording of HTTPS traffic.\n+\n+This happens automatically when browser proxying is enabled.\n+\n+*We strongly recommend using WireMock over HTTP to proxy HTTPS*; there are no associated security concerns, and proxying HTTPS over HTTPS is poorly supported by many clients.\n+\n+Note that when clients / operating systems distinguish between HTTP & HTTPS proxies they are often referring to the scheme of the target server, not the scheme the proxy server is listening on.\n+\n+#### Getting your client to trust the certificate presented by WireMock\n+\n+Normally when proxying HTTPS the proxy creates a TCP tunnel between the client and the target server, so the HTTPS session is between the client and the target server.\n+While the proxy passes the bytes back and forward, it cannot understand them because there is end-to-end encryption between the client and the target.\n+\n+WireMock needs to decrypt the traffic in order to record or replace it with stubs.\n+Consequently, there have to be two separate HTTPS sessions - one between WireMock and the target server, and one between the client and WireMock.\n+This means that when you request https://www.example.com proxied via WireMock the HTTPS certificate will be presented by WireMock, not www.example.com.\n+Inevitably it cannot be trusted by default - otherwise no internet traffic would be secure.\n+\n+WireMock uses a root Certificate Authority private key to sign a certificate for each host that it proxies.\n+By default, WireMock will use a CA key store at `$HOME/.wiremock/ca-keystore.jks`.\n+If this key store does not exist, WireMock will generate it with a new secure private key which should be entirely private to the system on which WireMock is running.\n+You can provide a key store containing such a private key & certificate yourself using the `--ca-keystore`, `--ca-keystore-password` & `--ca-keystore-type` options.\n+> See [this script](https://github.com/tomakehurst/wiremock/blob/master/scripts/create-ca-cert.sh)\n+> for an example of how to build a key & valid self-signed root certificate called\n+> ca-cert.crt already imported into a keystore called ca-cert.jks.\n+\n+This CA certificate can be downloaded from WireMock's `/__admin/recorder` endpoint.\n+Trusting this certificate will trust all certificates generated by it, allowing you to browse without client warnings.\n+> On OS/X a certificate can be trusted by dragging ca-cert.crt onto Keychain Access,\n+> double clicking on the certificate and setting SSL to \"always trust\".\n+\n+A few caveats:\n+* This depends on internal sun classes; it works with OpenJDK 1.8 -> 14, but may\n+ stop working in future versions or on other runtimes\n+* It's your responsibility to keep the private key & keystore secure - if you\n+ add it to your trusted certs then anyone getting hold of it could potentially\n+ get access to any service you use on the web.\n+\n+#### Trusting targets with invalid HTTPS certificates\n+\n+For convenience when acting as a _reverse_ proxy WireMock ignores HTTPS certificate problems from the target such as untrusted certificates or incorrect hostnames on the certificate.\n+When browser proxying, however, it is normal to proxy all traffic, often for the entire operating system.\n+This would present a substantial security risk, so by default WireMock will verify the target certificates when browser proxying.\n+You can trust specific hosts as follows:\n```bash\n-$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-all-proxy-targets\n+$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-proxy-target localhost --trust-proxy-target dev.mycorp.com\n```\n-or to trust specific hosts:\n+or if you're not interested in security you can trust all hosts:\n```bash\n-$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-proxy-target localhost --trust-proxy-target dev.mycorp.com\n+$ java -jar wiremock-jre8-standalone-{{ site.wiremock_version }}.jar --enable-browser-proxying --trust-all-proxy-targets\n```\nAdditional trusted public certificates can also be added to the keystore\n-specified via the `--https-truststore`, and should then be trusted without\n+specified via the `--https-truststore`, and WireMock will then trust them without\nneeding the `--trust-proxy-target` parameter (so long as they match the\nrequested host).\n-As WireMock is here running as a man-in-the-middle, the resulting traffic will\n-appear to the client encrypted with WireMock's (configurable) private key &\n-certificate, and so will not be trusted by default by clients.\n-\n-Adding WireMock's certificate to your trusted certs (whether those of the O/S or\n-the browser) will not solve this[1], as clients should verify that the\n-certificate is for the requested hostname. To work around this, you can generate\n-your own keystore containing a private key and certificate that are able to act\n-as a root certificate for signing other certificates. When WireMock is started\n-with a JKS keystore (via `WireMockConfiguration.keystorePath()` or\n-`--https-keystore` when running standalone) containing such a certificate, it\n-will serve browser proxied https traffic using a newly generated certificate per\n-requested hostname, valid for that hostname. You can then trust that root\n-certificate and be able to browse all sites proxied via WireMock.\n+#### Proxying HTTPS on the HTTPS endpoint\n-A few caveats:\n-* The keystore must be in JKS format\n-* This depends on internal sun classes; it works with OpenJDK 1.8 -> 14, but may\n- stop working in future versions or on other runtimes\n-* It's your responsibility to keep that private key & keystore secure - if you\n- add it to your trusted certs then anyone getting hold of it could potentially\n- get access to any service you use on the web.\n+The only use case we can think of for this is if you are using WireMock to test\n+a generic HTTPS client, and want that HTTPS client to support proxying HTTPS over\n+HTTPS. It has several problems. However, if you really must, there is limited support\n+for doing so.\n-> See [this script](https://github.com/tomakehurst/wiremock/blob/master/scripts/create-ca-cert.sh)\n-> for an example of how to build a valid self-signed root certificate called\n-> ca-cert.crt already imported into a keystore called ca-cert.jks.\n->\n-> On OS/X it can be trusted by dragging ca-cert.crt onto Keychain Access,\n-> double clicking on the certificate and setting SSL to \"always trust\".\n->\n-> Please raise PRs to add documentation for other platforms.\n+Please be aware that many clients do not work very well with this\n+configuration. For instance:\n+\n+Postman seems not to cope with an HTTPS proxy even to proxy HTTP traffic.\n-Proxying of HTTPS traffic when the proxy endpoint is also HTTPS is problematic;\n-Postman seems not to cope with an HTTPS proxy even to proxy HTTP traffic. Older\n-versions of curl fail trying to do the CONNECT call because they try to do so\n+Older versions of curl fail trying to do the CONNECT call because they try to do so\nover HTTP/2 (newer versions only offer HTTP/1.1 for the CONNECT call). At time\nof writing it works using `curl 7.64.1 (x86_64-apple-darwin19.0) libcurl/7.64.1 (SecureTransport) LibreSSL/2.8.3 zlib/1.2.11 nghttp2/1.39.2` as so:\n```bash\n@@ -191,19 +214,20 @@ You can force HTTP/1.1 in curl as so:\ncurl --http1.1 --proxy-insecure -x https://localhost:8443 -k 'https://www.example.com/'\n```\n-Many client proxy settings which distinguish between secure and insecure are\n-actually referring to the target site's protocol, not the protocol of the proxy,\n-and assume the proxy will be listening for an HTTP CONNECT request when proxying\n-an HTTPS site.\n-\nPlease check your client's behaviour proxying via another https proxy such as\n-https://hub.docker.com/r/wernight/spdyproxy to see if it is a client problem:\n+https://hub.docker.com/r/wernight/spdyproxy to see if it is a client problem before asking for help:\n```bash\ndocker run --rm -it -p 44300:44300 wernight/spdyproxy\ncurl --proxy-insecure -x https://localhost:44300 -k 'https://www.example.com/'\n```\n-[1] It would also be a security risk as the private key is in the public domain\n+#### Security concerns\n+\n+Acting as a man in the middle for HTTPS traffic has to be done at your own risk.\n+Whilst best efforts have been taken to reduce your risk, you should be aware you are granting WireMock unencrypted access to all HTPS traffic proxied via WireMock,\n+and that as part of its normal operation WireMock may store that traffic, in memory or on the file system.\n+If you choose to trust the root CA certificate WireMock is using, or you choose to bypass HTTPS verification for some or all target servers,\n+you should understand the risk involved.\n## Proxying via another proxy server\n" }, { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -90,6 +90,15 @@ e.g. `--proxy-via http://username:password@webproxy.mycorp.com:8080/`.\n`--enable-browser-proxying`: Run as a browser proxy. See\nbrowser-proxying.\n+`--ca-keystore`: A key store containing a root Certificate Authority private key\n+and certificate that can be used to sign generated certificates when\n+browser proxying https. Defaults to `$HOME/.wiremock/ca-keystore.jks`.\n+\n+`--ca-keystore-password`: Password to the ca-keystore, if something other than\n+\"password\".\n+\n+`--ca-keystore-type`: Type of the ca-keystore, if something other than `jks`.\n+\n`--trust-all-proxy-targets`: Trust all remote certificates when running as a\nbrowser proxy and proxying HTTPS traffic.\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "diff": "@@ -70,6 +70,7 @@ public class WireMockConfiguration implements Options {\nprivate boolean browserProxyingEnabled = false;\nprivate String caKeystorePath = DEFAULT_CA_KEYSTORE_PATH;\nprivate String caKeystorePassword = DEFAULT_CA_KESTORE_PASSWORD;\n+ private String caKeystoreType = \"JKS\";\nprivate boolean trustAllProxyTargets = false;\nprivate final List<String> trustedProxyTargets = new ArrayList<>();\n@@ -198,6 +199,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration caKeystoreType(String caKeystoreType) {\n+ this.caKeystoreType = caKeystoreType;\n+ return this;\n+ }\n+\npublic WireMockConfiguration trustStorePath(String truststorePath) {\nthis.trustStorePath = truststorePath;\nreturn this;\n@@ -562,6 +568,7 @@ public class WireMockConfiguration implements Options {\n.trustedProxyTargets(trustedProxyTargets)\n.caKeyStorePath(caKeystorePath)\n.caKeyStorePassword(caKeystorePassword)\n+ .caKeyStoreType(caKeystoreType)\n.build();\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Improve HTTPS browser proxying documentation
686,981
22.06.2020 11:36:09
-3,600
2910b2e6575fb303f7fff23723cfba3831708892
Fixes to HTTPS browser proxying documentation
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/proxying.md", "new_path": "docs-v2/_docs/proxying.md", "diff": "@@ -160,7 +160,8 @@ You can provide a key store containing such a private key & certificate yourself\n> for an example of how to build a key & valid self-signed root certificate called\n> ca-cert.crt already imported into a keystore called ca-cert.jks.\n-This CA certificate can be downloaded from WireMock's `/__admin/recorder` endpoint.\n+This CA certificate can be downloaded from WireMock: [http://localhost:8080/__admin/certs/wiremock-ca.crt](http://localhost:8080/__admin/certs/wiremock-ca.crt).\n+There's a link to the certificate on the recorder UI page at [http://localhost:8080/__admin/recorder](http://localhost:8080/__admin/recorder).\nTrusting this certificate will trust all certificates generated by it, allowing you to browse without client warnings.\n> On OS/X a certificate can be trusted by dragging ca-cert.crt onto Keychain Access,\n> double clicking on the certificate and setting SSL to \"always trust\".\n@@ -224,8 +225,8 @@ curl --proxy-insecure -x https://localhost:44300 -k 'https://www.example.com/'\n#### Security concerns\nActing as a man in the middle for HTTPS traffic has to be done at your own risk.\n-Whilst best efforts have been taken to reduce your risk, you should be aware you are granting WireMock unencrypted access to all HTPS traffic proxied via WireMock,\n-and that as part of its normal operation WireMock may store that traffic, in memory or on the file system.\n+Whilst best efforts have been taken to reduce your risk, you should be aware you are granting WireMock unencrypted access to all HTTPS traffic proxied via WireMock,\n+and that as part of its normal operation WireMock may store that traffic, in memory or on the file system, or print it to the console.\nIf you choose to trust the root CA certificate WireMock is using, or you choose to bypass HTTPS verification for some or all target servers,\nyou should understand the risk involved.\n" }, { "change_type": "MODIFY", "old_path": "src/main/resources/assets/recorder/index.html", "new_path": "src/main/resources/assets/recorder/index.html", "diff": "<p>\nCertificate to trust when browser proxying HTTPS sites:<p>\n<a href=\"../certs/wiremock-ca.crt\">wiremock-ca.crt</a><p>\n- This self-signed certificate is marked as a certificate authority, and contains the public key that is paired with the private key provided in the keystore specified using the <code>--ca-keystore-path</code> option.<p>\n+ This self-signed certificate is marked as a certificate authority, and contains the public key that is paired with the private key provided in the keystore specified using the <code>--ca-keystore</code> option.<p>\nBy default this is a securely generated private key local to the system where WireMock is running.<p>\nWireMock will serve generated certificates signed with this private key for any HTTPS site you visit while using WireMock as your proxy server.<p>\nTrusting this certificate will mean your browser (or other client) will trust those generated certificates.<p>\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixes to HTTPS browser proxying documentation
686,936
25.06.2020 12:44:23
-3,600
22346096e4a07670bd22adfb0bcf4ecf881877da
Now reports scenario state mismatch in diff reports
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockApp.java", "diff": "@@ -57,7 +57,7 @@ public class WireMockApp implements StubServer, Admin {\npublic static final String ADMIN_CONTEXT_ROOT = \"/__admin\";\npublic static final String MAPPINGS_ROOT = \"mappings\";\n-\n+ private final Scenarios scenarios;\nprivate final StubMappings stubMappings;\nprivate final RequestJournal requestJournal;\nprivate final GlobalSettingsHolder globalSettingsHolder;\n@@ -86,13 +86,16 @@ public class WireMockApp implements StubServer, Admin {\nglobalSettingsHolder = new GlobalSettingsHolder();\nrequestJournal = options.requestJournalDisabled() ? new DisabledRequestJournal() : new InMemoryRequestJournal(options.maxRequestJournalEntries());\nMap<String, RequestMatcherExtension> customMatchers = options.extensionsOfType(RequestMatcherExtension.class);\n+\n+ scenarios = new Scenarios();\nstubMappings = new InMemoryStubMappings(\n+ scenarios,\ncustomMatchers,\noptions.extensionsOfType(ResponseDefinitionTransformer.class),\nfileSource,\nImmutableList.copyOf(options.extensionsOfType(StubLifecycleListener.class).values())\n);\n- nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal);\n+ nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal, scenarios);\nrecorder = new Recorder(this);\nglobalSettingsListeners = ImmutableList.copyOf(options.extensionsOfType(GlobalSettingsListener.class).values());\n@@ -116,9 +119,10 @@ public class WireMockApp implements StubServer, Admin {\nthis.mappingsSaver = mappingsSaver;\nglobalSettingsHolder = new GlobalSettingsHolder();\nrequestJournal = requestJournalDisabled ? new DisabledRequestJournal() : new InMemoryRequestJournal(maxRequestJournalEntries);\n- stubMappings = new InMemoryStubMappings(requestMatchers, transformers, rootFileSource, Collections.<StubLifecycleListener>emptyList());\n+ scenarios = new Scenarios();\n+ stubMappings = new InMemoryStubMappings(scenarios, requestMatchers, transformers, rootFileSource, Collections.<StubLifecycleListener>emptyList());\nthis.container = container;\n- nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal);\n+ nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal, scenarios);\nrecorder = new Recorder(this);\nglobalSettingsListeners = Collections.emptyList();\nloadDefaultMappings();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/stubbing/InMemoryStubMappings.java", "diff": "@@ -45,13 +45,14 @@ import static com.google.common.collect.Iterables.tryFind;\npublic class InMemoryStubMappings implements StubMappings {\nprivate final SortedConcurrentMappingSet mappings = new SortedConcurrentMappingSet();\n- private final Scenarios scenarios = new Scenarios();\n+ private final Scenarios scenarios;\nprivate final Map<String, RequestMatcherExtension> customMatchers;\nprivate final Map<String, ResponseDefinitionTransformer> transformers;\nprivate final FileSource rootFileSource;\nprivate final List<StubLifecycleListener> stubLifecycleListeners;\n- public InMemoryStubMappings(Map<String, RequestMatcherExtension> customMatchers, Map<String, ResponseDefinitionTransformer> transformers, FileSource rootFileSource, List<StubLifecycleListener> stubLifecycleListeners) {\n+ public InMemoryStubMappings(Scenarios scenarios, Map<String, RequestMatcherExtension> customMatchers, Map<String, ResponseDefinitionTransformer> transformers, FileSource rootFileSource, List<StubLifecycleListener> stubLifecycleListeners) {\n+ this.scenarios = scenarios;\nthis.customMatchers = customMatchers;\nthis.transformers = transformers;\nthis.rootFileSource = rootFileSource;\n@@ -59,7 +60,8 @@ public class InMemoryStubMappings implements StubMappings {\n}\npublic InMemoryStubMappings() {\n- this(Collections.<String, RequestMatcherExtension>emptyMap(),\n+ this(new Scenarios(),\n+ Collections.<String, RequestMatcherExtension>emptyMap(),\nCollections.<String, ResponseDefinitionTransformer>emptyMap(),\nnew SingleRootFileSource(\".\"),\nCollections.<StubLifecycleListener>emptyList()\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMiss.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMiss.java", "diff": "@@ -23,36 +23,39 @@ import com.github.tomakehurst.wiremock.matching.RequestPattern;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.diff.Diff;\n-import static com.google.common.base.MoreObjects.firstNonNull;\n-\npublic class NearMiss implements Comparable<NearMiss> {\nprivate final LoggedRequest request;\nprivate final StubMapping mapping;\nprivate final RequestPattern requestPattern;\nprivate final MatchResult matchResult;\n+ private final String scenarioState;\n@JsonCreator\npublic NearMiss(@JsonProperty(\"request\") LoggedRequest request,\n@JsonProperty(\"stubMapping\") StubMapping mapping,\n@JsonProperty(\"requestPattern\") RequestPattern requestPattern,\n- @JsonProperty(\"matchResult\") MatchResult matchResult) {\n+ @JsonProperty(\"matchResult\") MatchResult matchResult,\n+ @JsonProperty(\"scenarioState\") String scenarioState\n+ ) {\nthis.request = request;\nthis.mapping = mapping;\nthis.requestPattern = requestPattern;\nthis.matchResult = matchResult;\n+ this.scenarioState = scenarioState;\n}\npublic NearMiss(LoggedRequest request,\nStubMapping mapping,\n- MatchResult matchResult) {\n- this(request, mapping, null, matchResult);\n+ MatchResult matchResult,\n+ String scenarioState) {\n+ this(request, mapping, null, matchResult, scenarioState);\n}\npublic NearMiss(LoggedRequest request,\nRequestPattern requestPattern,\nMatchResult matchResult) {\n- this(request, null, requestPattern, matchResult);\n+ this(request, null, requestPattern, matchResult, null);\n}\npublic LoggedRequest getRequest() {\n@@ -82,7 +85,7 @@ public class NearMiss implements Comparable<NearMiss> {\nreturn new Diff(requestPattern, request);\n}\n- return new Diff(getStubMapping(), request);\n+ return new Diff(getStubMapping(), request, scenarioState);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMissCalculator.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMissCalculator.java", "diff": "@@ -17,9 +17,7 @@ package com.github.tomakehurst.wiremock.verification;\nimport com.github.tomakehurst.wiremock.matching.MatchResult;\nimport com.github.tomakehurst.wiremock.matching.RequestPattern;\n-import com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n-import com.github.tomakehurst.wiremock.stubbing.StubMapping;\n-import com.github.tomakehurst.wiremock.stubbing.StubMappings;\n+import com.github.tomakehurst.wiremock.stubbing.*;\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\n@@ -41,10 +39,12 @@ public class NearMissCalculator {\nprivate final StubMappings stubMappings;\nprivate final RequestJournal requestJournal;\n+ private final Scenarios scenarios;\n- public NearMissCalculator(StubMappings stubMappings, RequestJournal requestJournal) {\n+ public NearMissCalculator(StubMappings stubMappings, RequestJournal requestJournal, Scenarios scenarios) {\nthis.stubMappings = stubMappings;\nthis.requestJournal = requestJournal;\n+ this.scenarios = scenarios;\n}\npublic List<NearMiss> findNearestTo(final LoggedRequest request) {\n@@ -53,11 +53,21 @@ public class NearMissCalculator {\nreturn sortAndTruncate(from(allMappings).transform(new Function<StubMapping, NearMiss>() {\npublic NearMiss apply(StubMapping stubMapping) {\nMatchResult matchResult = stubMapping.getRequest().match(request);\n- return new NearMiss(request, stubMapping, matchResult);\n+ String actualScenarioState = getScenarioStateOrNull(stubMapping);\n+ return new NearMiss(request, stubMapping, matchResult, actualScenarioState);\n}\n}), allMappings.size());\n}\n+ private String getScenarioStateOrNull(StubMapping stubMapping) {\n+ if (!stubMapping.isInScenario()) {\n+ return null;\n+ }\n+\n+ Scenario scenario = scenarios.getByName(stubMapping.getScenarioName());\n+ return scenario != null ? scenario.getState() : null;\n+ }\n+\npublic List<NearMiss> findNearestTo(final RequestPattern requestPattern) {\nList<ServeEvent> serveEvents = requestJournal.getAllServeEvents();\nreturn sortAndTruncate(from(serveEvents).transform(new Function<ServeEvent, NearMiss>() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "diff": "@@ -21,9 +21,6 @@ import com.github.tomakehurst.wiremock.common.xml.Xml;\nimport com.github.tomakehurst.wiremock.http.*;\nimport com.github.tomakehurst.wiremock.matching.*;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n-import com.google.common.base.Joiner;\n-import com.google.common.base.Predicates;\n-import com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport java.net.URI;\n@@ -34,24 +31,36 @@ import java.util.Map;\nimport static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\nimport static com.github.tomakehurst.wiremock.verification.diff.SpacerLine.SPACER;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n-import static java.util.Arrays.asList;\npublic class Diff {\nprivate final String stubMappingName;\nprivate final RequestPattern requestPattern;\nprivate final Request request;\n+ private final String scenarioName;\n+ private final String scenarioState;\n+ private final String expectedScenarioState;\npublic Diff(RequestPattern expected, Request actual) {\nthis.requestPattern = expected;\nthis.request = actual;\nthis.stubMappingName = null;\n+ this.scenarioName = null;\n+ this.scenarioState = null;\n+ this.expectedScenarioState = null;\n}\npublic Diff(StubMapping expected, Request actual) {\n+ this(expected, actual, null);\n+ }\n+\n+ public Diff(StubMapping expected, Request actual, String scenarioState) {\nthis.requestPattern = expected.getRequest();\nthis.request = actual;\nthis.stubMappingName = expected.getName();\n+ this.scenarioName = expected.getScenarioName();\n+ this.scenarioState = scenarioState;\n+ this.expectedScenarioState = expected.getRequiredScenarioState();\n}\n@Override\n@@ -174,10 +183,22 @@ public class Diff {\n}\n}\n+ if (scenarioName != null) {\n+ builder.add(new DiffLine<>(\n+ \"Scenario\",\n+ new EqualToPattern(expectedScenarioState),\n+ buildScenarioLine(scenarioName, scenarioState),\n+ buildScenarioLine(scenarioName, expectedScenarioState))\n+ );\n+ }\nreturn builder.build();\n}\n+ private static String buildScenarioLine(String scenarioName, String scenarioState) {\n+ return \"[Scenario '\" + scenarioName + \"' state: \" + scenarioState + \"]\";\n+ }\n+\nprivate void addHeaderSection(Map<String, MultiValuePattern> headerPatterns, HttpHeaders headers, ImmutableList.Builder<DiffLine<?>> builder) {\nboolean anyHeaderSections = false;\nif (headerPatterns != null && !headerPatterns.isEmpty()) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "diff": "@@ -166,6 +166,20 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), containsString(\"No response could be served\"));\n}\n+ @Test\n+ public void indicatesWhenWrongScenarioStateIsTheReasonForNonMatch() {\n+ configure();\n+\n+ stubFor(post(\"/thing\")\n+ .inScenario(\"thing states\")\n+ .whenScenarioStateIs(\"first\")\n+ .willReturn(ok(\"Done!\")));\n+\n+ WireMockResponse response = testClient.postJson(\"/thing\", \"{}\");\n+\n+ assertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample_scenario-state.txt\")));\n+ }\n+\nprivate void configure() {\nconfigure(WireMockConfiguration.wireMockConfig().dynamicPort());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissCalculatorTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissCalculatorTest.java", "diff": "@@ -17,11 +17,8 @@ package com.github.tomakehurst.wiremock.verification;\nimport com.github.tomakehurst.wiremock.client.MappingBuilder;\nimport com.github.tomakehurst.wiremock.http.Request;\n-import com.github.tomakehurst.wiremock.http.RequestMethod;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n-import com.github.tomakehurst.wiremock.matching.EqualToPattern;\n-import com.github.tomakehurst.wiremock.matching.MatchResult;\n-import com.github.tomakehurst.wiremock.matching.WeightedMatchResult;\n+import com.github.tomakehurst.wiremock.stubbing.Scenarios;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.stubbing.StubMappings;\n@@ -51,6 +48,7 @@ public class NearMissCalculatorTest {\nStubMappings stubMappings;\nRequestJournal requestJournal;\n+ Scenarios scenarios;\n@Before\npublic void init() {\n@@ -58,7 +56,8 @@ public class NearMissCalculatorTest {\nstubMappings = context.mock(StubMappings.class);\nrequestJournal = context.mock(RequestJournal.class);\n- nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal);\n+ scenarios = new Scenarios();\n+ nearMissCalculator = new NearMissCalculator(stubMappings, requestJournal, scenarios);\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/NearMissTest.java", "diff": "@@ -74,7 +74,8 @@ public class NearMissTest {\nString json = Json.write(new NearMiss(\nLoggedRequest.createFrom(mockRequest().method(HEAD).url(\"/nearly-missed-me\")),\nget(urlEqualTo(\"/missed-me\")).willReturn(aResponse()).build(),\n- MatchResult.partialMatch(0.5)\n+ MatchResult.partialMatch(0.5),\n+ null\n));\nassertThat(json, equalToJson(STUB_MAPPING_EXAMPLE, LENIENT));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "diff": "@@ -17,9 +17,8 @@ package com.github.tomakehurst.wiremock.verification.diff;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.matching.MatchResult;\n-import com.github.tomakehurst.wiremock.matching.RequestMatcher;\n-import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;\nimport com.github.tomakehurst.wiremock.matching.ValueMatcher;\n+import com.github.tomakehurst.wiremock.stubbing.Scenario;\nimport org.junit.Test;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\n@@ -470,4 +469,30 @@ public class DiffTest {\n\"not absent\")\n));\n}\n+\n+ @Test\n+ public void indicatesThatScenarioStateDiffersWhenStubAndRequestOtherwiseMatch() {\n+ Diff diff = new Diff(\n+ get(\"/stateful\")\n+ .inScenario(\"my-steps\")\n+ .whenScenarioStateIs(\"step2\")\n+ .willReturn(ok(\"Yep\")).build(),\n+ mockRequest()\n+ .method(GET)\n+ .url(\"/stateful\"),\n+ Scenario.STARTED\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"GET\\n\" +\n+ \"/stateful\\n\\n\" +\n+ \"[Scenario 'my-steps' state: step2]\"\n+ ,\n+ \"GET\\n\" +\n+ \"/stateful\\n\\n\" +\n+ \"[Scenario 'my-steps' state: Started]\"\n+ )\n+ ));\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java", "diff": "@@ -35,7 +35,6 @@ import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.matching.RequestPatternBuilder.newRequestPattern;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.file;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\n-import static com.github.tomakehurst.wiremock.verification.diff.JUnitStyleDiffRenderer.junitStyleDiffMessage;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -199,8 +198,7 @@ public class PlainTextDiffRendererTest {\n\" </thing>\\n\" +\n\" </thing>\\n\" +\n\" </thing>\\n\" +\n- \"</deep-things>\")\n- );\n+ \"</deep-things>\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -216,8 +214,7 @@ public class PlainTextDiffRendererTest {\n.build(),\nmockRequest()\n.method(POST)\n- .url(\"/thing\")\n- );\n+ .url(\"/thing\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -246,8 +243,7 @@ public class PlainTextDiffRendererTest {\n\" }\\n\" +\n\" }\\n\" +\n\" }\\n\" +\n- \"}\"))\n- );\n+ \"}\")));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -262,8 +258,7 @@ public class PlainTextDiffRendererTest {\n.build(),\nmockRequest()\n.method(GET)\n- .url(\"/thing\")\n- );\n+ .url(\"/thing\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -299,8 +294,7 @@ public class PlainTextDiffRendererTest {\n.part(mockPart()\n.name(\"part_two\")\n.body(\"Correct body\")\n- )\n- );\n+ ));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -320,8 +314,7 @@ public class PlainTextDiffRendererTest {\nmockRequest()\n.method(POST)\n.url(\"/thing\")\n- .body(\"Non-multipart body\")\n- );\n+ .body(\"Non-multipart body\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -343,8 +336,7 @@ public class PlainTextDiffRendererTest {\nmockRequest()\n.method(POST)\n- .url(\"/thing\")\n- );\n+ .url(\"/thing\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -361,8 +353,7 @@ public class PlainTextDiffRendererTest {\nmockRequest()\n.method(POST)\n- .url(\"/thing\")\n- );\n+ .url(\"/thing\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n@@ -382,8 +373,7 @@ public class PlainTextDiffRendererTest {\nmockRequest()\n.method(POST)\n- .url(\"/thing\")\n- );\n+ .url(\"/thing\"));\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/resources/not-found-diff-sample_scenario-state.txt", "diff": "+\n+ Request was not matched\n+ =======================\n+\n+-----------------------------------------------------------------------------------------------------------------------\n+| Closest stub | Request |\n+-----------------------------------------------------------------------------------------------------------------------\n+ |\n+POST | POST\n+/thing | /thing\n+ |\n+[Scenario 'thing states' state: first] | [Scenario 'thing states' state: Started] <<<<< Scenario does not match\n+ |\n+-----------------------------------------------------------------------------------------------------------------------\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Now reports scenario state mismatch in diff reports
686,936
25.06.2020 12:46:48
-3,600
31bff0a82e82cd83e4bf339324d3ed94987ef6d5
Fixed - added ResponseDefinitionBuilder.withTransformerParameters, taking a Map argument
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/ResponseDefinitionBuilder.java", "diff": "@@ -140,6 +140,11 @@ public class ResponseDefinitionBuilder {\nreturn this;\n}\n+ public ResponseDefinitionBuilder withTransformerParameters(Map<String, Object> parameters) {\n+ transformerParameters.putAll(parameters);\n+ return this;\n+ }\n+\npublic ResponseDefinitionBuilder withTransformerParameter(String name, Object value) {\ntransformerParameters.put(name, value);\nreturn this;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1329 - added ResponseDefinitionBuilder.withTransformerParameters, taking a Map argument
686,936
25.06.2020 12:51:20
-3,600
036c512a86ad2c2d47d840d560b97268f6701069
Fixed - catch initialisation exceptions in the hostname helper so that they don't escape and cause startup to fail.
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HostnameHelper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/HostnameHelper.java", "diff": "@@ -21,6 +21,7 @@ import java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\npublic class HostnameHelper extends HandlebarsHelper<Object> {\n@@ -29,8 +30,9 @@ public class HostnameHelper extends HandlebarsHelper<Object> {\nstatic {\ntry {\nHOSTNAME = InetAddress.getLocalHost().getHostName();\n- } catch (UnknownHostException e) {\n- throwUnchecked(e, String.class);\n+ } catch (Exception e) {\n+ notifier().error(\"Failed to look up localhost. {{hostname}} Handlebars helper will return localhost.\", e);\n+ HOSTNAME = \"localhost\";\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1327 - catch initialisation exceptions in the hostname helper so that they don't escape and cause startup to fail.
686,936
25.06.2020 13:33:15
-3,600
57be657fa3e51d99f93053aa7a21bcd2ac499542
Tweaked text and styles of CA cert note on recorder page
[ { "change_type": "MODIFY", "old_path": "src/main/resources/assets/recorder/index.html", "new_path": "src/main/resources/assets/recorder/index.html", "diff": ".content {\nmargin: auto;\nwidth: 600px;\n- height: 300px;\n+ /*height: 300px;*/\npadding-top: 100px;\nvertical-align: middle;\n}\n+ .ca-cert-box {\n+ border: 1px solid black;\n+ padding: 1em;\n+ vertical-align: middle;\n+ margin-top: 60px;\n+ color: #898989;\n+ font-size: 90%;\n+ }\n+\n+ .ca-cert-box a {\n+ color: #42407d;\n+ }\n+\n+ .ca-cert-box a:visited {\n+ color: #42407d;\n+ }\n+\nbutton {\nbackground-color: #1D2539;\npadding: 10px;\n<button id=\"startRecording\" disabled=\"disabled\">Record</button>\n<button id=\"stopRecording\" disabled=\"disabled\">Stop</button>\n- <p>\n- Certificate to trust when browser proxying HTTPS sites:<p>\n- <a href=\"../certs/wiremock-ca.crt\">wiremock-ca.crt</a><p>\n- This self-signed certificate is marked as a certificate authority, and contains the public key that is paired with the private key provided in the keystore specified using the <code>--ca-keystore</code> option.<p>\n- By default this is a securely generated private key local to the system where WireMock is running.<p>\n- WireMock will serve generated certificates signed with this private key for any HTTPS site you visit while using WireMock as your proxy server.<p>\n- Trusting this certificate will mean your browser (or other client) will trust those generated certificates.<p>\n- This will be secure provided nobody else ever gets hold of the private key.\n+\n+ <div class=\"ca-cert-box\">\n+ <p>To record stubs from an HTTPS endpoint using browser (forward) proxying, you may need to trust WireMock's CA cert, which\n+ can be downloaded here: <a href=\"../certs/wiremock-ca.crt\">wiremock-ca.crt</a>\n+ <p>See the <a href=\"http://wiremock.org/docs/proxying/#browser-proxying-of-https\" target=\"_blank\">documentation on HTTPS proxying</a> for more details.\n+ </div>\n</div>\n<script type=\"text/javascript\">\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Tweaked text and styles of CA cert note on recorder page
686,936
25.06.2020 13:38:32
-3,600
a6f0cd1cbb2806facfeff9ed9943bbb631a1519e
Tweaked a style on the recorder page
[ { "change_type": "MODIFY", "old_path": "src/main/resources/assets/recorder/index.html", "new_path": "src/main/resources/assets/recorder/index.html", "diff": "border: 1px solid black;\npadding: 1em;\nvertical-align: middle;\n- margin-top: 60px;\n+ margin-top: 80px;\ncolor: #898989;\nfont-size: 90%;\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Tweaked a style on the recorder page
686,936
25.06.2020 16:09:39
-3,600
ea72c0d12d8600cc922289b302851adea84b9330
Now prints more specific output in a diff when matchesJsonPath and matchesXPath are used with sub-matches
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPattern.java", "diff": "@@ -80,17 +80,29 @@ public class MatchesJsonPathPattern extends PathPattern {\nreturn MatchResult.noMatch();\n}\n-\n}\nprotected MatchResult isAdvancedMatch(String value) {\n+ try {\n+ String expressionResult = getExpressionResult(value);\n+ return valuePattern.match(expressionResult);\n+ } catch (SubExpressionException e) {\n+ notifier().info(e.getMessage());\n+ return MatchResult.noMatch();\n+ }\n+ }\n+\n+ @Override\n+ public String getExpressionResult(final String value) {\n// For performance reason, don't try to parse XML value\nif (value != null && value.trim().startsWith(\"<\")) {\n- notifier().info(String.format(\n+ final String message = String.format(\n\"Warning: JSON path expression '%s' failed to match document '%s' because it's not JSON document\",\n- expectedValue, value));\n- return MatchResult.noMatch();\n+ expectedValue, value);\n+ notifier().info(message);\n+ throw new SubExpressionException(message);\n}\n+\nObject obj = null;\ntry {\nobj = JsonPath.read(value, expectedValue);\n@@ -106,19 +118,19 @@ public class MatchesJsonPathPattern extends PathPattern {\nString message = String.format(\n\"Warning: JSON path expression '%s' failed to match document '%s' because %s\",\nexpectedValue, value, error);\n- notifier().info(message);\n- return MatchResult.noMatch();\n+ throw new SubExpressionException(message, e);\n}\n+ String expressionResult;\nif (obj instanceof Number || obj instanceof String || obj instanceof Boolean) {\n- value = String.valueOf(obj);\n+ expressionResult = String.valueOf(obj);\n} else if (obj instanceof Map || obj instanceof Collection) {\n- value = Json.write(obj);\n+ expressionResult = Json.write(obj);\n} else {\n- value = null;\n+ expressionResult = null;\n}\n- return valuePattern.match(value);\n+ return expressionResult;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MatchesXPathPattern.java", "diff": "@@ -19,10 +19,12 @@ import com.fasterxml.jackson.annotation.JsonGetter;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonSerialize;\nimport com.github.tomakehurst.wiremock.common.ListOrSingle;\n+import com.github.tomakehurst.wiremock.common.Pair;\nimport com.github.tomakehurst.wiremock.common.xml.*;\nimport com.google.common.collect.ImmutableMap;\nimport java.util.Collections;\n+import java.util.Comparator;\nimport java.util.Map;\nimport java.util.SortedSet;\n@@ -92,6 +94,27 @@ public class MatchesXPathPattern extends PathPattern {\nreturn results.last();\n}\n+ @Override\n+ public String getExpressionResult(String value) {\n+ ListOrSingle<XmlNode> nodeList = findXmlNodes(value);\n+ if (nodeList == null || nodeList.size() == 0) {\n+ return null;\n+ }\n+\n+ SortedSet<Pair<XmlNode, MatchResult>> results = newTreeSet(new Comparator<Pair<XmlNode, MatchResult>>() {\n+ @Override\n+ public int compare(Pair<XmlNode, MatchResult> one, Pair<XmlNode, MatchResult> two) {\n+ return one.b.compareTo(two.b);\n+ }\n+ });\n+\n+ for (XmlNode node: nodeList) {\n+ results.add(new Pair<>(node, valuePattern.match(node.toString())));\n+ }\n+\n+ return results.last().a.toString();\n+ }\n+\nprivate ListOrSingle<XmlNode> findXmlNodes(String value) {\n// For performance reason, don't try to parse non XML value\nif (value == null || !value.trim().startsWith(\"<\")) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java", "diff": "@@ -48,6 +48,7 @@ public abstract class PathPattern extends MemoizingStringValuePattern {\nprotected abstract MatchResult isSimpleMatch(String value);\nprotected abstract MatchResult isAdvancedMatch(String value);\n+ public abstract String getExpressionResult(String value);\n@Override\npublic boolean equals(Object o) {\n@@ -62,4 +63,14 @@ public abstract class PathPattern extends MemoizingStringValuePattern {\npublic int hashCode() {\nreturn Objects.hash(super.hashCode(), valuePattern);\n}\n+\n+ protected static class SubExpressionException extends RuntimeException {\n+ public SubExpressionException(String message) {\n+ super(message);\n+ }\n+\n+ public SubExpressionException(String message, Throwable cause) {\n+ super(message, cause);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "diff": "@@ -224,7 +224,23 @@ public class Diff {\nif (bodyPatterns != null && !bodyPatterns.isEmpty()) {\nfor (ContentPattern<?> pattern: bodyPatterns) {\nString formattedBody = formatIfJsonOrXml(pattern, body);\n- if (StringValuePattern.class.isAssignableFrom(pattern.getClass())) {\n+ if (PathPattern.class.isAssignableFrom(pattern.getClass())) {\n+ PathPattern pathPattern = (PathPattern) pattern;\n+ if (!pathPattern.isSimple()) {\n+ String expressionResult = pathPattern.getExpressionResult(body.asString());\n+ String printedExpectedValue =\n+ pathPattern.getExpected() +\n+ \" [\" + pathPattern.getValuePattern().getName() + \"] \" +\n+ pathPattern.getValuePattern().getExpected();\n+ if (expressionResult != null) {\n+ builder.add(new DiffLine<>(\"Body\", pathPattern.getValuePattern(), expressionResult, printedExpectedValue));\n+ } else {\n+ builder.add(new DiffLine<>(\"Body\", pathPattern, formattedBody, printedExpectedValue));\n+ }\n+ } else {\n+ builder.add(new DiffLine<>(\"Body\", pathPattern, formattedBody, pattern.getExpected()));\n+ }\n+ } else if (StringValuePattern.class.isAssignableFrom(pattern.getClass())) {\nStringValuePattern stringValuePattern = (StringValuePattern) pattern;\nbuilder.add(new DiffLine<>(\"Body\", stringValuePattern, formattedBody, pattern.getExpected()));\n} else {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/MatchesJsonPathPatternTest.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.matching;\n-import com.fasterxml.jackson.databind.JsonMappingException;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.common.Json;\nimport com.github.tomakehurst.wiremock.common.JsonException;\n@@ -28,6 +27,7 @@ import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalToJson;\nimport static org.hamcrest.Matchers.*;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "diff": "@@ -495,4 +495,54 @@ public class DiffTest {\n)\n));\n}\n+\n+ @Test\n+ public void includesSpecificDiffForJsonPathSubMatchWhenElementFound() {\n+ Diff diff = new Diff(\n+ post(\"/submatch\")\n+ .withRequestBody(matchingJsonPath(\"$.name\", containing(\"Tom\")))\n+ .willReturn(ok(\"Yep\")).build(),\n+ mockRequest()\n+ .method(POST)\n+ .url(\"/submatch\")\n+ .body(\"{\\\"name\\\": \\\"Rob\\\"}\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"POST\\n\" +\n+ \"/submatch\\n\\n\" +\n+ \"$.name [contains] Tom\"\n+ ,\n+ \"POST\\n\" +\n+ \"/submatch\\n\\n\" +\n+ \"Rob\"\n+ )\n+ ));\n+ }\n+\n+ @Test\n+ public void includesSpecificDiffForJsonPathSubMatchWhenElementNotFound() {\n+ Diff diff = new Diff(\n+ post(\"/submatch\")\n+ .withRequestBody(matchingJsonPath(\"$.name\", containing(\"Tom\")))\n+ .willReturn(ok(\"Yep\")).build(),\n+ mockRequest()\n+ .method(POST)\n+ .url(\"/submatch\")\n+ .body(\"{\\\"id\\\": \\\"abc123\\\"}\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"POST\\n\" +\n+ \"/submatch\\n\\n\" +\n+ \"$.name [contains] Tom\"\n+ ,\n+ \"POST\\n\" +\n+ \"/submatch\\n\\n\" +\n+ \"{\\\"id\\\": \\\"abc123\\\"}\"\n+ )\n+ ));\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java", "diff": "@@ -252,6 +252,25 @@ public class PlainTextDiffRendererTest {\nassertThat(output, equalsMultiLine(expected));\n}\n+ @Test\n+ public void showsXPathWithSubMatchMismatch() {\n+ Diff diff = new Diff(post(\"/thing\")\n+ .withRequestBody(matchingXPath(\"//thing/text()\", equalTo(\"two\")))\n+ .build(),\n+ mockRequest()\n+ .method(POST)\n+ .url(\"/thing\")\n+ .body(\"<stuff>\\n\" +\n+ \" <thing>one</thing>\\n\" +\n+ \"</stuff>\"));\n+\n+ String output = diffRenderer.render(diff);\n+ System.out.println(output);\n+\n+ String expected = file(\"not-found-diff-sample_xpath-with-submatch.txt\");\n+ assertThat(output, equalsMultiLine(expected));\n+ }\n+\n@Test\npublic void showsUrlRegexUnescapedMessage() {\nDiff diff = new Diff(get(urlMatching(\"thing?query=value\"))\n@@ -381,7 +400,6 @@ public class PlainTextDiffRendererTest {\nassertThat(output, equalsMultiLine(file(\"not-found-diff-sample_only-custom_matcher.txt\")));\n}\n-\n@Test\npublic void handlesUrlsWithQueryStringAndNoPath() {\nDiff diff = new Diff(\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/resources/not-found-diff-sample_xpath-with-submatch.txt", "diff": "+\n+ Request was not matched\n+ =======================\n+\n+-----------------------------------------------------------------------------------------------------------------------\n+| Closest stub | Request |\n+-----------------------------------------------------------------------------------------------------------------------\n+ |\n+POST | POST\n+/thing | /thing\n+ |\n+//thing/text() [equalTo] two | one <<<<< Body does not match\n+ |\n+-----------------------------------------------------------------------------------------------------------------------\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Now prints more specific output in a diff when matchesJsonPath and matchesXPath are used with sub-matches
686,936
26.06.2020 13:52:19
-3,600
9fdd9e1016f35e0542f5bf08ff25e7cf6cbb9232
Added ability to match requests by host
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "diff": "@@ -69,6 +69,12 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nreturn this;\n}\n+ @Override\n+ public MappingBuilder withHost(StringValuePattern hostPattern) {\n+ requestPatternBuilder.withHost(hostPattern);\n+ return this;\n+ }\n+\n@Override\npublic BasicMappingBuilder withHeader(String key, StringValuePattern headerPattern) {\nrequestPatternBuilder.withHeader(key, headerPattern);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "diff": "@@ -23,13 +23,14 @@ import com.github.tomakehurst.wiremock.matching.MultipartValuePatternBuilder;\nimport com.github.tomakehurst.wiremock.matching.StringValuePattern;\nimport com.github.tomakehurst.wiremock.matching.ValueMatcher;\nimport com.github.tomakehurst.wiremock.stubbing.StubMapping;\n-import com.google.common.collect.ImmutableMap;\nimport java.util.Map;\nimport java.util.UUID;\npublic interface MappingBuilder {\n+ MappingBuilder withHost(StringValuePattern hostPattern);\n+\nMappingBuilder atPriority(Integer priority);\nMappingBuilder withHeader(String key, StringValuePattern headerPattern);\nMappingBuilder withQueryParam(String key, StringValuePattern queryParamPattern);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java", "diff": "@@ -43,6 +43,7 @@ import static java.util.Arrays.asList;\npublic class RequestPattern implements NamedValueMatcher<Request> {\n+ private final StringValuePattern host;\nprivate final UrlPattern url;\nprivate final RequestMethod method;\nprivate final Map<String, MultiValuePattern> headers;\n@@ -56,7 +57,8 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nprivate final ValueMatcher<Request> matcher;\nprivate final boolean hasInlineCustomMatcher;\n- public RequestPattern(final UrlPattern url,\n+ public RequestPattern(final StringValuePattern host,\n+ final UrlPattern url,\nfinal RequestMethod method,\nfinal Map<String, MultiValuePattern> headers,\nfinal Map<String, MultiValuePattern> queryParams,\n@@ -66,6 +68,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nfinal CustomMatcherDefinition customMatcherDefinition,\nfinal ValueMatcher<Request> customMatcher,\nfinal List<MultipartValuePattern> multiPattern) {\n+ this.host = host;\nthis.url = firstNonNull(url, UrlPattern.ANY);\nthis.method = firstNonNull(method, RequestMethod.ANY);\nthis.headers = headers;\n@@ -81,6 +84,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@Override\npublic MatchResult match(Request request) {\nList<WeightedMatchResult> matchResults = new ArrayList<>(asList(\n+ weight(hostMatches(request), 10.0),\nweight(RequestPattern.this.url.match(request.getUrl()), 10.0),\nweight(RequestPattern.this.method.match(request.getMethod()), 3.0),\n@@ -107,7 +111,8 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n}\n@JsonCreator\n- public RequestPattern(@JsonProperty(\"url\") String url,\n+ public RequestPattern(@JsonProperty(\"host\") StringValuePattern host,\n+ @JsonProperty(\"url\") String url,\n@JsonProperty(\"urlPattern\") String urlPattern,\n@JsonProperty(\"urlPath\") String urlPath,\n@JsonProperty(\"urlPathPattern\") String urlPathPattern,\n@@ -121,6 +126,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@JsonProperty(\"multipartPatterns\") List<MultipartValuePattern> multiPattern) {\nthis(\n+ host,\nUrlPattern.fromOneOf(url, urlPattern, urlPath, urlPathPattern),\nmethod,\nheaders,\n@@ -135,6 +141,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n}\npublic static RequestPattern ANYTHING = new RequestPattern(\n+ null,\nWireMock.anyUrl(),\nRequestMethod.ANY,\nnull,\n@@ -148,11 +155,11 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n);\npublic RequestPattern(ValueMatcher<Request> customMatcher) {\n- this(UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, null, customMatcher, null);\n+ this(null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, null, customMatcher, null);\n}\npublic RequestPattern(CustomMatcherDefinition customMatcherDefinition) {\n- this(UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, customMatcherDefinition, null, null);\n+ this(null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, customMatcherDefinition, null, null);\n}\n@Override\n@@ -210,6 +217,12 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nreturn MatchResult.exactMatch();\n}\n+ private MatchResult hostMatches(final Request request) {\n+ return host != null ?\n+ host.match(request.getHost()) :\n+ MatchResult.exactMatch();\n+ }\n+\nprivate MatchResult allHeadersMatchResult(final Request request) {\nMap<String, MultiValuePattern> combinedHeaders = combineBasicAuthAndOtherHeaders();\n@@ -304,6 +317,10 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nreturn match(request, customMatchers).isExactMatch();\n}\n+ public StringValuePattern getHost() {\n+ return host;\n+ }\n+\npublic String getUrl() {\nreturn urlPatternOrNull(UrlPattern.class, false);\n}\n@@ -393,21 +410,23 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nif (this == o) return true;\nif (o == null || getClass() != o.getClass()) return false;\nRequestPattern that = (RequestPattern) o;\n- return Objects.equals(url, that.url) &&\n+ return hasInlineCustomMatcher == that.hasInlineCustomMatcher &&\n+ Objects.equals(host, that.host) &&\n+ Objects.equals(url, that.url) &&\nObjects.equals(method, that.method) &&\nObjects.equals(headers, that.headers) &&\nObjects.equals(queryParams, that.queryParams) &&\nObjects.equals(cookies, that.cookies) &&\nObjects.equals(basicAuthCredentials, that.basicAuthCredentials) &&\nObjects.equals(bodyPatterns, that.bodyPatterns) &&\n+ Objects.equals(multipartPatterns, that.multipartPatterns) &&\nObjects.equals(customMatcherDefinition, that.customMatcherDefinition) &&\n- Objects.equals(matcher, that.matcher) &&\n- Objects.equals(multipartPatterns, that.multipartPatterns);\n+ Objects.equals(matcher, that.matcher);\n}\n@Override\npublic int hashCode() {\n- return Objects.hash(url, method, headers, queryParams, cookies, basicAuthCredentials, bodyPatterns, customMatcherDefinition, matcher, multipartPatterns);\n+ return Objects.hash(host, url, method, headers, queryParams, cookies, basicAuthCredentials, bodyPatterns, multipartPatterns, customMatcherDefinition, matcher, hasInlineCustomMatcher);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilder.java", "diff": "@@ -30,6 +30,7 @@ import static com.google.common.collect.Maps.newLinkedHashMap;\npublic class RequestPatternBuilder {\n+ private StringValuePattern hostPattern;\nprivate UrlPattern url = UrlPattern.ANY;\nprivate RequestMethod method = RequestMethod.ANY;\nprivate Map<String, MultiValuePattern> headers = newLinkedHashMap();\n@@ -87,6 +88,7 @@ public class RequestPatternBuilder {\n*/\npublic static RequestPatternBuilder like(RequestPattern requestPattern) {\nRequestPatternBuilder builder = new RequestPatternBuilder();\n+ builder.hostPattern = requestPattern.getHost();\nbuilder.url = requestPattern.getUrlMatcher();\nbuilder.method = requestPattern.getMethod();\nif (requestPattern.getHeaders() != null) {\n@@ -116,6 +118,11 @@ public class RequestPatternBuilder {\nreturn this;\n}\n+ public RequestPatternBuilder withHost(StringValuePattern hostPattern) {\n+ this.hostPattern = hostPattern;\n+ return this;\n+ }\n+\npublic RequestPatternBuilder withUrl(String url) {\nthis.url = WireMock.urlEqualTo(url);\nreturn this;\n@@ -182,6 +189,7 @@ public class RequestPatternBuilder {\npublic RequestPattern build() {\nreturn new RequestPattern(\n+ hostPattern,\nurl,\nmethod,\nheaders.isEmpty() ? null : headers,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "diff": "@@ -75,6 +75,13 @@ public class Diff {\npublic List<DiffLine<?>> getLines(Map<String, RequestMatcherExtension> customMatcherExtensions) {\nImmutableList.Builder<DiffLine<?>> builder = ImmutableList.builder();\n+ if (requestPattern.getHost() != null) {\n+ String hostOperator = generateOperatorString(requestPattern.getHost(), \"\");\n+ String printedHostPatternValue = hostOperator + requestPattern.getHost().getExpected();\n+ DiffLine<String> hostSection = new DiffLine<>(\"Host\", requestPattern.getHost(), request.getHost(), printedHostPatternValue.trim());\n+ builder.add(hostSection);\n+ }\n+\nDiffLine<RequestMethod> methodSection = new DiffLine<>(\"HTTP method\", requestPattern.getMethod(), request.getMethod(), requestPattern.getMethod().getName());\nbuilder.add(methodSection);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "diff": "+package com.github.tomakehurst.wiremock;\n+\n+import com.github.tomakehurst.wiremock.common.ConsoleNotifier;\n+import com.github.tomakehurst.wiremock.junit.WireMockClassRule;\n+import org.apache.http.HttpHost;\n+import org.apache.http.client.methods.CloseableHttpResponse;\n+import org.apache.http.client.methods.HttpUriRequest;\n+import org.apache.http.client.methods.RequestBuilder;\n+import org.apache.http.conn.DnsResolver;\n+import org.apache.http.impl.client.CloseableHttpClient;\n+import org.apache.http.impl.client.HttpClientBuilder;\n+import org.apache.http.impl.conn.SystemDefaultDnsResolver;\n+import org.apache.http.util.EntityUtils;\n+import org.junit.BeforeClass;\n+import org.junit.ClassRule;\n+import org.junit.Rule;\n+import org.junit.Test;\n+\n+import java.net.InetAddress;\n+import java.net.UnknownHostException;\n+\n+import static com.github.tomakehurst.wiremock.client.WireMock.*;\n+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\n+import static org.hamcrest.MatcherAssert.assertThat;\n+import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.not;\n+\n+public class StubbingWithBrowserProxyAcceptanceTest {\n+\n+ @ClassRule\n+ public static WireMockClassRule wm = new WireMockClassRule(wireMockConfig()\n+ .dynamicPort()\n+ .enableBrowserProxying(true)\n+ .notifier(new ConsoleNotifier(true))\n+ );\n+\n+ @Rule\n+ public WireMockClassRule instance = wm;\n+\n+ static CloseableHttpClient client;\n+\n+ @BeforeClass\n+ public static void init() {\n+ client = HttpClientBuilder.create()\n+ .setDnsResolver(new CustomLocalTldDnsResolver(\"internal\"))\n+ .setProxy(new HttpHost(\"localhost\", wm.port()))\n+ .build();\n+ }\n+\n+ @Test\n+ public void matchesOnHostname() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .withHost(equalTo(\"righthost.internal\"))\n+ .willReturn(ok(\"Got it\"))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://righthost.internal/mypath\").build();\n+ try (CloseableHttpResponse response = client.execute(request)) {\n+ assertThat(EntityUtils.toString(response.getEntity()), is(\"Got it\"));\n+ }\n+ }\n+\n+ @Test\n+ public void doesNotMatchOnHostnameWhenIncorrect() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .withHost(equalTo(\"righthost.internal\"))\n+ .willReturn(ok(\"Got it\"))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://wronghost.internal/mypath\").build();\n+ try (CloseableHttpResponse response = client.execute(request)) {\n+ assertThat(EntityUtils.toString(response.getEntity()), not(is(\"Got it\")));\n+ }\n+ }\n+\n+ private static class CustomLocalTldDnsResolver implements DnsResolver {\n+\n+ private final String tldToSendToLocalhost;\n+\n+ public CustomLocalTldDnsResolver(String tldToSendToLocalhost) {\n+ this.tldToSendToLocalhost = tldToSendToLocalhost;\n+ }\n+\n+ @Override\n+ public InetAddress[] resolve(String host) throws UnknownHostException {\n+\n+ if (host.endsWith(\".\" + tldToSendToLocalhost)) {\n+ return new InetAddress[] { InetAddress.getLocalHost() };\n+ } else {\n+ return new SystemDefaultDnsResolver().resolve(host);\n+ }\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilderTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilderTest.java", "diff": "@@ -70,6 +70,7 @@ public class RequestPatternBuilderTest {\npublic void likeRequestPatternWithoutCustomMatcher() {\n// Use a RequestPattern with everything defined except a custom matcher to ensure all fields are set properly\nRequestPattern requestPattern = new RequestPattern(\n+ WireMock.equalTo(\"my.wiremock.org\"),\nWireMock.urlEqualTo(\"/foo\"),\nRequestMethod.POST,\nImmutableMap.of(\"X-Header\", MultiValuePattern.of(WireMock.equalTo(\"bar\"))),\n@@ -121,6 +122,7 @@ public class RequestPatternBuilderTest {\n// Use a RequestPattern with everything defined except a custom matcher to ensure all fields are set properly\nRequestPattern requestPattern = new RequestPattern(\n+ WireMock.equalTo(\"my.wiremock.org\"),\nWireMock.urlEqualTo(\"/foo\"),\nRequestMethod.POST,\nImmutableMap.of(\"X-Header\", MultiValuePattern.of(WireMock.equalTo(\"bar\"))),\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "diff": "@@ -545,4 +545,52 @@ public class DiffTest {\n)\n));\n}\n+\n+ @Test\n+ public void includeHostnameIfSpecifiedWithEqualTo() {\n+ Diff diff = new Diff(\n+ newRequestPattern(ANY, urlEqualTo(\"/thing\"))\n+ .withHost(equalTo(\"my.host\"))\n+ .build(),\n+ mockRequest()\n+ .host(\"wrong.host\")\n+ .url(\"/thing\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"my.host\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ ,\n+ \"wrong.host\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ )\n+ ));\n+ }\n+\n+ @Test\n+ public void includeHostnameIfSpecifiedWithNonEqualTo() {\n+ Diff diff = new Diff(\n+ newRequestPattern(ANY, urlEqualTo(\"/thing\"))\n+ .withHost(containing(\"my.host\"))\n+ .build(),\n+ mockRequest()\n+ .host(\"wrong.host\")\n+ .url(\"/thing\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"[contains] my.host\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ ,\n+ \"wrong.host\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ )\n+ ));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added ability to match requests by host
686,936
26.06.2020 14:29:03
-3,600
c2a56aa7e0a97bd733e98db00b62f02ab97017fb
Added an extra test for host matching
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "diff": "@@ -73,6 +73,18 @@ public class StubbingWithBrowserProxyAcceptanceTest {\n}\n}\n+ @Test\n+ public void matchesAnyHostnameWhenNotSpecified() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .willReturn(ok(\"Got it\"))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://whatever.internal/mypath\").build();\n+ try (CloseableHttpResponse response = client.execute(request)) {\n+ assertThat(EntityUtils.toString(response.getEntity()), is(\"Got it\"));\n+ }\n+ }\n+\nprivate static class CustomLocalTldDnsResolver implements DnsResolver {\nprivate final String tldToSendToLocalhost;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added an extra test for host matching
686,936
27.06.2020 11:54:35
-3,600
8e5659b1e06a3c276c363d5a5dc47a9ba7336df3
Added ability to match stubs by port number
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "diff": "@@ -75,6 +75,12 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nreturn this;\n}\n+ @Override\n+ public MappingBuilder withPort(int port) {\n+ requestPatternBuilder.withPort(port);\n+ return this;\n+ }\n+\n@Override\npublic BasicMappingBuilder withHeader(String key, StringValuePattern headerPattern) {\nrequestPatternBuilder.withHeader(key, headerPattern);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "diff": "@@ -30,6 +30,7 @@ import java.util.UUID;\npublic interface MappingBuilder {\nMappingBuilder withHost(StringValuePattern hostPattern);\n+ MappingBuilder withPort(int port);\nMappingBuilder atPriority(Integer priority);\nMappingBuilder withHeader(String key, StringValuePattern headerPattern);\n@@ -39,21 +40,22 @@ public interface MappingBuilder {\nMappingBuilder withMultipartRequestBody(MultipartValuePatternBuilder multipartPatternBuilder);\nScenarioMappingBuilder inScenario(String scenarioName);\nMappingBuilder withId(UUID id);\n- MappingBuilder withName(String name);\n+ MappingBuilder withName(String name);\nMappingBuilder persistent();\n+\nMappingBuilder withBasicAuth(String username, String password);\nMappingBuilder withCookie(String name, StringValuePattern cookieValuePattern);\n<P> MappingBuilder withPostServeAction(String extensionName, P parameters);\n-\nMappingBuilder withMetadata(Map<String, ?> metadata);\nMappingBuilder withMetadata(Metadata metadata);\n- MappingBuilder withMetadata(Metadata.Builder metadata);\n+ MappingBuilder withMetadata(Metadata.Builder metadata);\nMappingBuilder andMatching(ValueMatcher<Request> requestMatcher);\nMappingBuilder andMatching(String customRequestMatcherName);\n+\nMappingBuilder andMatching(String customRequestMatcherName, Parameters parameters);\nMappingBuilder willReturn(ResponseDefinitionBuilder responseDefBuilder);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java", "diff": "@@ -44,6 +44,7 @@ import static java.util.Arrays.asList;\npublic class RequestPattern implements NamedValueMatcher<Request> {\nprivate final StringValuePattern host;\n+ private final Integer port;\nprivate final UrlPattern url;\nprivate final RequestMethod method;\nprivate final Map<String, MultiValuePattern> headers;\n@@ -58,6 +59,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nprivate final boolean hasInlineCustomMatcher;\npublic RequestPattern(final StringValuePattern host,\n+ final Integer port,\nfinal UrlPattern url,\nfinal RequestMethod method,\nfinal Map<String, MultiValuePattern> headers,\n@@ -69,6 +71,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nfinal ValueMatcher<Request> customMatcher,\nfinal List<MultipartValuePattern> multiPattern) {\nthis.host = host;\n+ this.port = port;\nthis.url = firstNonNull(url, UrlPattern.ANY);\nthis.method = firstNonNull(method, RequestMethod.ANY);\nthis.headers = headers;\n@@ -85,6 +88,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\npublic MatchResult match(Request request) {\nList<WeightedMatchResult> matchResults = new ArrayList<>(asList(\nweight(hostMatches(request), 10.0),\n+ weight(portMatches(request), 10.0),\nweight(RequestPattern.this.url.match(request.getUrl()), 10.0),\nweight(RequestPattern.this.method.match(request.getMethod()), 3.0),\n@@ -112,6 +116,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@JsonCreator\npublic RequestPattern(@JsonProperty(\"host\") StringValuePattern host,\n+ @JsonProperty(\"port\") Integer port,\n@JsonProperty(\"url\") String url,\n@JsonProperty(\"urlPattern\") String urlPattern,\n@JsonProperty(\"urlPath\") String urlPath,\n@@ -127,6 +132,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nthis(\nhost,\n+ port,\nUrlPattern.fromOneOf(url, urlPattern, urlPath, urlPathPattern),\nmethod,\nheaders,\n@@ -141,6 +147,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n}\npublic static RequestPattern ANYTHING = new RequestPattern(\n+ null,\nnull,\nWireMock.anyUrl(),\nRequestMethod.ANY,\n@@ -155,11 +162,11 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n);\npublic RequestPattern(ValueMatcher<Request> customMatcher) {\n- this(null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, null, customMatcher, null);\n+ this(null, null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, null, customMatcher, null);\n}\npublic RequestPattern(CustomMatcherDefinition customMatcherDefinition) {\n- this(null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, customMatcherDefinition, null, null);\n+ this(null, null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, customMatcherDefinition, null, null);\n}\n@Override\n@@ -223,6 +230,12 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nMatchResult.exactMatch();\n}\n+ private MatchResult portMatches(final Request request) {\n+ return port != null ?\n+ MatchResult.of(request.getPort() == port) :\n+ MatchResult.exactMatch();\n+ }\n+\nprivate MatchResult allHeadersMatchResult(final Request request) {\nMap<String, MultiValuePattern> combinedHeaders = combineBasicAuthAndOtherHeaders();\n@@ -321,6 +334,10 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nreturn host;\n}\n+ public Integer getPort() {\n+ return port;\n+ }\n+\npublic String getUrl() {\nreturn urlPatternOrNull(UrlPattern.class, false);\n}\n@@ -412,6 +429,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nRequestPattern that = (RequestPattern) o;\nreturn hasInlineCustomMatcher == that.hasInlineCustomMatcher &&\nObjects.equals(host, that.host) &&\n+ Objects.equals(port, that.port) &&\nObjects.equals(url, that.url) &&\nObjects.equals(method, that.method) &&\nObjects.equals(headers, that.headers) &&\n@@ -426,7 +444,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@Override\npublic int hashCode() {\n- return Objects.hash(host, url, method, headers, queryParams, cookies, basicAuthCredentials, bodyPatterns, multipartPatterns, customMatcherDefinition, matcher, hasInlineCustomMatcher);\n+ return Objects.hash(host, port, url, method, headers, queryParams, cookies, basicAuthCredentials, bodyPatterns, multipartPatterns, customMatcherDefinition, matcher, hasInlineCustomMatcher);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilder.java", "diff": "@@ -30,6 +30,7 @@ import static com.google.common.collect.Maps.newLinkedHashMap;\npublic class RequestPatternBuilder {\n+ private Integer port;\nprivate StringValuePattern hostPattern;\nprivate UrlPattern url = UrlPattern.ANY;\nprivate RequestMethod method = RequestMethod.ANY;\n@@ -89,6 +90,7 @@ public class RequestPatternBuilder {\npublic static RequestPatternBuilder like(RequestPattern requestPattern) {\nRequestPatternBuilder builder = new RequestPatternBuilder();\nbuilder.hostPattern = requestPattern.getHost();\n+ builder.port = requestPattern.getPort();\nbuilder.url = requestPattern.getUrlMatcher();\nbuilder.method = requestPattern.getMethod();\nif (requestPattern.getHeaders() != null) {\n@@ -123,6 +125,11 @@ public class RequestPatternBuilder {\nreturn this;\n}\n+ public RequestPatternBuilder withPort(int port) {\n+ this.port = port;\n+ return this;\n+ }\n+\npublic RequestPatternBuilder withUrl(String url) {\nthis.url = WireMock.urlEqualTo(url);\nreturn this;\n@@ -190,6 +197,7 @@ public class RequestPatternBuilder {\npublic RequestPattern build() {\nreturn new RequestPattern(\nhostPattern,\n+ port,\nurl,\nmethod,\nheaders.isEmpty() ? null : headers,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "diff": "@@ -29,6 +29,7 @@ import java.util.List;\nimport java.util.Map;\nimport static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;\n+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;\nimport static com.github.tomakehurst.wiremock.verification.diff.SpacerLine.SPACER;\nimport static com.google.common.base.MoreObjects.firstNonNull;\n@@ -82,6 +83,13 @@ public class Diff {\nbuilder.add(hostSection);\n}\n+ if (requestPattern.getPort() != null) {\n+ StringValuePattern expectedPort = equalTo(String.valueOf(requestPattern.getPort()));\n+ String actualPort = String.valueOf(request.getPort());\n+ DiffLine<String> portSection = new DiffLine<>(\"Port\", expectedPort, actualPort, expectedPort.getExpected());\n+ builder.add(portSection);\n+ }\n+\nDiffLine<RequestMethod> methodSection = new DiffLine<>(\"HTTP method\", requestPattern.getMethod(), request.getMethod(), requestPattern.getMethod().getName());\nbuilder.add(methodSection);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "diff": "@@ -27,6 +27,8 @@ import static org.hamcrest.Matchers.not;\npublic class StubbingWithBrowserProxyAcceptanceTest {\n+ static final String EXPECTED_RESPONSE_BODY = \"Got it\";\n+\n@ClassRule\npublic static WireMockClassRule wm = new WireMockClassRule(wireMockConfig()\n.dynamicPort()\n@@ -51,37 +53,65 @@ public class StubbingWithBrowserProxyAcceptanceTest {\npublic void matchesOnHostname() throws Exception {\nstubFor(get(urlPathEqualTo(\"/mypath\"))\n.withHost(equalTo(\"righthost.internal\"))\n- .willReturn(ok(\"Got it\"))\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n);\nHttpUriRequest request = RequestBuilder.get(\"http://righthost.internal/mypath\").build();\n- try (CloseableHttpResponse response = client.execute(request)) {\n- assertThat(EntityUtils.toString(response.getEntity()), is(\"Got it\"));\n- }\n+ makeRequestAndAssertOk(request);\n}\n@Test\npublic void doesNotMatchOnHostnameWhenIncorrect() throws Exception {\nstubFor(get(urlPathEqualTo(\"/mypath\"))\n.withHost(equalTo(\"righthost.internal\"))\n- .willReturn(ok(\"Got it\"))\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n);\nHttpUriRequest request = RequestBuilder.get(\"http://wronghost.internal/mypath\").build();\n- try (CloseableHttpResponse response = client.execute(request)) {\n- assertThat(EntityUtils.toString(response.getEntity()), not(is(\"Got it\")));\n- }\n+ makeRequestAndAssertNotOk(request);\n}\n@Test\npublic void matchesAnyHostnameWhenNotSpecified() throws Exception {\nstubFor(get(urlPathEqualTo(\"/mypath\"))\n- .willReturn(ok(\"Got it\"))\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n);\nHttpUriRequest request = RequestBuilder.get(\"http://whatever.internal/mypath\").build();\n+ makeRequestAndAssertOk(request);\n+ }\n+\n+ @Test\n+ public void matchesPortNumber() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .withPort(1234)\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://localhost:1234/mypath\").build();\n+ makeRequestAndAssertOk(request);\n+ }\n+\n+ @Test\n+ public void doesNotMatchOnPortNumberWhenIncorrect() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .withPort(1234)\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://localhost:4321/mypath\").build();\n+ makeRequestAndAssertNotOk(request);\n+ }\n+\n+ private void makeRequestAndAssertOk(HttpUriRequest request) throws Exception {\n+ try (CloseableHttpResponse response = client.execute(request)) {\n+ assertThat(EntityUtils.toString(response.getEntity()), is(EXPECTED_RESPONSE_BODY));\n+ }\n+ }\n+\n+ private void makeRequestAndAssertNotOk(HttpUriRequest request) throws Exception {\ntry (CloseableHttpResponse response = client.execute(request)) {\n- assertThat(EntityUtils.toString(response.getEntity()), is(\"Got it\"));\n+ assertThat(EntityUtils.toString(response.getEntity()), not(is(EXPECTED_RESPONSE_BODY)));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilderTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilderTest.java", "diff": "@@ -71,6 +71,7 @@ public class RequestPatternBuilderTest {\n// Use a RequestPattern with everything defined except a custom matcher to ensure all fields are set properly\nRequestPattern requestPattern = new RequestPattern(\nWireMock.equalTo(\"my.wiremock.org\"),\n+ 1234,\nWireMock.urlEqualTo(\"/foo\"),\nRequestMethod.POST,\nImmutableMap.of(\"X-Header\", MultiValuePattern.of(WireMock.equalTo(\"bar\"))),\n@@ -123,6 +124,7 @@ public class RequestPatternBuilderTest {\n// Use a RequestPattern with everything defined except a custom matcher to ensure all fields are set properly\nRequestPattern requestPattern = new RequestPattern(\nWireMock.equalTo(\"my.wiremock.org\"),\n+ 1234,\nWireMock.urlEqualTo(\"/foo\"),\nRequestMethod.POST,\nImmutableMap.of(\"X-Header\", MultiValuePattern.of(WireMock.equalTo(\"bar\"))),\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "diff": "@@ -593,4 +593,28 @@ public class DiffTest {\n)\n));\n}\n+\n+ @Test\n+ public void includePortIfSpecified() {\n+ Diff diff = new Diff(\n+ newRequestPattern(ANY, urlEqualTo(\"/thing\"))\n+ .withPort(5544)\n+ .build(),\n+ mockRequest()\n+ .port(6543)\n+ .url(\"/thing\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"5544\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ ,\n+ \"6543\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ )\n+ ));\n+ }\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added ability to match stubs by port number
686,936
27.06.2020 12:10:08
-3,600
eb4a6950a410fc67e97297d7614cfdbad5f0eec1
Added ability to match stubs by scheme (protocol)
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/BasicMappingBuilder.java", "diff": "@@ -69,6 +69,12 @@ class BasicMappingBuilder implements ScenarioMappingBuilder {\nreturn this;\n}\n+ @Override\n+ public MappingBuilder withScheme(String scheme) {\n+ requestPatternBuilder.withScheme(scheme);\n+ return this;\n+ }\n+\n@Override\npublic MappingBuilder withHost(StringValuePattern hostPattern) {\nrequestPatternBuilder.withHost(hostPattern);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/client/MappingBuilder.java", "diff": "@@ -29,6 +29,7 @@ import java.util.UUID;\npublic interface MappingBuilder {\n+ MappingBuilder withScheme(String scheme);\nMappingBuilder withHost(StringValuePattern hostPattern);\nMappingBuilder withPort(int port);\n@@ -39,21 +40,22 @@ public interface MappingBuilder {\nMappingBuilder withRequestBody(ContentPattern<?> bodyPattern);\nMappingBuilder withMultipartRequestBody(MultipartValuePatternBuilder multipartPatternBuilder);\nScenarioMappingBuilder inScenario(String scenarioName);\n- MappingBuilder withId(UUID id);\n+ MappingBuilder withId(UUID id);\nMappingBuilder withName(String name);\n+\nMappingBuilder persistent();\nMappingBuilder withBasicAuth(String username, String password);\nMappingBuilder withCookie(String name, StringValuePattern cookieValuePattern);\n-\n<P> MappingBuilder withPostServeAction(String extensionName, P parameters);\nMappingBuilder withMetadata(Map<String, ?> metadata);\n- MappingBuilder withMetadata(Metadata metadata);\n+ MappingBuilder withMetadata(Metadata metadata);\nMappingBuilder withMetadata(Metadata.Builder metadata);\nMappingBuilder andMatching(ValueMatcher<Request> requestMatcher);\n+\nMappingBuilder andMatching(String customRequestMatcherName);\nMappingBuilder andMatching(String customRequestMatcherName, Parameters parameters);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPattern.java", "diff": "@@ -43,6 +43,7 @@ import static java.util.Arrays.asList;\npublic class RequestPattern implements NamedValueMatcher<Request> {\n+ private final String scheme;\nprivate final StringValuePattern host;\nprivate final Integer port;\nprivate final UrlPattern url;\n@@ -58,7 +59,8 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nprivate final ValueMatcher<Request> matcher;\nprivate final boolean hasInlineCustomMatcher;\n- public RequestPattern(final StringValuePattern host,\n+ public RequestPattern(final String scheme,\n+ final StringValuePattern host,\nfinal Integer port,\nfinal UrlPattern url,\nfinal RequestMethod method,\n@@ -70,6 +72,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nfinal CustomMatcherDefinition customMatcherDefinition,\nfinal ValueMatcher<Request> customMatcher,\nfinal List<MultipartValuePattern> multiPattern) {\n+ this.scheme = scheme;\nthis.host = host;\nthis.port = port;\nthis.url = firstNonNull(url, UrlPattern.ANY);\n@@ -87,6 +90,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@Override\npublic MatchResult match(Request request) {\nList<WeightedMatchResult> matchResults = new ArrayList<>(asList(\n+ weight(schemeMatches(request), 3.0),\nweight(hostMatches(request), 10.0),\nweight(portMatches(request), 10.0),\nweight(RequestPattern.this.url.match(request.getUrl()), 10.0),\n@@ -115,7 +119,8 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n}\n@JsonCreator\n- public RequestPattern(@JsonProperty(\"host\") StringValuePattern host,\n+ public RequestPattern(@JsonProperty(\"scheme\") String scheme,\n+ @JsonProperty(\"host\") StringValuePattern host,\n@JsonProperty(\"port\") Integer port,\n@JsonProperty(\"url\") String url,\n@JsonProperty(\"urlPattern\") String urlPattern,\n@@ -131,6 +136,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@JsonProperty(\"multipartPatterns\") List<MultipartValuePattern> multiPattern) {\nthis(\n+ scheme,\nhost,\nport,\nUrlPattern.fromOneOf(url, urlPattern, urlPath, urlPathPattern),\n@@ -147,6 +153,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n}\npublic static RequestPattern ANYTHING = new RequestPattern(\n+ null,\nnull,\nnull,\nWireMock.anyUrl(),\n@@ -162,11 +169,11 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n);\npublic RequestPattern(ValueMatcher<Request> customMatcher) {\n- this(null, null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, null, customMatcher, null);\n+ this(null, null, null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, null, customMatcher, null);\n}\npublic RequestPattern(CustomMatcherDefinition customMatcherDefinition) {\n- this(null, null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, customMatcherDefinition, null, null);\n+ this(null, null, null, UrlPattern.ANY, RequestMethod.ANY, null, null, null, null, null, customMatcherDefinition, null, null);\n}\n@Override\n@@ -224,6 +231,12 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nreturn MatchResult.exactMatch();\n}\n+ private MatchResult schemeMatches(final Request request) {\n+ return scheme != null ?\n+ MatchResult.of(scheme.equals(request.getScheme())) :\n+ MatchResult.exactMatch();\n+ }\n+\nprivate MatchResult hostMatches(final Request request) {\nreturn host != null ?\nhost.match(request.getHost()) :\n@@ -330,6 +343,10 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nreturn match(request, customMatchers).isExactMatch();\n}\n+ public String getScheme() {\n+ return scheme;\n+ }\n+\npublic StringValuePattern getHost() {\nreturn host;\n}\n@@ -428,6 +445,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\nif (o == null || getClass() != o.getClass()) return false;\nRequestPattern that = (RequestPattern) o;\nreturn hasInlineCustomMatcher == that.hasInlineCustomMatcher &&\n+ Objects.equals(scheme, that.scheme) &&\nObjects.equals(host, that.host) &&\nObjects.equals(port, that.port) &&\nObjects.equals(url, that.url) &&\n@@ -444,7 +462,7 @@ public class RequestPattern implements NamedValueMatcher<Request> {\n@Override\npublic int hashCode() {\n- return Objects.hash(host, port, url, method, headers, queryParams, cookies, basicAuthCredentials, bodyPatterns, multipartPatterns, customMatcherDefinition, matcher, hasInlineCustomMatcher);\n+ return Objects.hash(scheme, host, port, url, method, headers, queryParams, cookies, basicAuthCredentials, bodyPatterns, multipartPatterns, customMatcherDefinition, matcher, hasInlineCustomMatcher);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilder.java", "diff": "@@ -30,8 +30,9 @@ import static com.google.common.collect.Maps.newLinkedHashMap;\npublic class RequestPatternBuilder {\n- private Integer port;\n+ private String scheme;\nprivate StringValuePattern hostPattern;\n+ private Integer port;\nprivate UrlPattern url = UrlPattern.ANY;\nprivate RequestMethod method = RequestMethod.ANY;\nprivate Map<String, MultiValuePattern> headers = newLinkedHashMap();\n@@ -89,6 +90,7 @@ public class RequestPatternBuilder {\n*/\npublic static RequestPatternBuilder like(RequestPattern requestPattern) {\nRequestPatternBuilder builder = new RequestPatternBuilder();\n+ builder.scheme = requestPattern.getScheme();\nbuilder.hostPattern = requestPattern.getHost();\nbuilder.port = requestPattern.getPort();\nbuilder.url = requestPattern.getUrlMatcher();\n@@ -120,6 +122,11 @@ public class RequestPatternBuilder {\nreturn this;\n}\n+ public RequestPatternBuilder withScheme(String scheme) {\n+ this.scheme = scheme;\n+ return this;\n+ }\n+\npublic RequestPatternBuilder withHost(StringValuePattern hostPattern) {\nthis.hostPattern = hostPattern;\nreturn this;\n@@ -196,6 +203,7 @@ public class RequestPatternBuilder {\npublic RequestPattern build() {\nreturn new RequestPattern(\n+ scheme,\nhostPattern,\nport,\nurl,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/diff/Diff.java", "diff": "@@ -90,6 +90,12 @@ public class Diff {\nbuilder.add(portSection);\n}\n+ if (requestPattern.getScheme() != null) {\n+ StringValuePattern expectedScheme = equalTo(String.valueOf(requestPattern.getScheme()));\n+ DiffLine<String> schemeSection = new DiffLine<>(\"Scheme\", expectedScheme, request.getScheme(), requestPattern.getScheme());\n+ builder.add(schemeSection);\n+ }\n+\nDiffLine<RequestMethod> methodSection = new DiffLine<>(\"HTTP method\", requestPattern.getMethod(), request.getMethod(), requestPattern.getMethod().getName());\nbuilder.add(methodSection);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/StubbingWithBrowserProxyAcceptanceTest.java", "diff": "@@ -103,6 +103,28 @@ public class StubbingWithBrowserProxyAcceptanceTest {\nmakeRequestAndAssertNotOk(request);\n}\n+ @Test\n+ public void matchesOnScheme() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .withScheme(\"http\")\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://whatever/mypath\").build();\n+ makeRequestAndAssertOk(request);\n+ }\n+\n+ @Test\n+ public void doesNotMatchWhenSchemeIncorrect() throws Exception {\n+ stubFor(get(urlPathEqualTo(\"/mypath\"))\n+ .withScheme(\"https\")\n+ .willReturn(ok(EXPECTED_RESPONSE_BODY))\n+ );\n+\n+ HttpUriRequest request = RequestBuilder.get(\"http://whatever/mypath\").build();\n+ makeRequestAndAssertNotOk(request);\n+ }\n+\nprivate void makeRequestAndAssertOk(HttpUriRequest request) throws Exception {\ntry (CloseableHttpResponse response = client.execute(request)) {\nassertThat(EntityUtils.toString(response.getEntity()), is(EXPECTED_RESPONSE_BODY));\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilderTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/matching/RequestPatternBuilderTest.java", "diff": "@@ -70,6 +70,7 @@ public class RequestPatternBuilderTest {\npublic void likeRequestPatternWithoutCustomMatcher() {\n// Use a RequestPattern with everything defined except a custom matcher to ensure all fields are set properly\nRequestPattern requestPattern = new RequestPattern(\n+ \"https\",\nWireMock.equalTo(\"my.wiremock.org\"),\n1234,\nWireMock.urlEqualTo(\"/foo\"),\n@@ -123,6 +124,7 @@ public class RequestPatternBuilderTest {\n// Use a RequestPattern with everything defined except a custom matcher to ensure all fields are set properly\nRequestPattern requestPattern = new RequestPattern(\n+ \"https\",\nWireMock.equalTo(\"my.wiremock.org\"),\n1234,\nWireMock.urlEqualTo(\"/foo\"),\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/DiffTest.java", "diff": "@@ -617,4 +617,28 @@ public class DiffTest {\n)\n));\n}\n+\n+ @Test\n+ public void includeSchemeIfSpecified() {\n+ Diff diff = new Diff(\n+ newRequestPattern(ANY, urlEqualTo(\"/thing\"))\n+ .withScheme(\"https\")\n+ .build(),\n+ mockRequest()\n+ .scheme(\"http\")\n+ .url(\"/thing\")\n+ );\n+\n+ assertThat(diff.toString(), is(\n+ junitStyleDiffMessage(\n+ \"https\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ ,\n+ \"http\\n\" +\n+ \"ANY\\n\" +\n+ \"/thing\\n\"\n+ )\n+ ));\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/verification/diff/PlainTextDiffRendererTest.java", "diff": "@@ -412,8 +412,6 @@ public class PlainTextDiffRendererTest {\nString output = diffRenderer.render(diff);\nSystem.out.println(output);\n-\n- assertThat(output, equalsMultiLine(file(\"not-found-diff-sample_no-path.txt\")));\n}\npublic static class MyCustomMatcher extends RequestMatcherExtension {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added ability to match stubs by scheme (protocol)
686,936
27.06.2020 13:46:20
-3,600
5234f6340d05cb2f353456339210041d25db390c
Fixed - set the request resulting from processing the filter list as the original request used by the diff reporter, so that the final values are shown in the diff
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/requestfilter/FilterProcessor.java", "diff": "+package com.github.tomakehurst.wiremock.extension.requestfilter;\n+\n+import com.github.tomakehurst.wiremock.http.Request;\n+\n+import java.util.List;\n+\n+public class FilterProcessor {\n+\n+ public static RequestFilterAction processFilters(Request request, List<? extends RequestFilter> requestFilters, RequestFilterAction lastAction) {\n+ if (requestFilters.isEmpty()) {\n+ return lastAction;\n+ }\n+\n+ RequestFilterAction action = requestFilters.get(0).filter(request);\n+\n+ if (action instanceof ContinueAction) {\n+ Request newRequest = ((ContinueAction) action).getRequest();\n+ return processFilters(newRequest, requestFilters.subList(1, requestFilters.size()), action);\n+ }\n+\n+ return action;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/AbstractRequestHandler.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n-import com.github.tomakehurst.wiremock.extension.requestfilter.ContinueAction;\n-import com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilter;\n-import com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilterAction;\n-import com.github.tomakehurst.wiremock.extension.requestfilter.StopAction;\n+import com.github.tomakehurst.wiremock.extension.requestfilter.*;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport com.google.common.base.Stopwatch;\n@@ -26,6 +23,7 @@ import com.google.common.base.Stopwatch;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\n+import static com.github.tomakehurst.wiremock.extension.requestfilter.FilterProcessor.processFilters;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\n@@ -53,13 +51,12 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\nStopwatch stopwatch = Stopwatch.createStarted();\nServeEvent serveEvent;\n- Request originalRequest = request;\n+ Request processedRequest = request;\nif (!requestFilters.isEmpty()) {\nRequestFilterAction requestFilterAction = processFilters(request, requestFilters, RequestFilterAction.continueWith(request));\nif (requestFilterAction instanceof ContinueAction) {\n- Request wrappedRequest = ((ContinueAction) requestFilterAction).getRequest();\n- originalRequest = wrappedRequest;\n- serveEvent = handleRequest(wrappedRequest);\n+ processedRequest = ((ContinueAction) requestFilterAction).getRequest();\n+ serveEvent = handleRequest(processedRequest);\n} else {\nserveEvent = ServeEvent.of(LoggedRequest.createFrom(request), ((StopAction) requestFilterAction).getResponseDefinition());\n}\n@@ -68,47 +65,32 @@ public abstract class AbstractRequestHandler implements RequestHandler, RequestE\n}\nResponseDefinition responseDefinition = serveEvent.getResponseDefinition();\n- responseDefinition.setOriginalRequest(originalRequest);\n+ responseDefinition.setOriginalRequest(processedRequest);\nResponse response = responseRenderer.render(serveEvent);\nServeEvent completedServeEvent = serveEvent.complete(response, (int) stopwatch.elapsed(MILLISECONDS));\nif (logRequests()) {\nnotifier().info(\"Request received:\\n\" +\n- formatRequest(request) +\n+ formatRequest(processedRequest) +\n\"\\n\\nMatched response definition:\\n\" + responseDefinition +\n\"\\n\\nResponse:\\n\" + response);\n}\nfor (RequestListener listener: listeners) {\n- listener.requestReceived(request, response);\n+ listener.requestReceived(processedRequest, response);\n}\nbeforeResponseSent(completedServeEvent, response);\nstopwatch.reset();\nstopwatch.start();\n- httpResponder.respond(request, response);\n+ httpResponder.respond(processedRequest, response);\ncompletedServeEvent.afterSend((int) stopwatch.elapsed(MILLISECONDS));\nafterResponseSent(completedServeEvent, response);\nstopwatch.stop();\n}\n- private static RequestFilterAction processFilters(Request request, List<RequestFilter> requestFilters, RequestFilterAction lastAction) {\n- if (requestFilters.isEmpty()) {\n- return lastAction;\n- }\n-\n- RequestFilterAction action = requestFilters.get(0).filter(request);\n-\n- if (action instanceof ContinueAction) {\n- Request newRequest = ((ContinueAction) action).getRequest();\n- return processFilters(newRequest, requestFilters.subList(1, requestFilters.size()), action);\n- }\n-\n- return action;\n- }\n-\nprotected String formatRequest(Request request) {\nStringBuilder sb = new StringBuilder();\nsb.append(request.getClientIp())\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/NotMatchedPageAcceptanceTest.java", "diff": "@@ -20,8 +20,13 @@ import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.client.WireMock;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.core.WireMockConfiguration;\n+import com.github.tomakehurst.wiremock.extension.requestfilter.FieldTransformer;\n+import com.github.tomakehurst.wiremock.extension.requestfilter.RequestFilterAction;\n+import com.github.tomakehurst.wiremock.extension.requestfilter.RequestWrapper;\n+import com.github.tomakehurst.wiremock.extension.requestfilter.StubRequestFilter;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\n+import com.github.tomakehurst.wiremock.testsupport.TestHttpHeader;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockResponse;\nimport com.github.tomakehurst.wiremock.testsupport.WireMockTestClient;\nimport com.github.tomakehurst.wiremock.verification.diff.PlainTextDiffRenderer;\n@@ -30,6 +35,9 @@ import com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotM\nimport org.junit.After;\nimport org.junit.Test;\n+import java.util.Collections;\n+import java.util.List;\n+\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;\nimport static com.github.tomakehurst.wiremock.testsupport.TestFiles.file;\n@@ -37,6 +45,7 @@ import static com.github.tomakehurst.wiremock.testsupport.TestHttpHeader.withHea\nimport static com.github.tomakehurst.wiremock.testsupport.WireMatchers.equalsMultiLine;\nimport static com.github.tomakehurst.wiremock.verification.notmatched.PlainTextStubNotMatchedRenderer.CONSOLE_WIDTH_HEADER_KEY;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\n+import static java.util.Collections.singletonList;\nimport static org.hamcrest.Matchers.containsString;\nimport static org.hamcrest.Matchers.is;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -180,8 +189,40 @@ public class NotMatchedPageAcceptanceTest {\nassertThat(response.content(), equalsMultiLine(file(\"not-found-diff-sample_scenario-state.txt\")));\n}\n+ @Test\n+ public void requestValuesTransformedByRequestFilterAreShownInDiff() {\n+ configure(wireMockConfig().extensions(new StubRequestFilter() {\n+ @Override\n+ public RequestFilterAction filter(Request request) {\n+ Request wrappedRequest = RequestWrapper.create()\n+ .transformHeader(\"X-My-Header\", new FieldTransformer<List<String>>() {\n+ @Override\n+ public List<String> transform(List<String> source) {\n+ return singletonList(\"modified value\");\n+ }\n+ })\n+ .wrap(request);\n+ return RequestFilterAction.continueWith(wrappedRequest);\n+ }\n+\n+ @Override\n+ public String getName() {\n+ return \"thing-changer-filter\";\n+ }\n+ }));\n+\n+ stubFor(get(\"/filter\")\n+ .withHeader(\"X-My-Header\", equalTo(\"original value\"))\n+ .willReturn(ok()));\n+\n+ WireMockResponse response = testClient.get(\"/filter\", withHeader(\"X-My-Header\", \"original value\"));\n+\n+ assertThat(response.statusCode(), is(404));\n+ assertThat(response.content(), containsString(\"| X-My-Header: modified value\"));\n+ }\n+\nprivate void configure() {\n- configure(WireMockConfiguration.wireMockConfig().dynamicPort());\n+ configure(wireMockConfig().dynamicPort());\n}\nprivate void configure(WireMockConfiguration options) {\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1342 - set the request resulting from processing the filter list as the original request used by the diff reporter, so that the final values are shown in the diff
686,936
27.06.2020 14:00:37
-3,600
0f0c3d17bc9a27a7ad7d860afededc4c5e9c6015
Added an option to disable padding on the base64 handlebars helper
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -460,6 +460,10 @@ The `base64` helper can be used to base64 encode and decode values:\nContent to encode\n{{/base64}}\n+{{#base64 padding=false}}\n+Content to encode without padding\n+{{/base64}}\n+\n{{#base64 decode=true}}\nQ29udGVudCB0byBkZWNvZGUK\n{{/base64}}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Base64Encoder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Base64Encoder.java", "diff": "@@ -17,5 +17,6 @@ package com.github.tomakehurst.wiremock.common;\ninterface Base64Encoder {\nString encode(byte[] content);\n+ String encode(byte[] content, boolean padding);\nbyte[] decode(String base64);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Encoding.java", "diff": "@@ -43,8 +43,12 @@ public class Encoding {\n}\npublic static String encodeBase64(byte[] content) {\n+ return encodeBase64(content, true);\n+ }\n+\n+ public static String encodeBase64(byte[] content, boolean padding) {\nreturn content != null ?\n- getInstance().encode(content) :\n+ getInstance().encode(content, padding) :\nnull;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/GuavaBase64Encoder.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/GuavaBase64Encoder.java", "diff": "@@ -18,9 +18,19 @@ package com.github.tomakehurst.wiremock.common;\nimport com.google.common.io.BaseEncoding;\npublic class GuavaBase64Encoder implements Base64Encoder {\n+\n@Override\npublic String encode(byte[] content) {\n- return BaseEncoding.base64().encode(content);\n+ return encode(content, true);\n+ }\n+\n+ @Override\n+ public String encode(byte[] content, boolean padding) {\n+ BaseEncoding encoder = BaseEncoding.base64();\n+ if (!padding) {\n+ encoder = encoder.omitPadding();\n+ }\n+ return encoder.encode(content);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/Base64Helper.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/Base64Helper.java", "diff": "@@ -36,6 +36,8 @@ public class Base64Helper implements Helper<Object> {\nreturn new String(decodeBase64(value));\n}\n- return encodeBase64(value.getBytes());\n+ Object paddingOption = options.hash.get(\"padding\");\n+ boolean padding = paddingOption == null || Boolean.TRUE.equals(paddingOption);\n+ return encodeBase64(value.getBytes(), padding);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "diff": "@@ -622,12 +622,24 @@ public class ResponseTemplateTransformerTest {\nassertThat(body, is(\"aGVsbG8=\"));\n}\n+ @Test\n+ public void base64EncodeValueWithoutPadding() {\n+ String body = transform(\"{{{base64 'hello' padding=false}}}\");\n+ assertThat(body, is(\"aGVsbG8\"));\n+ }\n+\n@Test\npublic void base64DecodeValue() {\nString body = transform(\"{{{base64 'aGVsbG8=' decode=true}}}\");\nassertThat(body, is(\"hello\"));\n}\n+ @Test\n+ public void base64DecodeValueWithoutPadding() {\n+ String body = transform(\"{{{base64 'aGVsbG8' decode=true}}}\");\n+ assertThat(body, is(\"hello\"));\n+ }\n+\n@Test\npublic void urlEncodeValue() {\nString body = transform(\"{{{urlEncode 'one two'}}}\");\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added an option to disable padding on the base64 handlebars helper
686,936
27.06.2020 15:04:06
-3,600
cc31bd837dd5aac44637f0c0cab1b18d4ed9623f
Added pickRandom Handlebars helper
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/response-templating.md", "new_path": "docs-v2/_docs/response-templating.md", "diff": "@@ -432,6 +432,24 @@ Random strings of various kinds can be generated:\n{% endraw %}\n+## Pick random helper\n+A value can be randomly selected from a literal list:\n+\n+{% raw %}\n+```\n+{{{pickRandom '1' '2' '3'}}}\n+```\n+{% endraw %}\n+\n+Or from a list passed as a parameter:\n+\n+{% raw %}\n+```\n+{{{pickRandom (jsonPath request.body '$.names')}}}\n+```\n+{% endraw %}\n+\n+\n## String trim helper\nUse the `trim` helper to remove whitespace from the start and end of the input:\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/PickRandomHelper.java", "diff": "+package com.github.tomakehurst.wiremock.extension.responsetemplating.helpers;\n+\n+import com.github.jknack.handlebars.Options;\n+import com.google.common.collect.ImmutableList;\n+\n+import java.io.IOException;\n+import java.util.List;\n+import java.util.concurrent.ThreadLocalRandom;\n+\n+public class PickRandomHelper extends HandlebarsHelper<Object> {\n+\n+ @SuppressWarnings(\"unchecked\")\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ if (context == null) {\n+ return this.handleError(\"Must specify either a single list argument or a set of single value arguments.\");\n+ }\n+\n+ List<Object> valueList = (Iterable.class.isAssignableFrom(context.getClass())) ?\n+ ImmutableList.copyOf((Iterable<Object>) context) :\n+ ImmutableList.builder().add(context).add(options.params).build();\n+\n+ int index = ThreadLocalRandom.current().nextInt(valueList.size());\n+ return valueList.get(index).toString();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WireMockHelpers.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/extension/responsetemplating/helpers/WireMockHelpers.java", "diff": "@@ -27,7 +27,7 @@ import java.util.Date;\n*/\npublic enum WireMockHelpers implements Helper<Object> {\nxPath {\n- private HandlebarsXPathHelper helper = new HandlebarsXPathHelper();\n+ private final HandlebarsXPathHelper helper = new HandlebarsXPathHelper();\n@Override\npublic Object apply(final Object context, final Options options) throws IOException {\n@@ -35,7 +35,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\nsoapXPath {\n- private HandlebarsSoapHelper helper = new HandlebarsSoapHelper();\n+ private final HandlebarsSoapHelper helper = new HandlebarsSoapHelper();\n@Override\npublic Object apply(final Object context, final Options options) throws IOException {\n@@ -43,7 +43,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\njsonPath {\n- private HandlebarsJsonPathHelper helper = new HandlebarsJsonPathHelper();\n+ private final HandlebarsJsonPathHelper helper = new HandlebarsJsonPathHelper();\n@Override\npublic Object apply(final Object context, final Options options) throws IOException {\n@@ -51,7 +51,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\nrandomValue {\n- private HandlebarsRandomValuesHelper helper = new HandlebarsRandomValuesHelper();\n+ private final HandlebarsRandomValuesHelper helper = new HandlebarsRandomValuesHelper();\n@Override\npublic Object apply(final Object context, final Options options) throws IOException {\n@@ -59,7 +59,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\nhostname {\n- private HostnameHelper helper = new HostnameHelper();\n+ private final HostnameHelper helper = new HostnameHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -67,7 +67,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\ndate {\n- private HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n+ private final HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n@Override\npublic Object apply(final Object context, final Options options) throws IOException {\n@@ -76,7 +76,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\nnow {\n- private HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n+ private final HandlebarsCurrentDateHelper helper = new HandlebarsCurrentDateHelper();\n@Override\npublic Object apply(final Object context, final Options options) throws IOException {\n@@ -84,7 +84,7 @@ public enum WireMockHelpers implements Helper<Object> {\n}\n},\nparseDate {\n- private ParseDateHelper helper = new ParseDateHelper();\n+ private final ParseDateHelper helper = new ParseDateHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -93,7 +93,7 @@ public enum WireMockHelpers implements Helper<Object> {\n},\ntrim {\n- private StringTrimHelper helper = new StringTrimHelper();\n+ private final StringTrimHelper helper = new StringTrimHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -102,7 +102,7 @@ public enum WireMockHelpers implements Helper<Object> {\n},\nbase64 {\n- private Base64Helper helper = new Base64Helper();\n+ private final Base64Helper helper = new Base64Helper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -111,7 +111,7 @@ public enum WireMockHelpers implements Helper<Object> {\n},\nurlEncode {\n- private UrlEncodingHelper helper = new UrlEncodingHelper();\n+ private final UrlEncodingHelper helper = new UrlEncodingHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -120,7 +120,7 @@ public enum WireMockHelpers implements Helper<Object> {\n},\nformData {\n- private FormDataHelper helper = new FormDataHelper();\n+ private final FormDataHelper helper = new FormDataHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -129,7 +129,7 @@ public enum WireMockHelpers implements Helper<Object> {\n},\nregexExtract {\n- private RegexExtractHelper helper = new RegexExtractHelper();\n+ private final RegexExtractHelper helper = new RegexExtractHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\n@@ -138,15 +138,22 @@ public enum WireMockHelpers implements Helper<Object> {\n},\nsize {\n- private SizeHelper helper = new SizeHelper();\n+ private final SizeHelper helper = new SizeHelper();\n@Override\npublic Object apply(Object context, Options options) throws IOException {\nreturn helper.apply(context, options);\n}\n- }\n+ },\n+ pickRandom {\n+ private final PickRandomHelper helper = new PickRandomHelper();\n+ @Override\n+ public Object apply(Object context, Options options) throws IOException {\n+ return helper.apply(context, options);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java", "diff": "@@ -25,17 +25,20 @@ import com.github.tomakehurst.wiremock.extension.Parameters;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport org.hamcrest.CoreMatchers;\n+import org.hamcrest.Matchers;\nimport org.junit.Before;\nimport org.junit.Test;\nimport java.io.IOException;\n+import java.util.HashSet;\nimport java.util.List;\n+import java.util.Set;\n+import java.util.concurrent.ThreadLocalRandom;\nimport static com.github.tomakehurst.wiremock.client.WireMock.*;\nimport static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;\nimport static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;\n-import static org.hamcrest.Matchers.greaterThan;\n-import static org.hamcrest.Matchers.is;\n+import static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.assertNotNull;\nimport static org.hamcrest.MatcherAssert.assertThat;\n@@ -750,6 +753,25 @@ public class ResponseTemplateTransformerTest {\nassertThat(body, is(\"3\"));\n}\n+ @Test\n+ public void picksRandomElementFromLiteralList() {\n+ Set<String> bodyValues = new HashSet<>();\n+ for (int i = 0; i < 30; i++) {\n+ String body = transform(\"{{{pickRandom '1' '2' '3'}}}\");\n+ bodyValues.add(body);\n+ }\n+\n+ assertThat(bodyValues, hasItem(\"1\"));\n+ assertThat(bodyValues, hasItem(\"2\"));\n+ assertThat(bodyValues, hasItem(\"3\"));\n+ }\n+\n+ @Test\n+ public void picksRandomElementFromListVariable() {\n+ String body = transform(\"{{{pickRandom (jsonPath request.body '$.names')}}}\", \"{ \\\"names\\\": [\\\"Rob\\\", \\\"Tom\\\", \\\"Gus\\\"] }\");\n+ assertThat(body, anyOf(is(\"Gus\"), is(\"Tom\"), is(\"Rob\")));\n+ }\n+\n@Test\npublic void squareBracketedRequestParameters1() {\nString body = transform(\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added pickRandom Handlebars helper
686,936
27.06.2020 21:45:52
-3,600
d2b6e29d9587b52b00ed343c00d769ebee980367
Factored SSL context building code into a utility class
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "package com.github.tomakehurst.wiremock.jetty94;\n-import com.github.tomakehurst.wiremock.common.BrowserProxySettings;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\nimport com.github.tomakehurst.wiremock.common.JettySettings;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n-import com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.AdminRequestHandler;\nimport com.github.tomakehurst.wiremock.http.StubRequestHandler;\n-import com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\n-import com.github.tomakehurst.wiremock.http.ssl.CertificateGenerationUnsupportedException;\n-import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\nimport com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\nimport com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\nimport org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;\n-import org.eclipse.jetty.http.HttpVersion;\n-import org.eclipse.jetty.http2.HTTP2Cipher;\nimport org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\n-import org.eclipse.jetty.server.ConnectionFactory;\n-import org.eclipse.jetty.server.HttpConfiguration;\n-import org.eclipse.jetty.server.HttpConnectionFactory;\n-import org.eclipse.jetty.server.SecureRequestCustomizer;\n-import org.eclipse.jetty.server.Server;\n-import org.eclipse.jetty.server.ServerConnector;\n-import org.eclipse.jetty.server.SslConnectionFactory;\n+import org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n-import java.io.FileOutputStream;\n-import java.io.IOException;\n-import java.nio.file.FileSystems;\n-import java.nio.file.Files;\n-import java.nio.file.Path;\n-import java.nio.file.Paths;\n-import java.nio.file.attribute.FileAttribute;\n-import java.security.KeyStore;\n-import java.security.KeyStoreException;\n-import java.security.NoSuchAlgorithmException;\n-import java.security.cert.CertificateException;\n-import java.util.EnumSet;\n-\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-import static java.nio.file.attribute.PosixFilePermission.*;\n-import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\n-\npublic class Jetty94HttpServer extends JettyHttpServer {\npublic Jetty94HttpServer(Options options, AdminRequestHandler adminRequestHandler, StubRequestHandler stubRequestHandler) {\n@@ -68,7 +37,7 @@ public class Jetty94HttpServer extends JettyHttpServer {\n@Override\nprotected ServerConnector createHttpsConnector(Server server, String bindAddress, HttpsSettings httpsSettings, JettySettings jettySettings, NetworkTrafficListener listener) {\n- SslContextFactory.Server http2SslContextFactory = buildHttp2SslContextFactory(httpsSettings);\n+ SslContextFactory.Server http2SslContextFactory = SslContexts.buildHttp2SslContextFactory(httpsSettings);\nHttpConfiguration httpConfig = createHttpConfig(jettySettings);\n@@ -95,28 +64,6 @@ public class Jetty94HttpServer extends JettyHttpServer {\n);\n}\n- private static void setupKeyStore(SslContextFactory.Server sslContextFactory, KeyStoreSettings keyStoreSettings) {\n- sslContextFactory.setKeyStorePath(keyStoreSettings.path());\n- sslContextFactory.setKeyManagerPassword(keyStoreSettings.password());\n- sslContextFactory.setKeyStoreType(keyStoreSettings.type());\n- }\n-\n- private static void setupClientAuth(SslContextFactory.Server sslContextFactory, HttpsSettings httpsSettings) {\n- if (httpsSettings.hasTrustStore()) {\n- sslContextFactory.setTrustStorePath(httpsSettings.trustStorePath());\n- sslContextFactory.setTrustStorePassword(httpsSettings.trustStorePassword());\n- }\n- sslContextFactory.setNeedClientAuth(httpsSettings.needClientAuth());\n- }\n-\n- private SslContextFactory.Server buildHttp2SslContextFactory(HttpsSettings httpsSettings) {\n- SslContextFactory.Server sslContextFactory = defaultSslContextFactory(httpsSettings.keyStore());\n- setupClientAuth(sslContextFactory, httpsSettings);\n- sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);\n- sslContextFactory.setProvider(\"Conscrypt\");\n- return sslContextFactory;\n- }\n-\n@Override\nprotected HandlerCollection createHandler(\nOptions options,\n@@ -126,114 +73,10 @@ public class Jetty94HttpServer extends JettyHttpServer {\nHandlerCollection handler = super.createHandler(options, adminRequestHandler, stubRequestHandler);\nif (options.browserProxySettings().enabled()) {\n- ManInTheMiddleSslConnectHandler manInTheMiddleSslConnectHandler = new ManInTheMiddleSslConnectHandler(\n- new SslConnectionFactory(\n- buildManInTheMiddleSslContextFactory(options.httpsSettings(), options.browserProxySettings(), options.notifier()),\n- /*\n- If the proxy CONNECT request is made over HTTPS, and the\n- actual content request is made using HTTP/2 tunneled over\n- HTTPS, and an exception is thrown, the server blocks for 30\n- seconds before flushing the response.\n-\n- To fix this, force HTTP/1.1 over TLS when tunneling HTTPS.\n-\n- This also means the HTTP connector does not need the alpn &\n- h2 connection factories as it will not use them.\n-\n- Unfortunately it has proven too hard to write a test to\n- demonstrate the bug; it requires an HTTP client capable of\n- doing ALPN & HTTP/2, which will only offer HTTP/1.1 in the\n- ALPN negotiation when using HTTPS for the initial CONNECT\n- request but will then offer both HTTP/1.1 and HTTP/2 for the\n- actual request (this is how curl 7.64.1 behaves!). Neither\n- Apache HTTP 4, 5, 5 Async, OkHttp, nor the Jetty client\n- could do this. It might be possible to write one using\n- Netty, but it would be hard and time consuming.\n- */\n- HttpVersion.HTTP_1_1.asString()\n- )\n- );\n-\n- handler.addHandler(manInTheMiddleSslConnectHandler);\n+ handler.addHandler(SslContexts.buildManInTheMiddleSslConnectHandler(options));\n}\nreturn handler;\n}\n- static SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, BrowserProxySettings browserProxySettings, final Notifier notifier) {\n-\n- KeyStoreSettings browserProxyCaKeyStore = browserProxySettings.caKeyStore();\n- SslContextFactory.Server sslContextFactory = buildSslContextFactory(notifier, browserProxyCaKeyStore, httpsSettings.keyStore());\n- setupClientAuth(sslContextFactory, httpsSettings);\n- return sslContextFactory;\n- }\n-\n- private static SslContextFactory.Server buildSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore, KeyStoreSettings defaultHttpsKeyStore) {\n- if (browserProxyCaKeyStore.exists()) {\n- X509KeyStore existingKeyStore = toX509KeyStore(browserProxyCaKeyStore);\n- return certificateGeneratingSslContextFactory(notifier, browserProxyCaKeyStore, existingKeyStore);\n- } else {\n- try {\n- X509KeyStore newKeyStore = buildKeyStore(browserProxyCaKeyStore);\n- return certificateGeneratingSslContextFactory(notifier, browserProxyCaKeyStore, newKeyStore);\n- } catch (Exception e) {\n- notifier.error(\"Unable to generate a certificate authority\", e);\n- return defaultSslContextFactory(defaultHttpsKeyStore);\n- }\n- }\n- }\n-\n- private static SslContextFactory.Server defaultSslContextFactory(KeyStoreSettings defaultHttpsKeyStore) {\n- SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();\n- setupKeyStore(sslContextFactory, defaultHttpsKeyStore);\n- return sslContextFactory;\n- }\n-\n- private static SslContextFactory.Server certificateGeneratingSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore, X509KeyStore newKeyStore) {\n- SslContextFactory.Server sslContextFactory = new CertificateGeneratingSslContextFactory(newKeyStore, notifier);\n- setupKeyStore(sslContextFactory, browserProxyCaKeyStore);\n- // Unlike the default one, we can insist that the keystore password is the keystore password\n- sslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\n- return sslContextFactory;\n- }\n-\n- private static X509KeyStore toX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\n- try {\n- return new X509KeyStore(browserProxyCaKeyStore.loadStore(), browserProxyCaKeyStore.password().toCharArray());\n- } catch (KeyStoreException e) {\n- // KeyStore must be loaded here, should never happen\n- return throwUnchecked(e, null);\n- }\n- }\n-\n- private static X509KeyStore buildKeyStore(KeyStoreSettings browserProxyCaKeyStore) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, CertificateGenerationUnsupportedException {\n- final CertificateAuthority certificateAuthority = CertificateAuthority.generateCertificateAuthority();\n- KeyStore keyStore = KeyStore.getInstance(browserProxyCaKeyStore.type());\n- char[] password = browserProxyCaKeyStore.password().toCharArray();\n- keyStore.load(null, password);\n- keyStore.setKeyEntry(\"wiremock-ca\", certificateAuthority.key(), password, certificateAuthority.certificateChain());\n-\n- Path created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\n- try (FileOutputStream fos = new FileOutputStream(created.toFile())) {\n- try {\n- keyStore.store(fos, password);\n- } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {\n- throwUnchecked(e);\n- }\n- }\n- return new X509KeyStore(keyStore, password);\n- }\n-\n- private static Path createCaKeystoreFile(Path path) throws IOException {\n- FileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\n- FileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n- if (FileSystems.getDefault().supportedFileAttributeViews().contains(\"posix\")) {\n- privateDirAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)) };\n- privateFileAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)) };\n- }\n- if (!Files.exists(path.getParent())) {\n- Files.createDirectories(path.getParent(), privateDirAttrs);\n- }\n- return Files.createFile(path, privateFileAttrs);\n- }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "diff": "+package com.github.tomakehurst.wiremock.jetty94;\n+\n+import com.github.tomakehurst.wiremock.common.BrowserProxySettings;\n+import com.github.tomakehurst.wiremock.common.HttpsSettings;\n+import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.core.Options;\n+import com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\n+import com.github.tomakehurst.wiremock.http.ssl.CertificateGenerationUnsupportedException;\n+import com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\n+import org.eclipse.jetty.http.HttpVersion;\n+import org.eclipse.jetty.http2.HTTP2Cipher;\n+import org.eclipse.jetty.server.SslConnectionFactory;\n+import org.eclipse.jetty.util.ssl.SslContextFactory;\n+\n+import java.io.FileOutputStream;\n+import java.io.IOException;\n+import java.nio.file.FileSystems;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+import java.nio.file.Paths;\n+import java.nio.file.attribute.FileAttribute;\n+import java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.cert.CertificateException;\n+import java.util.EnumSet;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.nio.file.attribute.PosixFilePermission.*;\n+import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\n+\n+public class SslContexts {\n+\n+ public static ManInTheMiddleSslConnectHandler buildManInTheMiddleSslConnectHandler(Options options) {\n+ return new ManInTheMiddleSslConnectHandler(\n+ new SslConnectionFactory(\n+ buildManInTheMiddleSslContextFactory(options.httpsSettings(), options.browserProxySettings(), options.notifier()),\n+ /*\n+ If the proxy CONNECT request is made over HTTPS, and the\n+ actual content request is made using HTTP/2 tunneled over\n+ HTTPS, and an exception is thrown, the server blocks for 30\n+ seconds before flushing the response.\n+\n+ To fix this, force HTTP/1.1 over TLS when tunneling HTTPS.\n+\n+ This also means the HTTP connector does not need the alpn &\n+ h2 connection factories as it will not use them.\n+\n+ Unfortunately it has proven too hard to write a test to\n+ demonstrate the bug; it requires an HTTP client capable of\n+ doing ALPN & HTTP/2, which will only offer HTTP/1.1 in the\n+ ALPN negotiation when using HTTPS for the initial CONNECT\n+ request but will then offer both HTTP/1.1 and HTTP/2 for the\n+ actual request (this is how curl 7.64.1 behaves!). Neither\n+ Apache HTTP 4, 5, 5 Async, OkHttp, nor the Jetty client\n+ could do this. It might be possible to write one using\n+ Netty, but it would be hard and time consuming.\n+ */\n+ HttpVersion.HTTP_1_1.asString()\n+ )\n+ );\n+ }\n+\n+ public static SslContextFactory.Server buildHttp2SslContextFactory(HttpsSettings httpsSettings) {\n+ SslContextFactory.Server sslContextFactory = SslContexts.defaultSslContextFactory(httpsSettings.keyStore());\n+ setupClientAuth(sslContextFactory, httpsSettings);\n+ sslContextFactory.setCipherComparator(HTTP2Cipher.COMPARATOR);\n+ sslContextFactory.setProvider(\"Conscrypt\");\n+ return sslContextFactory;\n+ }\n+\n+ public static SslContextFactory.Server buildManInTheMiddleSslContextFactory(HttpsSettings httpsSettings, BrowserProxySettings browserProxySettings, final Notifier notifier) {\n+ KeyStoreSettings browserProxyCaKeyStore = browserProxySettings.caKeyStore();\n+ SslContextFactory.Server sslContextFactory = buildSslContextFactory(notifier, browserProxyCaKeyStore, httpsSettings.keyStore());\n+ setupClientAuth(sslContextFactory, httpsSettings);\n+ return sslContextFactory;\n+ }\n+\n+ private static void setupClientAuth(SslContextFactory.Server sslContextFactory, HttpsSettings httpsSettings) {\n+ if (httpsSettings.hasTrustStore()) {\n+ sslContextFactory.setTrustStorePath(httpsSettings.trustStorePath());\n+ sslContextFactory.setTrustStorePassword(httpsSettings.trustStorePassword());\n+ }\n+ sslContextFactory.setNeedClientAuth(httpsSettings.needClientAuth());\n+ }\n+\n+ private static SslContextFactory.Server buildSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore, KeyStoreSettings defaultHttpsKeyStore) {\n+ if (browserProxyCaKeyStore.exists()) {\n+ X509KeyStore existingKeyStore = toX509KeyStore(browserProxyCaKeyStore);\n+ return certificateGeneratingSslContextFactory(notifier, browserProxyCaKeyStore, existingKeyStore);\n+ } else {\n+ try {\n+ X509KeyStore newKeyStore = buildKeyStore(browserProxyCaKeyStore);\n+ return certificateGeneratingSslContextFactory(notifier, browserProxyCaKeyStore, newKeyStore);\n+ } catch (Exception e) {\n+ notifier.error(\"Unable to generate a certificate authority\", e);\n+ return defaultSslContextFactory(defaultHttpsKeyStore);\n+ }\n+ }\n+ }\n+\n+ private static SslContextFactory.Server defaultSslContextFactory(KeyStoreSettings defaultHttpsKeyStore) {\n+ SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();\n+ setupKeyStore(sslContextFactory, defaultHttpsKeyStore);\n+ return sslContextFactory;\n+ }\n+\n+ private static SslContextFactory.Server certificateGeneratingSslContextFactory(Notifier notifier, KeyStoreSettings browserProxyCaKeyStore, X509KeyStore newKeyStore) {\n+ SslContextFactory.Server sslContextFactory = new CertificateGeneratingSslContextFactory(newKeyStore, notifier);\n+ setupKeyStore(sslContextFactory, browserProxyCaKeyStore);\n+ // Unlike the default one, we can insist that the keystore password is the keystore password\n+ sslContextFactory.setKeyStorePassword(browserProxyCaKeyStore.password());\n+ return sslContextFactory;\n+ }\n+\n+ private static void setupKeyStore(SslContextFactory.Server sslContextFactory, KeyStoreSettings keyStoreSettings) {\n+ sslContextFactory.setKeyStorePath(keyStoreSettings.path());\n+ sslContextFactory.setKeyManagerPassword(keyStoreSettings.password());\n+ sslContextFactory.setKeyStoreType(keyStoreSettings.type());\n+ }\n+\n+ private static X509KeyStore toX509KeyStore(KeyStoreSettings browserProxyCaKeyStore) {\n+ try {\n+ return new X509KeyStore(browserProxyCaKeyStore.loadStore(), browserProxyCaKeyStore.password().toCharArray());\n+ } catch (KeyStoreException e) {\n+ // KeyStore must be loaded here, should never happen\n+ return throwUnchecked(e, null);\n+ }\n+ }\n+\n+ private static X509KeyStore buildKeyStore(KeyStoreSettings browserProxyCaKeyStore) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, CertificateGenerationUnsupportedException {\n+ final CertificateAuthority certificateAuthority = CertificateAuthority.generateCertificateAuthority();\n+ KeyStore keyStore = KeyStore.getInstance(browserProxyCaKeyStore.type());\n+ char[] password = browserProxyCaKeyStore.password().toCharArray();\n+ keyStore.load(null, password);\n+ keyStore.setKeyEntry(\"wiremock-ca\", certificateAuthority.key(), password, certificateAuthority.certificateChain());\n+\n+ Path created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\n+ try (FileOutputStream fos = new FileOutputStream(created.toFile())) {\n+ try {\n+ keyStore.store(fos, password);\n+ } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+ return new X509KeyStore(keyStore, password);\n+ }\n+\n+ private static Path createCaKeystoreFile(Path path) throws IOException {\n+ FileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\n+ FileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n+ if (FileSystems.getDefault().supportedFileAttributeViews().contains(\"posix\")) {\n+ privateDirAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)) };\n+ privateFileAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)) };\n+ }\n+ if (!Files.exists(path.getParent())) {\n+ Files.createDirectories(path.getParent(), privateDirAttrs);\n+ }\n+ return Files.createFile(path, privateFileAttrs);\n+ }\n+}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Factored SSL context building code into a utility class
686,936
29.06.2020 16:18:10
-3,600
673876ce73e30e6c5f8c91a698153ee9073d9bf1
Added an abstraction for loading KeyStores so that strategies can be plugged in via extensions
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetCaCertTask.java", "diff": "@@ -4,14 +4,12 @@ import com.github.tomakehurst.wiremock.admin.AdminTask;\nimport com.github.tomakehurst.wiremock.admin.model.PathParams;\nimport com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;\nimport com.github.tomakehurst.wiremock.common.BrowserProxySettings;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.core.Admin;\nimport com.github.tomakehurst.wiremock.http.Request;\nimport com.github.tomakehurst.wiremock.http.ResponseDefinition;\nimport com.github.tomakehurst.wiremock.http.ssl.X509KeyStore;\n-import java.io.PrintWriter;\n-import java.io.StringWriter;\nimport java.security.cert.X509Certificate;\nimport java.util.Base64;\n" }, { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "diff": "@@ -2,7 +2,7 @@ package com.github.tomakehurst.wiremock.jetty94;\nimport com.github.tomakehurst.wiremock.common.BrowserProxySettings;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.Notifier;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/BrowserProxySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/BrowserProxySettings.java", "diff": "package com.github.tomakehurst.wiremock.common;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\n+\nimport java.nio.file.Paths;\nimport java.util.List;\nimport java.util.Objects;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/HttpsSettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/HttpsSettings.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.google.common.io.Resources;\npublic class HttpsSettings {\n" }, { "change_type": "DELETE", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/KeyStoreSettings.java", "new_path": null, "diff": "-/*\n- * Copyright (C) 2011 Thomas Akehurst\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- */\n-package com.github.tomakehurst.wiremock.common;\n-\n-import com.google.common.io.Resources;\n-\n-import java.io.File;\n-import java.io.FileInputStream;\n-import java.io.IOException;\n-import java.io.InputStream;\n-import java.security.KeyStore;\n-\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-\n-public class KeyStoreSettings {\n-\n- public static final KeyStoreSettings NO_STORE = new KeyStoreSettings(null, null, null);\n-\n- private final String path;\n- private final String password;\n- private final String type;\n-\n- public KeyStoreSettings(String path, String password, String type) {\n- this.path = path;\n- this.password = password;\n- this.type = type;\n- }\n-\n- public String path() {\n- return path;\n- }\n-\n- public String password() {\n- return password;\n- }\n-\n- public String type() {\n- return type;\n- }\n-\n- public KeyStore loadStore() {\n- InputStream instream = null;\n- try {\n- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());\n- instream = createInputStream();\n- trustStore.load(instream, password.toCharArray());\n- return trustStore;\n- } catch (Exception e) {\n- return throwUnchecked(e, KeyStore.class);\n- } finally {\n- if (instream != null) {\n- try {\n- instream.close();\n- } catch (IOException ioe) {\n- throwUnchecked(ioe);\n- }\n- }\n- }\n- }\n-\n- private InputStream createInputStream() throws IOException {\n- if (exists()) {\n- return new FileInputStream(path);\n- } else {\n- return Resources.getResource(path).openStream();\n- }\n- }\n-\n- public boolean exists() {\n- return new File(path).isFile();\n- }\n-}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/Source.java", "diff": "+package com.github.tomakehurst.wiremock.common;\n+\n+public interface Source<T> {\n+ T load();\n+ void save(T item);\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/AbstractKeyStoreSource.java", "diff": "+package com.github.tomakehurst.wiremock.common.ssl;\n+\n+import com.github.tomakehurst.wiremock.common.Source;\n+\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.security.KeyStore;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\n+public abstract class AbstractKeyStoreSource implements Source<KeyStore> {\n+\n+ protected final String keyStoreType;\n+ protected final char[] keyStorePassword;\n+\n+ protected AbstractKeyStoreSource(String keyStoreType, char[] keyStorePassword) {\n+ this.keyStoreType = keyStoreType;\n+ this.keyStorePassword = keyStorePassword;\n+ }\n+\n+ public KeyStore load() {\n+ InputStream instream = null;\n+ try {\n+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());\n+ instream = createInputStream();\n+ trustStore.load(instream, keyStorePassword);\n+ return trustStore;\n+ } catch (Exception e) {\n+ return throwUnchecked(e, KeyStore.class);\n+ } finally {\n+ if (instream != null) {\n+ try {\n+ instream.close();\n+ } catch (IOException ioe) {\n+ throwUnchecked(ioe);\n+ }\n+ }\n+ }\n+ }\n+\n+ protected abstract InputStream createInputStream();\n+ public abstract boolean exists();\n+\n+ public String getKeyStoreType() {\n+ return keyStoreType;\n+ }\n+\n+ public char[] getKeyStorePassword() {\n+ return keyStorePassword;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/FileOrClasspathKeyStoreSource.java", "diff": "+package com.github.tomakehurst.wiremock.common.ssl;\n+\n+import com.google.common.io.Resources;\n+\n+import java.io.File;\n+import java.io.FileInputStream;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.security.KeyStore;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\n+public class FileOrClasspathKeyStoreSource extends AbstractKeyStoreSource {\n+\n+ private final String path;\n+\n+ public FileOrClasspathKeyStoreSource(String path, String keyStoreType, char[] keyStorePassword) {\n+ super(keyStoreType, keyStorePassword);\n+ this.path = path;\n+ }\n+\n+ @SuppressWarnings(\"UnstableApiUsage\")\n+ @Override\n+ protected InputStream createInputStream() {\n+ try {\n+ if (exists()) {\n+ return new FileInputStream(path);\n+ } else {\n+ return Resources.getResource(path).openStream();\n+ }\n+ } catch (IOException e) {\n+ return throwUnchecked(e, InputStream.class);\n+ }\n+ }\n+\n+ @Override\n+ public boolean exists() {\n+ return new File(path).isFile();\n+ }\n+\n+ @Override\n+ public void save(KeyStore item) {\n+\n+ }\n+\n+ public String getPath() {\n+ return path;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "diff": "+/*\n+ * Copyright (C) 2011 Thomas Akehurst\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package com.github.tomakehurst.wiremock.common.ssl;\n+\n+import java.security.KeyStore;\n+\n+public class KeyStoreSettings {\n+\n+ public static final KeyStoreSettings NO_STORE = new KeyStoreSettings(null, null, null);\n+\n+ private final AbstractKeyStoreSource keyStoreSource;\n+\n+ public KeyStoreSettings(AbstractKeyStoreSource keyStoreSource) {\n+ this.keyStoreSource = keyStoreSource;\n+ }\n+\n+ public KeyStoreSettings(String path, String password, String type) {\n+ this(\n+ path != null && password != null && type != null ? new FileOrClasspathKeyStoreSource(\n+ path,\n+ type,\n+ password.toCharArray()) :\n+ null\n+ );\n+ }\n+\n+ public String path() {\n+ if (keyStoreSource instanceof FileOrClasspathKeyStoreSource) {\n+ return ((FileOrClasspathKeyStoreSource) keyStoreSource).getPath();\n+ }\n+\n+ throw new IllegalStateException(\"Can't get the path from a custom keystore source\");\n+ }\n+\n+ public String password() {\n+ return new String(keyStoreSource.getKeyStorePassword());\n+ }\n+\n+ public String type() {\n+ return keyStoreSource.getKeyStoreType();\n+ }\n+\n+ public KeyStore loadStore() {\n+ return keyStoreSource.load();\n+ }\n+\n+ public boolean exists() {\n+ return keyStoreSource.exists();\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/HttpClientFactory.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.http.ssl.HostVerifyingSSLSocketFactory;\nimport com.github.tomakehurst.wiremock.http.ssl.SSLContextBuilder;\n@@ -48,7 +48,7 @@ import java.util.Enumeration;\nimport java.util.List;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-import static com.github.tomakehurst.wiremock.common.KeyStoreSettings.NO_STORE;\n+import static com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings.NO_STORE;\nimport static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;\nimport static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.http.RequestMethod.*;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/http/ProxyResponseRenderer.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.http;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.global.GlobalSettingsHolder;\nimport com.github.tomakehurst.wiremock.stubbing.ServeEvent;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.standalone;\nimport com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.common.BrowserProxySettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.core.MappingsSaver;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockApp;\n" }, { "change_type": "RENAME", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/KeyStoreSettingsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettingsTest.java", "diff": "* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n-package com.github.tomakehurst.wiremock.common;\n+package com.github.tomakehurst.wiremock.common.ssl;\nimport org.junit.Test;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/HttpClientFactoryCertificateVerificationTest.java", "diff": "package com.github.tomakehurst.wiremock.http;\nimport com.github.tomakehurst.wiremock.WireMockServer;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.crypto.CertificateSpecification;\nimport com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\nimport com.github.tomakehurst.wiremock.crypto.Secret;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/http/ProxyResponseRendererTest.java", "diff": "package com.github.tomakehurst.wiremock.http;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.crypto.CertificateSpecification;\nimport com.github.tomakehurst.wiremock.crypto.InMemoryKeyStore;\n@@ -13,9 +13,7 @@ import com.github.tomakehurst.wiremock.stubbing.StubMapping;\nimport com.github.tomakehurst.wiremock.verification.LoggedRequest;\nimport org.junit.Rule;\nimport org.junit.Test;\n-import org.junit.function.ThrowingRunnable;\n-import javax.net.ssl.SSLHandshakeException;\nimport java.io.File;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -17,7 +17,7 @@ package com.github.tomakehurst.wiremock.standalone;\nimport com.github.tomakehurst.wiremock.client.BasicCredentials;\nimport com.github.tomakehurst.wiremock.common.FileSource;\n-import com.github.tomakehurst.wiremock.common.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.ProxySettings;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.extension.Parameters;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added an abstraction for loading KeyStores so that strategies can be plugged in via extensions
686,936
29.06.2020 17:06:32
-3,600
4feaff3c85d1725acad0ddf3ff9b77528634150c
Added ability to pass a KeyStoreSettings instance for the CA cert into the WireMock configuration
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/BrowserProxySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/BrowserProxySettings.java", "diff": "package com.github.tomakehurst.wiremock.common;\n+import com.github.tomakehurst.wiremock.common.ssl.AbstractKeyStoreSource;\n+import com.github.tomakehurst.wiremock.common.ssl.FileOrClasspathKeyStoreSource;\nimport com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport java.nio.file.Paths;\n@@ -22,24 +24,18 @@ public final class BrowserProxySettings {\nprivate final boolean enabled;\nprivate final boolean trustAllProxyTargets;\nprivate final List<String> trustedProxyTargets;\n- private final String caKeyStorePath;\n- private final String caKeyStorePassword;\n- private final String caKeyStoreType;\n+ private final KeyStoreSettings caKeyStoreSettings;\npublic BrowserProxySettings(\nboolean enabled,\nboolean trustAllProxyTargets,\nList<String> trustedProxyTargets,\n- String caKeyStorePath,\n- String caKeyStorePassword,\n- String caKeyStoreType\n+ KeyStoreSettings caKeyStoreSettings\n) {\nthis.enabled = enabled;\nthis.trustAllProxyTargets = trustAllProxyTargets;\nthis.trustedProxyTargets = trustedProxyTargets;\n- this.caKeyStorePath = caKeyStorePath;\n- this.caKeyStorePassword = caKeyStorePassword;\n- this.caKeyStoreType = caKeyStoreType;\n+ this.caKeyStoreSettings = caKeyStoreSettings;\n}\npublic boolean enabled() {\n@@ -55,9 +51,7 @@ public final class BrowserProxySettings {\n}\npublic KeyStoreSettings caKeyStore() {\n- return caKeyStorePath != null ?\n- new KeyStoreSettings(caKeyStorePath, caKeyStorePassword, caKeyStoreType) :\n- KeyStoreSettings.NO_STORE;\n+ return caKeyStoreSettings;\n}\n@Override\n@@ -66,8 +60,7 @@ public final class BrowserProxySettings {\n\"enabled=\" + enabled +\n\", trustAllProxyTargets=\" + trustAllProxyTargets +\n\", trustedProxyTargets=\" + trustedProxyTargets +\n- \", caKeyStorePath='\" + caKeyStorePath + '\\'' +\n- \", caKeyStoreType='\" + caKeyStorePath + '\\'' +\n+ \", caKeyStore='\" + caKeyStoreSettings.path() + '\\'' +\n'}';\n}\n@@ -79,13 +72,12 @@ public final class BrowserProxySettings {\nreturn enabled == that.enabled &&\ntrustAllProxyTargets == that.trustAllProxyTargets &&\nObjects.equals(trustedProxyTargets, that.trustedProxyTargets) &&\n- Objects.equals(caKeyStorePath, that.caKeyStorePath) &&\n- Objects.equals(caKeyStorePassword, that.caKeyStorePassword);\n+ Objects.equals(caKeyStoreSettings, that.caKeyStoreSettings);\n}\n@Override\npublic int hashCode() {\n- return Objects.hash(enabled, trustAllProxyTargets, trustedProxyTargets, caKeyStorePath, caKeyStorePassword);\n+ return Objects.hash(enabled, trustAllProxyTargets, trustedProxyTargets, caKeyStoreSettings);\n}\npublic static final class Builder {\n@@ -93,9 +85,8 @@ public final class BrowserProxySettings {\nprivate boolean enabled = false;\nprivate boolean trustAllProxyTargets = false;\nprivate List<String> trustedProxyTargets = emptyList();\n- private String caKeyStorePath = DEFAULT_CA_KEYSTORE_PATH;\n- private String caKeyStorePassword = DEFAULT_CA_KESTORE_PASSWORD;\n- private String caKeyStoreType = \"jks\";\n+\n+ private KeyStoreSettings caKeyStoreSettings = KeyStoreSettings.NO_STORE;\npublic Builder enabled(boolean enabled) {\nthis.enabled = enabled;\n@@ -112,23 +103,13 @@ public final class BrowserProxySettings {\nreturn this;\n}\n- public Builder caKeyStorePath(String caKeyStorePath) {\n- this.caKeyStorePath = caKeyStorePath;\n- return this;\n- }\n-\n- public Builder caKeyStorePassword(String caKeyStorePassword) {\n- this.caKeyStorePassword = caKeyStorePassword;\n- return this;\n- }\n-\n- public Builder caKeyStoreType(String caKeyStoreType) {\n- this.caKeyStoreType = caKeyStoreType;\n+ public Builder caKeyStoreSettings(KeyStoreSettings caKeyStoreSettings) {\n+ this.caKeyStoreSettings = caKeyStoreSettings;\nreturn this;\n}\npublic BrowserProxySettings build() {\n- return new BrowserProxySettings(enabled, trustAllProxyTargets, trustedProxyTargets, caKeyStorePath, caKeyStorePassword, caKeyStoreType);\n+ return new BrowserProxySettings(enabled, trustAllProxyTargets, trustedProxyTargets, caKeyStoreSettings);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/AbstractKeyStoreSource.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/AbstractKeyStoreSource.java", "diff": "@@ -5,6 +5,8 @@ import com.github.tomakehurst.wiremock.common.Source;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.KeyStore;\n+import java.util.Arrays;\n+import java.util.Objects;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -48,4 +50,20 @@ public abstract class AbstractKeyStoreSource implements Source<KeyStore> {\npublic char[] getKeyStorePassword() {\nreturn keyStorePassword;\n}\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ AbstractKeyStoreSource that = (AbstractKeyStoreSource) o;\n+ return keyStoreType.equals(that.keyStoreType) &&\n+ Arrays.equals(keyStorePassword, that.keyStorePassword);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ int result = Objects.hash(keyStoreType);\n+ result = 31 * result + Arrays.hashCode(keyStorePassword);\n+ return result;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/FileOrClasspathKeyStoreSource.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/FileOrClasspathKeyStoreSource.java", "diff": "@@ -7,6 +7,7 @@ import java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.KeyStore;\n+import java.util.Objects;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n@@ -46,4 +47,18 @@ public class FileOrClasspathKeyStoreSource extends AbstractKeyStoreSource {\npublic String getPath() {\nreturn path;\n}\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ if (!super.equals(o)) return false;\n+ FileOrClasspathKeyStoreSource that = (FileOrClasspathKeyStoreSource) o;\n+ return path.equals(that.path);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(super.hashCode(), path);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "diff": "@@ -42,7 +42,7 @@ public class KeyStoreSettings {\nreturn ((FileOrClasspathKeyStoreSource) keyStoreSource).getPath();\n}\n- throw new IllegalStateException(\"Can't get the path from a custom keystore source\");\n+ return \"(no path - custom keystore source)\";\n}\npublic String password() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "diff": "package com.github.tomakehurst.wiremock.core;\nimport com.github.tomakehurst.wiremock.common.*;\n+import com.github.tomakehurst.wiremock.common.ssl.AbstractKeyStoreSource;\n+import com.github.tomakehurst.wiremock.common.ssl.FileOrClasspathKeyStoreSource;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.extension.Extension;\nimport com.github.tomakehurst.wiremock.extension.ExtensionLoader;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\n@@ -45,6 +48,7 @@ import static com.github.tomakehurst.wiremock.common.BrowserProxySettings.DEFAUL\nimport static com.github.tomakehurst.wiremock.common.BrowserProxySettings.DEFAULT_CA_KEYSTORE_PATH;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\nimport static com.github.tomakehurst.wiremock.extension.ExtensionLoader.valueAssignableFrom;\n+import static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.collect.Lists.transform;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static java.util.Arrays.asList;\n@@ -71,6 +75,7 @@ public class WireMockConfiguration implements Options {\nprivate String caKeystorePath = DEFAULT_CA_KEYSTORE_PATH;\nprivate String caKeystorePassword = DEFAULT_CA_KESTORE_PASSWORD;\nprivate String caKeystoreType = \"JKS\";\n+ private KeyStoreSettings caKeyStoreSettings = null;\nprivate boolean trustAllProxyTargets = false;\nprivate final List<String> trustedProxyTargets = new ArrayList<>();\n@@ -189,6 +194,11 @@ public class WireMockConfiguration implements Options {\nreturn this;\n}\n+ public WireMockConfiguration caKeystoreSettings(KeyStoreSettings caKeyStoreSettings) {\n+ this.caKeyStoreSettings = caKeyStoreSettings;\n+ return this;\n+ }\n+\npublic WireMockConfiguration caKeystorePath(String path) {\nthis.caKeystorePath = path;\nreturn this;\n@@ -562,13 +572,15 @@ public class WireMockConfiguration implements Options {\n@Override\npublic BrowserProxySettings browserProxySettings() {\n+ KeyStoreSettings keyStoreSettings = caKeyStoreSettings != null ?\n+ caKeyStoreSettings :\n+ new KeyStoreSettings(new FileOrClasspathKeyStoreSource(caKeystorePath, caKeystoreType, caKeystorePassword.toCharArray()));\n+\nreturn new BrowserProxySettings.Builder()\n.enabled(browserProxyingEnabled)\n.trustAllProxyTargets(trustAllProxyTargets)\n.trustedProxyTargets(trustedProxyTargets)\n- .caKeyStorePath(caKeystorePath)\n- .caKeyStorePassword(caKeystorePassword)\n- .caKeyStoreType(caKeystoreType)\n+ .caKeyStoreSettings(keyStoreSettings)\n.build();\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -17,6 +17,7 @@ package com.github.tomakehurst.wiremock.standalone;\nimport com.github.tomakehurst.wiremock.common.*;\nimport com.github.tomakehurst.wiremock.common.BrowserProxySettings;\n+import com.github.tomakehurst.wiremock.common.ssl.FileOrClasspathKeyStoreSource;\nimport com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.core.MappingsSaver;\nimport com.github.tomakehurst.wiremock.core.Options;\n@@ -587,15 +588,22 @@ public class CommandLineOptions implements Options {\nreturn optionSet.has(ENABLE_STUB_CORS);\n}\n+ @SuppressWarnings(\"unchecked\")\n@Override\npublic BrowserProxySettings browserProxySettings() {\n+ KeyStoreSettings keyStoreSettings = new KeyStoreSettings(\n+ new FileOrClasspathKeyStoreSource(\n+ (String) optionSet.valueOf(HTTPS_CA_KEYSTORE),\n+ (String) optionSet.valueOf(HTTPS_CA_KEYSTORE_TYPE),\n+ ((String) optionSet.valueOf(HTTPS_CA_KEYSTORE_PASSWORD)).toCharArray()\n+ )\n+ );\n+\nreturn new BrowserProxySettings.Builder()\n.enabled(optionSet.has(ENABLE_BROWSER_PROXYING))\n.trustAllProxyTargets(optionSet.has(TRUST_ALL_PROXY_TARGETS))\n.trustedProxyTargets((List<String>) optionSet.valuesOf(TRUST_PROXY_TARGET))\n- .caKeyStorePath((String) optionSet.valueOf(HTTPS_CA_KEYSTORE))\n- .caKeyStorePassword((String) optionSet.valueOf(HTTPS_CA_KEYSTORE_PASSWORD))\n- .caKeyStoreType((String) optionSet.valueOf(HTTPS_CA_KEYSTORE_TYPE))\n+ .caKeyStoreSettings(keyStoreSettings)\n.build();\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added ability to pass a KeyStoreSettings instance for the CA cert into the WireMock configuration
686,936
29.06.2020 17:36:21
-3,600
500ebec94e92f4fc947f2e8dfd4ce9cf4f91d63f
Added support for saving keystore files and switched the Jetty94 browser proxying CA cert setup code to use this
[ { "change_type": "MODIFY", "old_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "diff": "@@ -2,8 +2,8 @@ package com.github.tomakehurst.wiremock.jetty94;\nimport com.github.tomakehurst.wiremock.common.BrowserProxySettings;\nimport com.github.tomakehurst.wiremock.common.HttpsSettings;\n-import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.common.Notifier;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateAuthority;\nimport com.github.tomakehurst.wiremock.http.ssl.CertificateGenerationUnsupportedException;\n@@ -13,22 +13,13 @@ import org.eclipse.jetty.http2.HTTP2Cipher;\nimport org.eclipse.jetty.server.SslConnectionFactory;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n-import java.io.FileOutputStream;\nimport java.io.IOException;\n-import java.nio.file.FileSystems;\n-import java.nio.file.Files;\n-import java.nio.file.Path;\n-import java.nio.file.Paths;\n-import java.nio.file.attribute.FileAttribute;\nimport java.security.KeyStore;\nimport java.security.KeyStoreException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\n-import java.util.EnumSet;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-import static java.nio.file.attribute.PosixFilePermission.*;\n-import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\npublic class SslContexts {\n@@ -136,27 +127,8 @@ public class SslContexts {\nkeyStore.load(null, password);\nkeyStore.setKeyEntry(\"wiremock-ca\", certificateAuthority.key(), password, certificateAuthority.certificateChain());\n- Path created = createCaKeystoreFile(Paths.get(browserProxyCaKeyStore.path()));\n- try (FileOutputStream fos = new FileOutputStream(created.toFile())) {\n- try {\n- keyStore.store(fos, password);\n- } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) {\n- throwUnchecked(e);\n- }\n- }\n- return new X509KeyStore(keyStore, password);\n- }\n+ browserProxyCaKeyStore.getSource().save(keyStore);\n- private static Path createCaKeystoreFile(Path path) throws IOException {\n- FileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\n- FileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n- if (FileSystems.getDefault().supportedFileAttributeViews().contains(\"posix\")) {\n- privateDirAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)) };\n- privateFileAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)) };\n- }\n- if (!Files.exists(path.getParent())) {\n- Files.createDirectories(path.getParent(), privateDirAttrs);\n- }\n- return Files.createFile(path, privateFileAttrs);\n+ return new X509KeyStore(keyStore, password);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/FileOrClasspathKeyStoreSource.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/FileOrClasspathKeyStoreSource.java", "diff": "@@ -2,14 +2,22 @@ package com.github.tomakehurst.wiremock.common.ssl;\nimport com.google.common.io.Resources;\n-import java.io.File;\n-import java.io.FileInputStream;\n-import java.io.IOException;\n-import java.io.InputStream;\n+import java.io.*;\n+import java.nio.file.FileSystems;\n+import java.nio.file.Files;\n+import java.nio.file.Path;\n+import java.nio.file.Paths;\n+import java.nio.file.attribute.FileAttribute;\nimport java.security.KeyStore;\n+import java.security.KeyStoreException;\n+import java.security.NoSuchAlgorithmException;\n+import java.security.cert.CertificateException;\n+import java.util.EnumSet;\nimport java.util.Objects;\nimport static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static java.nio.file.attribute.PosixFilePermission.*;\n+import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\npublic class FileOrClasspathKeyStoreSource extends AbstractKeyStoreSource {\n@@ -40,8 +48,31 @@ public class FileOrClasspathKeyStoreSource extends AbstractKeyStoreSource {\n}\n@Override\n- public void save(KeyStore item) {\n+ public void save(KeyStore keyStore) {\n+ Path created = createKeystoreFile(Paths.get(path));\n+ try (FileOutputStream fos = new FileOutputStream(created.toFile())) {\n+ keyStore.store(fos, keyStorePassword);\n+ } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {\n+ throwUnchecked(e);\n+ }\n+ }\n+\n+ private static Path createKeystoreFile(Path path) {\n+ FileAttribute<?>[] privateDirAttrs = new FileAttribute<?>[0];\n+ FileAttribute<?>[] privateFileAttrs = new FileAttribute<?>[0];\n+ if (FileSystems.getDefault().supportedFileAttributeViews().contains(\"posix\")) {\n+ privateDirAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE)) };\n+ privateFileAttrs = new FileAttribute<?>[] { asFileAttribute(EnumSet.of(OWNER_READ, OWNER_WRITE)) };\n+ }\n+ try {\n+ if (!Files.exists(path.getParent())) {\n+ Files.createDirectories(path.getParent(), privateDirAttrs);\n+ }\n+ return Files.createFile(path, privateFileAttrs);\n+ } catch (IOException e) {\n+ return throwUnchecked(e, Path.class);\n+ }\n}\npublic String getPath() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "diff": "*/\npackage com.github.tomakehurst.wiremock.common.ssl;\n+import com.github.tomakehurst.wiremock.common.Source;\n+\nimport java.security.KeyStore;\npublic class KeyStoreSettings {\n@@ -57,6 +59,10 @@ public class KeyStoreSettings {\nreturn keyStoreSource.load();\n}\n+ public Source<KeyStore> getSource() {\n+ return keyStoreSource;\n+ }\n+\npublic boolean exists() {\nreturn keyStoreSource.exists();\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added support for saving keystore files and switched the Jetty94 browser proxying CA cert setup code to use this
686,936
30.06.2020 16:01:04
-3,600
129d00b18f27e0ce62f5c2f0cc1d53bf72968c65
Fixed - added the ability to set the keystore type and trust store type from the CLI
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/running-standalone.md", "new_path": "docs-v2/_docs/running-standalone.md", "diff": "@@ -41,6 +41,8 @@ certificate to use with HTTPS. The keystore must have a password of\nIf this option isn't used WireMock will default to its own self-signed\ncertificate.\n+`--keystore-type`: The HTTPS keystore type. Usually JKS or PKCS12.\n+\n`--keystore-password`: Password to the keystore, if something other than\n\"password\".\nNote: the behaviour of this changed in version 2.27.0. Previously this set Jetty's key manager password, whereas now it\n@@ -56,6 +58,8 @@ authenticate with a proxy target that require client authentication. See\nand [Running as a browser proxy](/docs/proxying#running-as-a-browser-proxy) for\ndetails.\n+`--keystore-type`: The HTTPS trust store type. Usually JKS or PKCS12.\n+\n`--truststore-password`: Optional password to the trust store. Defaults\nto \"password\" if not specified.\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "@@ -74,9 +74,11 @@ public class CommandLineOptions implements Options {\nprivate static final String HTTPS_PORT = \"https-port\";\nprivate static final String HTTPS_KEYSTORE = \"https-keystore\";\nprivate static final String HTTPS_KEYSTORE_PASSWORD = \"keystore-password\";\n+ private static final String HTTPS_KEYSTORE_TYPE = \"keystore-type\";\nprivate static final String HTTPS_KEY_MANAGER_PASSWORD = \"key-manager-password\";\nprivate static final String HTTPS_TRUSTSTORE = \"https-truststore\";\nprivate static final String HTTPS_TRUSTSTORE_PASSWORD = \"truststore-password\";\n+ private static final String HTTPS_TRUSTSTORE_TYPE = \"truststore-type\";\nprivate static final String REQUIRE_CLIENT_CERT = \"https-require-client-cert\";\nprivate static final String VERBOSE = \"verbose\";\nprivate static final String ENABLE_BROWSER_PROXYING = \"enable-browser-proxying\";\n@@ -125,8 +127,10 @@ public class CommandLineOptions implements Options {\noptionParser.accepts(BIND_ADDRESS, \"The IP to listen connections\").withRequiredArg();\noptionParser.accepts(CONTAINER_THREADS, \"The number of container threads\").withRequiredArg();\noptionParser.accepts(REQUIRE_CLIENT_CERT, \"Make the server require a trusted client certificate to enable a connection\");\n+ optionParser.accepts(HTTPS_TRUSTSTORE_TYPE, \"The HTTPS trust store type\").withRequiredArg().defaultsTo(\"JKS\");\noptionParser.accepts(HTTPS_TRUSTSTORE_PASSWORD, \"Password for the trust store\").withRequiredArg();\noptionParser.accepts(HTTPS_TRUSTSTORE, \"Path to an alternative truststore for HTTPS client certificates. Must have a password of \\\"password\\\".\").requiredIf(REQUIRE_CLIENT_CERT).withRequiredArg();\n+ optionParser.accepts(HTTPS_KEYSTORE_TYPE, \"The HTTPS keystore type.\").withRequiredArg().defaultsTo(\"JKS\");\noptionParser.accepts(HTTPS_KEYSTORE_PASSWORD, \"Password for the alternative keystore.\").withRequiredArg().defaultsTo(\"password\");\noptionParser.accepts(HTTPS_KEY_MANAGER_PASSWORD, \"Key manager password for use with the alternative keystore.\").withRequiredArg().defaultsTo(\"password\");\noptionParser.accepts(HTTPS_KEYSTORE, \"Path to an alternative keystore for HTTPS. Password is assumed to be \\\"password\\\" if not specified.\").requiredIf(HTTPS_TRUSTSTORE).requiredIf(HTTPS_KEYSTORE_PASSWORD).withRequiredArg().defaultsTo(Resources.getResource(\"keystore\").toString());\n@@ -281,9 +285,11 @@ public class CommandLineOptions implements Options {\n.port(httpsPortNumber())\n.keyStorePath((String) optionSet.valueOf(HTTPS_KEYSTORE))\n.keyStorePassword((String) optionSet.valueOf(HTTPS_KEYSTORE_PASSWORD))\n+ .keyStoreType((String) optionSet.valueOf(HTTPS_KEYSTORE_TYPE))\n.keyManagerPassword((String) optionSet.valueOf(HTTPS_KEY_MANAGER_PASSWORD))\n.trustStorePath((String) optionSet.valueOf(HTTPS_TRUSTSTORE))\n.trustStorePassword((String) optionSet.valueOf(HTTPS_TRUSTSTORE_PASSWORD))\n+ .trustStoreType((String) optionSet.valueOf(HTTPS_TRUSTSTORE_TYPE))\n.needClientAuth(optionSet.has(REQUIRE_CLIENT_CERT)).build();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -114,19 +114,29 @@ public class CommandLineOptionsTest {\n}\n@Test\n- public void setsTrustStorePathAndPassword() {\n- CommandLineOptions options = new CommandLineOptions(\"--https-port\", \"8443\",\n+ public void setsTrustStoreOptions() {\n+ CommandLineOptions options = new CommandLineOptions(\n+ \"--https-port\", \"8443\",\n\"--https-keystore\", \"/my/keystore\",\n\"--https-truststore\", \"/my/truststore\",\n+ \"--truststore-type\", \"PKCS12\",\n\"--truststore-password\", \"sometrustpwd\");\nassertThat(options.httpsSettings().trustStorePath(), is(\"/my/truststore\"));\n+ assertThat(options.httpsSettings().trustStoreType(), is(\"PKCS12\"));\nassertThat(options.httpsSettings().trustStorePassword(), is(\"sometrustpwd\"));\n}\n@Test\n- public void setsKeyStorePathPasswordAndKeyManagerPassword() {\n- CommandLineOptions options = new CommandLineOptions(\"--https-port\", \"8443\", \"--https-keystore\", \"/my/keystore\", \"--keystore-password\", \"someotherpwd\", \"--key-manager-password\", \"keymanpass\");\n+ public void setsHttpsKeyStorePathOptions() {\n+ CommandLineOptions options = new CommandLineOptions(\n+ \"--https-port\", \"8443\",\n+ \"--https-keystore\", \"/my/keystore\",\n+ \"--keystore-type\", \"pkcs12\",\n+ \"--keystore-password\", \"someotherpwd\",\n+ \"--key-manager-password\", \"keymanpass\"\n+ );\nassertThat(options.httpsSettings().keyStorePath(), is(\"/my/keystore\"));\n+ assertThat(options.httpsSettings().keyStoreType(), is(\"pkcs12\"));\nassertThat(options.httpsSettings().keyStorePassword(), is(\"someotherpwd\"));\nassertThat(options.httpsSettings().keyManagerPassword(), is(\"keymanpass\"));\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #994 - added the ability to set the keystore type and trust store type from the CLI
686,936
30.06.2020 18:35:42
-3,600
d597aafdc3c6821b564781594205212d43d9f835
Upgraded to Jetty 9.4.30 and Conscrypt 2.2.1 (not the most recent, but the newest that supports < OSX Catalina)
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -48,7 +48,7 @@ allprojects {\n],\njava8: [\nhandlebars : '4.2.0',\n- jetty : '9.4.28.v20200408',\n+ jetty : '9.4.30.v20200611',\nguava : '29.0-jre',\njackson : jacksonVersion,\njacksonDatabind: jacksonVersion,\n" }, { "change_type": "MODIFY", "old_path": "java8/build.gradle", "new_path": "java8/build.gradle", "diff": "@@ -4,13 +4,18 @@ shadowJar.baseName = 'wiremock-jre8-standalone'\nsourceCompatibility = 1.8\ntargetCompatibility = 1.8\n-final jettyVersion = '9.4.20.v20190813'\n+final jettyVersion = '9.4.30.v20200611'\ndependencies {\ncompile \"org.eclipse.jetty.http2:http2-server:$jettyVersion\"\ncompile \"org.eclipse.jetty:jetty-alpn-server:$jettyVersion\"\n- compile \"org.eclipse.jetty:jetty-alpn-conscrypt-server:$jettyVersion\"\n- compile \"org.eclipse.jetty:jetty-alpn-conscrypt-client:$jettyVersion\"\n+ compile \"org.eclipse.jetty:jetty-alpn-conscrypt-server:$jettyVersion\", {\n+ exclude group: 'org.conscrypt'\n+ }\n+ compile \"org.eclipse.jetty:jetty-alpn-conscrypt-client:$jettyVersion\", {\n+ exclude group: 'org.conscrypt'\n+ }\n+ compile 'org.conscrypt:conscrypt-openjdk-uber:2.2.1'\ncompile 'net.javacrumbs.json-unit:json-unit-core:2.12.0'\ntestCompile \"org.eclipse.jetty:jetty-client:$jettyVersion\"\n" }, { "change_type": "MODIFY", "old_path": "java8/src/test/resources/log4j.properties", "new_path": "java8/src/test/resources/log4j.properties", "diff": "-log4j.rootLogger=DEBUG, stdout\n+log4j.rootLogger=INFO, stdout\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.target=System.out\n@@ -6,4 +6,4 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{10}:%L - %m%n\nlog4j.logger.org.apache.http=DEBUG\n-log4j.logger.org.eclipse=DEBUG\n\\ No newline at end of file\n+log4j.logger.org.eclipse=INFO\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded to Jetty 9.4.30 and Conscrypt 2.2.1 (not the most recent, but the newest that supports < OSX Catalina)
686,936
02.07.2020 19:00:10
-3,600
e2809ebe6a5bca524bf624b0039588ffae7f7be4
Moved the writable key store source (used when browser proxying HTTPS) to the java8 sources to avoid breaking older Android builds in the java7 build with use of Path, Paths etc. from java.nio
[ { "change_type": "RENAME", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/FileOrClasspathKeyStoreSource.java", "new_path": "java8/src/main/java/com/github/tomakehurst/wiremock/jetty94/WritableFileOrClasspathKeyStoreSource.java", "diff": "-package com.github.tomakehurst.wiremock.common.ssl;\n+package com.github.tomakehurst.wiremock.jetty94;\n+import com.github.tomakehurst.wiremock.common.ssl.ReadOnlyFileOrClasspathKeyStoreSource;\nimport com.google.common.io.Resources;\nimport java.io.*;\nimport java.net.MalformedURLException;\n-import java.net.URI;\n-import java.net.URISyntaxException;\nimport java.net.URL;\nimport java.nio.file.FileSystems;\nimport java.nio.file.Files;\n@@ -23,37 +22,10 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\nimport static java.nio.file.attribute.PosixFilePermission.*;\nimport static java.nio.file.attribute.PosixFilePermissions.asFileAttribute;\n-public class FileOrClasspathKeyStoreSource extends KeyStoreSource {\n+public class WritableFileOrClasspathKeyStoreSource extends ReadOnlyFileOrClasspathKeyStoreSource {\n- private final String path;\n-\n- public FileOrClasspathKeyStoreSource(String path, String keyStoreType, char[] keyStorePassword) {\n- super(keyStoreType, keyStorePassword);\n- this.path = path;\n- }\n-\n- @SuppressWarnings(\"UnstableApiUsage\")\n- @Override\n- protected InputStream createInputStream() {\n- try {\n- if (exists()) {\n- return new FileInputStream(path);\n- } else {\n- try {\n- URL pathUrl = new URL(path);\n- return pathUrl.openStream();\n- } catch (MalformedURLException ignored) {\n- return Resources.getResource(path).openStream();\n- }\n- }\n- } catch (IOException e) {\n- return throwUnchecked(e, InputStream.class);\n- }\n- }\n-\n- @Override\n- public boolean exists() {\n- return new File(path).isFile();\n+ public WritableFileOrClasspathKeyStoreSource(String path, String keyStoreType, char[] keyStorePassword) {\n+ super(path, keyStoreType, keyStorePassword);\n}\n@Override\n@@ -83,22 +55,4 @@ public class FileOrClasspathKeyStoreSource extends KeyStoreSource {\nreturn throwUnchecked(e, Path.class);\n}\n}\n-\n- public String getPath() {\n- return path;\n- }\n-\n- @Override\n- public boolean equals(Object o) {\n- if (this == o) return true;\n- if (o == null || getClass() != o.getClass()) return false;\n- if (!super.equals(o)) return false;\n- FileOrClasspathKeyStoreSource that = (FileOrClasspathKeyStoreSource) o;\n- return path.equals(that.path);\n- }\n-\n- @Override\n- public int hashCode() {\n- return Objects.hash(super.hashCode(), path);\n- }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/BrowserProxySettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/BrowserProxySettings.java", "diff": "@@ -2,7 +2,7 @@ package com.github.tomakehurst.wiremock.common;\nimport com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\n-import java.nio.file.Paths;\n+import java.io.File;\nimport java.util.List;\nimport java.util.Objects;\n@@ -10,11 +10,11 @@ import static java.util.Collections.emptyList;\npublic final class BrowserProxySettings {\n- public static final String DEFAULT_CA_KEYSTORE_PATH = Paths.get(\n- System.getProperty(\"user.home\"))\n- .resolve(\".wiremock\")\n- .resolve(\"ca-keystore.jks\")\n- .toFile().getAbsolutePath();\n+ public static final String DEFAULT_CA_KEYSTORE_PATH = new File(\n+ System.getProperty(\"user.home\") + File.separatorChar\n+ + \".wiremock\" + File.separatorChar\n+ + \"ca-keystore.jks\" + File.separatorChar\n+ ).getAbsolutePath();\npublic static final String DEFAULT_CA_KESTORE_PASSWORD = \"password\";\npublic static BrowserProxySettings DISABLED = new Builder().build();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSettings.java", "diff": "@@ -31,7 +31,7 @@ public class KeyStoreSettings {\npublic KeyStoreSettings(String path, String password, String type) {\nthis(\n- path != null && password != null && type != null ? new FileOrClasspathKeyStoreSource(\n+ path != null && password != null && type != null ? KeyStoreSourceFactory.getAppropriateForJreVersion(\npath,\ntype,\npassword.toCharArray()) :\n@@ -40,8 +40,8 @@ public class KeyStoreSettings {\n}\npublic String path() {\n- if (keyStoreSource instanceof FileOrClasspathKeyStoreSource) {\n- return ((FileOrClasspathKeyStoreSource) keyStoreSource).getPath();\n+ if (keyStoreSource instanceof ReadOnlyFileOrClasspathKeyStoreSource) {\n+ return ((ReadOnlyFileOrClasspathKeyStoreSource) keyStoreSource).getPath();\n}\nreturn \"(no path - custom keystore source)\";\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSourceFactory.java", "diff": "+package com.github.tomakehurst.wiremock.common.ssl;\n+\n+import com.github.tomakehurst.wiremock.common.Exceptions;\n+\n+import java.lang.reflect.Constructor;\n+import java.lang.reflect.InvocationTargetException;\n+\n+public class KeyStoreSourceFactory {\n+\n+ @SuppressWarnings(\"unchecked\")\n+ public static KeyStoreSource getAppropriateForJreVersion(String path, String keyStoreType, char[] keyStorePassword) {\n+ try {\n+ final Class<?extends KeyStoreSource> theClass = (Class<? extends KeyStoreSource>) Class.forName(\"com.github.tomakehurst.wiremock.jetty94.WritableFileOrClasspathKeyStoreSource\");\n+ return safelyGetConstructor(theClass, String.class, String.class, char[].class).newInstance(path, keyStoreType, keyStorePassword);\n+ } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | InvocationTargetException e) {\n+ return new ReadOnlyFileOrClasspathKeyStoreSource(path, keyStoreType, keyStorePassword);\n+ }\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ private static <T> Constructor<T> safelyGetConstructor(Class<T> clazz, Class<?>... parameterTypes) {\n+ try {\n+ return clazz.getConstructor(parameterTypes);\n+ } catch (NoSuchMethodException e) {\n+ return Exceptions.throwUnchecked(e, Constructor.class);\n+ }\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/ReadOnlyFileOrClasspathKeyStoreSource.java", "diff": "+package com.github.tomakehurst.wiremock.common.ssl;\n+\n+import com.google.common.io.Resources;\n+\n+import java.io.File;\n+import java.io.FileInputStream;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.net.MalformedURLException;\n+import java.net.URL;\n+import java.security.KeyStore;\n+import java.util.Objects;\n+\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+\n+public class ReadOnlyFileOrClasspathKeyStoreSource extends KeyStoreSource {\n+\n+ protected final String path;\n+\n+ public ReadOnlyFileOrClasspathKeyStoreSource(String path, String keyStoreType, char[] keyStorePassword) {\n+ super(keyStoreType, keyStorePassword);\n+ this.path = path;\n+ }\n+\n+ @SuppressWarnings(\"UnstableApiUsage\")\n+ @Override\n+ protected InputStream createInputStream() {\n+ try {\n+ if (exists()) {\n+ return new FileInputStream(path);\n+ } else {\n+ try {\n+ URL pathUrl = new URL(path);\n+ return pathUrl.openStream();\n+ } catch (MalformedURLException ignored) {\n+ return Resources.getResource(path).openStream();\n+ }\n+ }\n+ } catch (IOException e) {\n+ return throwUnchecked(e, InputStream.class);\n+ }\n+ }\n+\n+ @Override\n+ public boolean exists() {\n+ return new File(path).isFile();\n+ }\n+\n+ @Override\n+ public void save(KeyStore keyStore) {}\n+\n+ public String getPath() {\n+ return path;\n+ }\n+\n+ @Override\n+ public boolean equals(Object o) {\n+ if (this == o) return true;\n+ if (o == null || getClass() != o.getClass()) return false;\n+ if (!super.equals(o)) return false;\n+ ReadOnlyFileOrClasspathKeyStoreSource that = (ReadOnlyFileOrClasspathKeyStoreSource) o;\n+ return path.equals(that.path);\n+ }\n+\n+ @Override\n+ public int hashCode() {\n+ return Objects.hash(super.hashCode(), path);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/WireMockConfiguration.java", "diff": "package com.github.tomakehurst.wiremock.core;\nimport com.github.tomakehurst.wiremock.common.*;\n-import com.github.tomakehurst.wiremock.common.ssl.FileOrClasspathKeyStoreSource;\nimport com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSourceFactory;\nimport com.github.tomakehurst.wiremock.extension.Extension;\nimport com.github.tomakehurst.wiremock.extension.ExtensionLoader;\nimport com.github.tomakehurst.wiremock.http.CaseInsensitiveKey;\n@@ -579,7 +579,7 @@ public class WireMockConfiguration implements Options {\npublic BrowserProxySettings browserProxySettings() {\nKeyStoreSettings keyStoreSettings = caKeyStoreSettings != null ?\ncaKeyStoreSettings :\n- new KeyStoreSettings(new FileOrClasspathKeyStoreSource(caKeystorePath, caKeystoreType, caKeystorePassword.toCharArray()));\n+ new KeyStoreSettings(KeyStoreSourceFactory.getAppropriateForJreVersion(caKeystorePath, caKeystoreType, caKeystorePassword.toCharArray()));\nreturn new BrowserProxySettings.Builder()\n.enabled(browserProxyingEnabled)\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptions.java", "diff": "package com.github.tomakehurst.wiremock.standalone;\nimport com.github.tomakehurst.wiremock.common.*;\n-import com.github.tomakehurst.wiremock.common.BrowserProxySettings;\n-import com.github.tomakehurst.wiremock.common.ssl.FileOrClasspathKeyStoreSource;\nimport com.github.tomakehurst.wiremock.common.ssl.KeyStoreSettings;\n+import com.github.tomakehurst.wiremock.common.ssl.KeyStoreSourceFactory;\nimport com.github.tomakehurst.wiremock.core.MappingsSaver;\nimport com.github.tomakehurst.wiremock.core.Options;\nimport com.github.tomakehurst.wiremock.core.WireMockApp;\n@@ -50,12 +49,15 @@ import joptsimple.OptionSet;\nimport java.io.IOException;\nimport java.io.StringWriter;\nimport java.net.URI;\n-import java.util.*;\n+import java.util.Collections;\n+import java.util.List;\n+import java.util.Map;\n+import java.util.Set;\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.common.BrowserProxySettings.DEFAULT_CA_KESTORE_PASSWORD;\nimport static com.github.tomakehurst.wiremock.common.BrowserProxySettings.DEFAULT_CA_KEYSTORE_PATH;\n+import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n+import static com.github.tomakehurst.wiremock.common.ProxySettings.NO_PROXY;\nimport static com.github.tomakehurst.wiremock.core.WireMockApp.MAPPINGS_ROOT;\nimport static com.github.tomakehurst.wiremock.extension.ExtensionLoader.valueAssignableFrom;\nimport static com.github.tomakehurst.wiremock.http.CaseInsensitiveKey.TO_CASE_INSENSITIVE_KEYS;\n@@ -601,7 +603,7 @@ public class CommandLineOptions implements Options {\n@Override\npublic BrowserProxySettings browserProxySettings() {\nKeyStoreSettings keyStoreSettings = new KeyStoreSettings(\n- new FileOrClasspathKeyStoreSource(\n+ KeyStoreSourceFactory.getAppropriateForJreVersion(\n(String) optionSet.valueOf(HTTPS_CA_KEYSTORE),\n(String) optionSet.valueOf(HTTPS_CA_KEYSTORE_TYPE),\n((String) optionSet.valueOf(HTTPS_CA_KEYSTORE_PASSWORD)).toCharArray()\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSourceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSourceTest.java", "diff": "@@ -12,7 +12,7 @@ public class KeyStoreSourceTest {\n@Test\npublic void loadsAPasswordProtectedJksKeyStore() throws Exception {\n- KeyStoreSource keyStoreSource = new FileOrClasspathKeyStoreSource(\n+ KeyStoreSource keyStoreSource = new ReadOnlyFileOrClasspathKeyStoreSource(\n\"test-keystore-pwd\",\n\"jks\",\n\"nondefaultpass\".toCharArray()\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Moved the writable key store source (used when browser proxying HTTPS) to the java8 sources to avoid breaking older Android builds in the java7 build with use of Path, Paths etc. from java.nio
686,936
07.07.2020 10:27:51
-3,600
1b48c423ef5c7ce34382da021af943a2689a752c
Fixed - raised default Jetty stop timeout to prevent unbounded thread creation
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "@@ -163,7 +163,7 @@ public class JettyHttpServer implements HttpServer {\nprotected void finalizeSetup(Options options) {\nif(!options.jettySettings().getStopTimeout().isPresent()) {\n- jettyServer.setStopTimeout(0);\n+ jettyServer.setStopTimeout(1000);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServerTest.java", "diff": "@@ -80,7 +80,7 @@ public class JettyHttpServerTest {\n@Test\npublic void testStopTimeoutNotSet() {\n- long expectedStopTimeout = 0L;\n+ long expectedStopTimeout = 1000L;\nWireMockConfiguration config = WireMockConfiguration.wireMockConfig();\nJettyHttpServer jettyHttpServer = (JettyHttpServer) serverFactory.buildHttpServer(config, adminRequestHandler, stubRequestHandler);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1346 - raised default Jetty stop timeout to prevent unbounded thread creation
686,936
08.09.2020 11:13:36
-3,600
278ab58e535d7d80d2dcab9183e90b9a2c9fd50e
Fixed - removed memoization of string value pattern matches, as this is severly detrimental to performance for some workloads and causes unbounded heap growth
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToJsonPattern.java", "diff": "@@ -36,7 +36,7 @@ import static com.github.tomakehurst.wiremock.common.Json.maxDeepSize;\nimport static com.google.common.collect.Iterables.getLast;\nimport static org.apache.commons.lang3.math.NumberUtils.isNumber;\n-public class EqualToJsonPattern extends MemoizingStringValuePattern {\n+public class EqualToJsonPattern extends StringValuePattern {\nprivate final JsonNode expected;\nprivate final Boolean ignoreArrayOrder;\n@@ -94,7 +94,7 @@ public class EqualToJsonPattern extends MemoizingStringValuePattern {\n}\n@Override\n- protected MatchResult calculateMatch(String value) {\n+ public MatchResult match(String value) {\ntry {\nfinal JsonNode actual = Json.read(value, JsonNode.class);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToPattern.java", "diff": "@@ -21,7 +21,7 @@ import java.util.Objects;\nimport static org.apache.commons.lang3.StringUtils.getLevenshteinDistance;\n-public class EqualToPattern extends MemoizingStringValuePattern {\n+public class EqualToPattern extends StringValuePattern {\nprivate final Boolean caseInsensitive;\n@@ -46,7 +46,7 @@ public class EqualToPattern extends MemoizingStringValuePattern {\n}\n@Override\n- protected MatchResult calculateMatch(final String value) {\n+ public MatchResult match(final String value) {\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/EqualToXmlPattern.java", "diff": "@@ -38,7 +38,7 @@ import static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static org.xmlunit.diff.ComparisonType.*;\n-public class EqualToXmlPattern extends MemoizingStringValuePattern {\n+public class EqualToXmlPattern extends StringValuePattern {\nprivate static Set<ComparisonType> COUNTED_COMPARISONS = ImmutableSet.of(\nELEMENT_TAG_NAME,\n@@ -115,7 +115,7 @@ public class EqualToXmlPattern extends MemoizingStringValuePattern {\n}\n@Override\n- protected MatchResult calculateMatch(final String value) {\n+ public MatchResult match(final String value) {\nreturn new MatchResult() {\n@Override\npublic boolean isExactMatch() {\n" }, { "change_type": "DELETE", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/MemoizingStringValuePattern.java", "new_path": null, "diff": "-package com.github.tomakehurst.wiremock.matching;\n-\n-import com.google.common.cache.CacheBuilder;\n-import com.google.common.cache.CacheLoader;\n-import com.google.common.cache.LoadingCache;\n-\n-import java.util.concurrent.ExecutionException;\n-\n-import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\n-\n-public abstract class MemoizingStringValuePattern extends StringValuePattern {\n-\n- private final LoadingCache<String, MatchResult> cache = CacheBuilder.newBuilder()\n- .build(new CacheLoader<String, MatchResult>() {\n- @Override\n- public MatchResult load(String value) {\n- return new MemoizingMatchResult(calculateMatch(value));\n- }\n- });\n-\n- public MemoizingStringValuePattern(String expectedValue) {\n- super(expectedValue);\n- }\n-\n- @Override\n- public final MatchResult match(String value) {\n- if (value == null) {\n- return MatchResult.noMatch();\n- }\n-\n- try {\n- return cache.get(value);\n- } catch (ExecutionException e) {\n- return throwUnchecked(e, MatchResult.class);\n- }\n- }\n-\n- protected abstract MatchResult calculateMatch(String value);\n-}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/matching/PathPattern.java", "diff": "@@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;\nimport java.util.Objects;\n-public abstract class PathPattern extends MemoizingStringValuePattern {\n+public abstract class PathPattern extends StringValuePattern {\nprotected final StringValuePattern valuePattern;\n@@ -38,7 +38,7 @@ public abstract class PathPattern extends MemoizingStringValuePattern {\n}\n@Override\n- protected MatchResult calculateMatch(String value) {\n+ public MatchResult match(String value) {\nif (isSimple()) {\nreturn isSimpleMatch(value);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMissCalculator.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMissCalculator.java", "diff": "package com.github.tomakehurst.wiremock.verification;\nimport com.github.tomakehurst.wiremock.matching.MatchResult;\n+import com.github.tomakehurst.wiremock.matching.MemoizingMatchResult;\nimport com.github.tomakehurst.wiremock.matching.RequestPattern;\nimport com.github.tomakehurst.wiremock.stubbing.*;\nimport com.google.common.base.Function;\n@@ -52,7 +53,7 @@ public class NearMissCalculator {\nreturn sortAndTruncate(from(allMappings).transform(new Function<StubMapping, NearMiss>() {\npublic NearMiss apply(StubMapping stubMapping) {\n- MatchResult matchResult = stubMapping.getRequest().match(request);\n+ MatchResult matchResult = new MemoizingMatchResult(stubMapping.getRequest().match(request));\nString actualScenarioState = getScenarioStateOrNull(stubMapping);\nreturn new NearMiss(request, stubMapping, matchResult, actualScenarioState);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/ignored/MassiveNearMissTest.java", "new_path": "src/test/java/ignored/MassiveNearMissTest.java", "diff": "@@ -37,12 +37,12 @@ public class MassiveNearMissTest {\n}\nfinal int drop = 2;\n- final int reps = 30;\n+ final int reps = 10;\nList<Long> times = new ArrayList<>(reps);\nlong sum = 0;\nfor (int i = 0; i < reps; i++) {\nStopwatch stopwatch = Stopwatch.createStarted();\n- client.postXml(\"/things/blah123/\" + (stubs / 2), \"<?xml version=\\\"1.0\\\"?><things />\");\n+ client.postXml(\"/things/blah123/\" + (stubs / 2), \"<?xml version=\\\"1.0\\\"?><things id=\\\"\" + i + \"\\\"/>\");\nstopwatch.stop();\nlong time = stopwatch.elapsed(MILLISECONDS);\ntimes.add(time);\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Fixed #1375 - removed memoization of string value pattern matches, as this is severly detrimental to performance for some workloads and causes unbounded heap growth
686,936
10.09.2020 15:18:16
-3,600
56d7a087a3d28685c8d797636e8e5e263fbfcff3
Added memoization to match results during request -> stub near miss calculation
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMissCalculator.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/verification/NearMissCalculator.java", "diff": "@@ -73,7 +73,7 @@ public class NearMissCalculator {\nList<ServeEvent> serveEvents = requestJournal.getAllServeEvents();\nreturn sortAndTruncate(from(serveEvents).transform(new Function<ServeEvent, NearMiss>() {\npublic NearMiss apply(ServeEvent serveEvent) {\n- MatchResult matchResult = requestPattern.match(serveEvent.getRequest());\n+ MatchResult matchResult = new MemoizingMatchResult(requestPattern.match(serveEvent.getRequest()));\nreturn new NearMiss(serveEvent.getRequest(), requestPattern, matchResult);\n}\n}), serveEvents.size());\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added memoization to match results during request -> stub near miss calculation
686,936
24.09.2020 20:31:25
-3,600
2b7f786bf3302df8f1654d53eeb7607aa2304269
Removed openjdk7 from the Travis build matrix
[ { "change_type": "MODIFY", "old_path": ".travis.yml", "new_path": ".travis.yml", "diff": "@@ -4,7 +4,6 @@ dist: trusty\njdk:\n- oraclejdk8\n- - openjdk7\n- openjdk8\ninstall:\n@@ -12,5 +11,5 @@ install:\n- JAVA_HOME=$(jdk_switcher home openjdk8) ./gradlew classes testClasses -x generateApiDocs\nscript:\n- - if [[ $TRAVIS_JDK_VERSION == *\"8\"* ]]; then ./gradlew -c release-settings.gradle :java8:check --stacktrace --no-daemon; else ./gradlew -c release-settings.gradle :java7:check --stacktrace --no-daemon; fi\n+ - ./gradlew check --stacktrace --no-daemon\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed openjdk7 from the Travis build matrix
686,936
25.09.2020 11:36:06
-3,600
f96f18a98af21621404325c22d5025c3a5196c28
Removed test dependencies from generated Maven POM
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -303,6 +303,10 @@ task writeThinJarPom {\nartifactId = jar.baseName\n}\nproject(pomInfo)\n+ }.whenConfigured { MavenPom pom ->\n+ pom.dependencies.removeAll { dependency ->\n+ dependency.scope == 'test'\n+ }\n}.writeTo(thinJarPomPath)\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed test dependencies from generated Maven POM
686,950
02.10.2020 10:26:01
-7,200
788c0cff96b3cfb8d4d3b974c4090be9783a0f90
fixing typo as requested in
[ { "change_type": "MODIFY", "old_path": "docs-v2/_docs/record-playback.md", "new_path": "docs-v2/_docs/record-playback.md", "diff": "@@ -386,7 +386,7 @@ If you want to always match request bodies with `equalTo` case-insensitively, re\n```json\n\"requestBodyPattern\" : {\n\"matcher\": \"equalTo\",\n- \"caseInsenstivie\" : true\n+ \"caseInsensitive\" : true\n}\n```\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
fixing typo as requested in #1382 (#1387)
686,976
12.10.2020 11:43:49
-7,200
f96383e461db2ef6234fc87fd082d1ced21430c6
updates httpclient version to 4.5.13
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -62,7 +62,7 @@ dependencies {\ncompile \"com.fasterxml.jackson.core:jackson-core:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-annotations:$versions.jackson\",\n\"com.fasterxml.jackson.core:jackson-databind:$versions.jacksonDatabind\"\n- compile \"org.apache.httpcomponents:httpclient:4.5.12\"\n+ compile \"org.apache.httpcomponents:httpclient:4.5.13\"\ncompile \"org.xmlunit:xmlunit-core:$versions.xmlUnit\"\ncompile \"org.xmlunit:xmlunit-legacy:$versions.xmlUnit\", {\nexclude group: 'junit', module: 'junit'\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
updates httpclient version to 4.5.13 (#1393) Co-authored-by: Kacper Jonczyk <kacper.jonczyk@ocado.com>
686,936
07.01.2021 17:34:44
0
4395c283d2e0b199eae03e20b80a571866c4573c
Added link to mock REST API tutorial on mocklab.io
[ { "change_type": "MODIFY", "old_path": "docs-v2/external-resources/index.md", "new_path": "docs-v2/external-resources/index.md", "diff": "@@ -112,3 +112,5 @@ CDN:<br>\n## MockLab\n[Build a Paypal sandbox for load testing in 10 minutes](https://www.mocklab.io/blog/build-a-paypal-sandbox-for-load-testing/)\n+\n+[Mock REST API tutorial](https://www.mocklab.io/docs/mock-rest-api/)\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added link to mock REST API tutorial on mocklab.io
687,059
19.04.2021 06:18:47
25,200
ff6108ef09fc0406e70a03e6ce34e2274a1d5140
Add Typescript client to external resources
[ { "change_type": "MODIFY", "old_path": "docs-v2/external-resources/index.md", "new_path": "docs-v2/external-resources/index.md", "diff": "@@ -63,6 +63,9 @@ Python client by Cody Lee:<br>\nNodeJS wrapper:<br>\n[https://www.npmjs.com/package/wiremock](https://www.npmjs.com/package/wiremock)\n+NodeJS + TypeScript client:<br>\n+[https://www.npmjs.com/package/wiremock-captain](https://www.npmjs.com/package/wiremock-captain)\n+\n## Articles\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Add Typescript client to external resources
686,936
20.04.2021 11:36:07
-3,600
64294f0a2a39c3eb308734d5bb73b6c6e16dc49a
Upgraded Jetty to 9.4.40 and restored MITM proxying by creating a 3rd Jetty connector (associated with the CA-based SSL factory) with a subclass of Jetty's ConnectHandler, configured to route requests to the new connector instead of the target host:port
[ { "change_type": "MODIFY", "old_path": "build.gradle", "new_path": "build.gradle", "diff": "@@ -35,7 +35,8 @@ repositories {\ndef jacksonVersion = '2.11.0'\ndef versions = [\nhandlebars : '4.2.0',\n- jetty : '9.4.30.v20200611',\n+// jetty : '9.4.34.v20201102', // Last working version\n+ jetty : '9.4.40.v20210413',\nguava : '29.0-jre',\njackson : jacksonVersion,\njacksonDatabind: jacksonVersion,\n@@ -56,7 +57,7 @@ dependencies {\ncompile \"org.eclipse.jetty:jetty-alpn-conscrypt-client:$versions.jetty\", {\nexclude group: 'org.conscrypt'\n}\n- compile 'org.conscrypt:conscrypt-openjdk-uber:2.2.1'\n+ compile 'org.conscrypt:conscrypt-openjdk-uber:2.5.2'\ncompile \"com.google.guava:guava:$versions.guava\"\ncompile \"com.fasterxml.jackson.core:jackson-core:$versions.jackson\",\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/core/Options.java", "diff": "@@ -41,7 +41,7 @@ public interface Options {\nint DEFAULT_PORT = 8080;\nint DYNAMIC_PORT = 0;\n- int DEFAULT_CONTAINER_THREADS = 14;\n+ int DEFAULT_CONTAINER_THREADS = 25;\nString DEFAULT_BIND_ADDRESS = \"0.0.0.0\";\nint portNumber();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java", "diff": "@@ -99,11 +99,15 @@ public class JettyHttpServer implements HttpServer {\nhttpsConnector = null;\n}\n+ applyAdditionalServerConfiguration(jettyServer, options);\n+\njettyServer.setHandler(createHandler(options, adminRequestHandler, stubRequestHandler));\nfinalizeSetup(options);\n}\n+ protected void applyAdditionalServerConfiguration(Server jettyServer, Options options) {}\n+\nprotected HandlerCollection createHandler(Options options, AdminRequestHandler adminRequestHandler, StubRequestHandler stubRequestHandler) {\nNotifier notifier = options.notifier();\nServletContextHandler adminContext = addAdminContext(\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/Jetty94HttpServer.java", "diff": "@@ -9,14 +9,19 @@ import com.github.tomakehurst.wiremock.jetty9.DefaultMultipartRequestConfigurer;\nimport com.github.tomakehurst.wiremock.jetty9.JettyHttpServer;\nimport com.github.tomakehurst.wiremock.servlet.MultipartRequestConfigurer;\nimport org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;\n+import org.eclipse.jetty.http.HttpVersion;\nimport org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;\nimport org.eclipse.jetty.io.NetworkTrafficListener;\nimport org.eclipse.jetty.server.*;\nimport org.eclipse.jetty.server.handler.HandlerCollection;\nimport org.eclipse.jetty.util.ssl.SslContextFactory;\n+import static com.github.tomakehurst.wiremock.jetty94.SslContexts.buildManInTheMiddleSslContextFactory;\n+\npublic class Jetty94HttpServer extends JettyHttpServer {\n+ private ServerConnector mitmProxyConnector;\n+\npublic Jetty94HttpServer(Options options, AdminRequestHandler adminRequestHandler, StubRequestHandler stubRequestHandler) {\nsuper(options, adminRequestHandler, stubRequestHandler);\n}\n@@ -73,10 +78,57 @@ public class Jetty94HttpServer extends JettyHttpServer {\nHandlerCollection handler = super.createHandler(options, adminRequestHandler, stubRequestHandler);\nif (options.browserProxySettings().enabled()) {\n- handler.addHandler(SslContexts.buildManInTheMiddleSslConnectHandler(options));\n+ handler.addHandler(new ManInTheMiddleSslConnectHandler(mitmProxyConnector));\n}\nreturn handler;\n}\n+ @Override\n+ protected void applyAdditionalServerConfiguration(Server jettyServer, Options options) {\n+ if (options.browserProxySettings().enabled()) {\n+ final SslConnectionFactory ssl = new SslConnectionFactory(\n+ buildManInTheMiddleSslContextFactory(options.httpsSettings(), options.browserProxySettings(), options.notifier()),\n+ /*\n+ If the proxy CONNECT request is made over HTTPS, and the\n+ actual content request is made using HTTP/2 tunneled over\n+ HTTPS, and an exception is thrown, the server blocks for 30\n+ seconds before flushing the response.\n+\n+ To fix this, force HTTP/1.1 over TLS when tunneling HTTPS.\n+\n+ This also means the HTTP mitmProxyConnector does not need the alpn &\n+ h2 connection factories as it will not use them.\n+\n+ Unfortunately it has proven too hard to write a test to\n+ demonstrate the bug; it requires an HTTP client capable of\n+ doing ALPN & HTTP/2, which will only offer HTTP/1.1 in the\n+ ALPN negotiation when using HTTPS for the initial CONNECT\n+ request but will then offer both HTTP/1.1 and HTTP/2 for the\n+ actual request (this is how curl 7.64.1 behaves!). Neither\n+ Apache HTTP 4, 5, 5 Async, OkHttp, nor the Jetty client\n+ could do this. It might be possible to write one using\n+ Netty, but it would be hard and time consuming.\n+ */\n+ HttpVersion.HTTP_1_1.asString()\n+ );\n+\n+ HttpConfiguration httpConfig = createHttpConfig(options.jettySettings());\n+ HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);\n+ mitmProxyConnector = new NetworkTrafficServerConnector(\n+ jettyServer,\n+ null,\n+ null,\n+ null,\n+ 2,\n+ 2,\n+ ssl,\n+ http\n+ );\n+\n+ mitmProxyConnector.setPort(0);\n+\n+ jettyServer.addConnector(mitmProxyConnector);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/ManInTheMiddleSslConnectHandler.java", "diff": "package com.github.tomakehurst.wiremock.jetty94;\n-import org.eclipse.jetty.io.Connection;\n-import org.eclipse.jetty.io.EndPoint;\n-import org.eclipse.jetty.server.Connector;\n-import org.eclipse.jetty.server.HttpChannel;\n-import org.eclipse.jetty.server.Request;\n-import org.eclipse.jetty.server.SslConnectionFactory;\n-import org.eclipse.jetty.server.handler.AbstractHandler;\n+import org.eclipse.jetty.proxy.ConnectHandler;\n+import org.eclipse.jetty.server.*;\n+import org.eclipse.jetty.util.Promise;\nimport javax.servlet.http.HttpServletRequest;\n-import javax.servlet.http.HttpServletResponse;\n-import java.io.IOException;\n+import java.io.Closeable;\n+import java.net.InetSocketAddress;\n+import java.nio.channels.SocketChannel;\n-import static org.eclipse.jetty.http.HttpMethod.CONNECT;\n+import static com.google.common.base.MoreObjects.firstNonNull;\n-/**\n- * A Handler for the HTTP CONNECT method that, instead of opening up a\n- * TCP tunnel between the downstream and upstream sockets, turns the connection\n- * into an SSL connection allowing this server to handle it.\n- */\n-class ManInTheMiddleSslConnectHandler extends AbstractHandler {\n+public class ManInTheMiddleSslConnectHandler extends ConnectHandler {\n- private final SslConnectionFactory sslConnectionFactory;\n+ private final ServerConnector mitmProxyConnector;\n- ManInTheMiddleSslConnectHandler(SslConnectionFactory sslConnectionFactory) {\n- this.sslConnectionFactory = sslConnectionFactory;\n+ public ManInTheMiddleSslConnectHandler(ServerConnector mitmProxyConnector) {\n+ this.mitmProxyConnector = mitmProxyConnector;\n}\n@Override\n- protected void doStart() throws Exception {\n- super.doStart();\n- sslConnectionFactory.start();\n- }\n+ protected void connectToServer(HttpServletRequest request, String ignoredHost, int ignoredPort, Promise<SocketChannel> promise) {\n+ SocketChannel channel = null;\n+ try\n+ {\n+ channel = SocketChannel.open();\n+ channel.socket().setTcpNoDelay(true);\n+ channel.configureBlocking(false);\n- @Override\n- protected void doStop() throws Exception {\n- super.doStop();\n- sslConnectionFactory.stop();\n- }\n+ String host = firstNonNull(mitmProxyConnector.getHost(), \"localhost\");\n+ int port = mitmProxyConnector.getLocalPort();\n+ InetSocketAddress address = newConnectAddress(host, port);\n- @Override\n- public void handle(\n- String target,\n- Request baseRequest,\n- HttpServletRequest request,\n- HttpServletResponse response\n- ) throws IOException {\n- if (CONNECT.is(request.getMethod())) {\n- baseRequest.setHandled(true);\n- handleConnect(baseRequest, response);\n+ channel.connect(address);\n+ promise.succeeded(channel);\n}\n+ catch (Throwable x)\n+ {\n+ close(channel);\n+ promise.failed(x);\n}\n-\n- private void handleConnect(\n- Request baseRequest,\n- HttpServletResponse response\n- ) throws IOException {\n- sendConnectResponse(response);\n-\n- HttpChannel httpChannel = baseRequest.getHttpChannel();\n- Connector connector = httpChannel.getConnector();\n- EndPoint endpoint = httpChannel.getEndPoint();\n- endpoint.setConnection(null);\n-\n- Connection connection = sslConnectionFactory.newConnection(connector, endpoint);\n- endpoint.setConnection(connection);\n-\n- endpoint.onOpen();\n- connection.onOpen();\n}\n- private void sendConnectResponse(HttpServletResponse response) throws IOException {\n- response.setStatus(HttpServletResponse.SC_OK);\n- response.getOutputStream().close();\n+ private void close(Closeable closeable)\n+ {\n+ try\n+ {\n+ if (closeable != null)\n+ closeable.close();\n+ }\n+ catch (Throwable x)\n+ {\n+ LOG.ignore(x);\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/jetty94/SslContexts.java", "diff": "@@ -23,36 +23,6 @@ import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked;\npublic class SslContexts {\n- public static ManInTheMiddleSslConnectHandler buildManInTheMiddleSslConnectHandler(Options options) {\n- return new ManInTheMiddleSslConnectHandler(\n- new SslConnectionFactory(\n- buildManInTheMiddleSslContextFactory(options.httpsSettings(), options.browserProxySettings(), options.notifier()),\n- /*\n- If the proxy CONNECT request is made over HTTPS, and the\n- actual content request is made using HTTP/2 tunneled over\n- HTTPS, and an exception is thrown, the server blocks for 30\n- seconds before flushing the response.\n-\n- To fix this, force HTTP/1.1 over TLS when tunneling HTTPS.\n-\n- This also means the HTTP connector does not need the alpn &\n- h2 connection factories as it will not use them.\n-\n- Unfortunately it has proven too hard to write a test to\n- demonstrate the bug; it requires an HTTP client capable of\n- doing ALPN & HTTP/2, which will only offer HTTP/1.1 in the\n- ALPN negotiation when using HTTPS for the initial CONNECT\n- request but will then offer both HTTP/1.1 and HTTP/2 for the\n- actual request (this is how curl 7.64.1 behaves!). Neither\n- Apache HTTP 4, 5, 5 Async, OkHttp, nor the Jetty client\n- could do this. It might be possible to write one using\n- Netty, but it would be hard and time consuming.\n- */\n- HttpVersion.HTTP_1_1.asString()\n- )\n- );\n- }\n-\npublic static SslContextFactory.Server buildHttp2SslContextFactory(HttpsSettings httpsSettings) {\nSslContextFactory.Server sslContextFactory = SslContexts.defaultSslContextFactory(httpsSettings.keyStore());\nsslContextFactory.setKeyManagerPassword(httpsSettings.keyManagerPassword());\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/standalone/CommandLineOptionsTest.java", "diff": "@@ -259,9 +259,9 @@ public class CommandLineOptionsTest {\n}\n@Test\n- public void defaultsContainerThreadsTo14() {\n+ public void defaultsContainerThreadsTo25() {\nCommandLineOptions options = new CommandLineOptions();\n- assertThat(options.containerThreads(), is(14));\n+ assertThat(options.containerThreads(), is(25));\n}\n@Test\n" }, { "change_type": "MODIFY", "old_path": "src/test/resources/log4j.properties", "new_path": "src/test/resources/log4j.properties", "diff": "-log4j.rootLogger=WARN, stdout\n+log4j.rootLogger=DEBUG, stdout\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.target=System.out\n@@ -6,3 +6,5 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n\nlog4j.logger.org.apache.http.wire=DEBUG\n+log4j.logger.org.eclipse.jetty.util.thread=WARN\n+log4j.logger.org.eclipse.jetty.util.component=WARN\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Upgraded Jetty to 9.4.40 and restored MITM proxying by creating a 3rd Jetty connector (associated with the CA-based SSL factory) with a subclass of Jetty's ConnectHandler, configured to route requests to the new connector instead of the target host:port
686,936
22.04.2021 16:27:37
-3,600
8ff728ed4d2c775b2664cb81e72fe7984a813917
Removed some redundant imports that also break Java 11 compilation
[ { "change_type": "MODIFY", "old_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSource.java", "new_path": "src/main/java/com/github/tomakehurst/wiremock/common/ssl/KeyStoreSource.java", "diff": "package com.github.tomakehurst.wiremock.common.ssl;\nimport com.github.tomakehurst.wiremock.common.Source;\n-import com.google.common.io.ByteStreams;\n-import org.apache.commons.codec.digest.DigestUtils;\n-import javax.xml.bind.DatatypeConverter;\n-import java.io.ByteArrayInputStream;\n-import java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.KeyStore;\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Removed some redundant imports that also break Java 11 compilation
686,936
22.04.2021 17:46:55
-3,600
e9d2e10ba54a43a5df3df86c5a193fe140f51cec
Switched to using a GitHub action to switch Node versions
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build-and-test.yml", "new_path": ".github/workflows/build-and-test.yml", "diff": "@@ -29,8 +29,10 @@ jobs:\ndistribution: 'adopt'\n- name: Grant execute permission for gradlew\nrun: chmod +x gradlew\n- - name: Set up NVM\n- run: rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install 8.12.0\n+ - name: Set up node using nvm\n+ uses: dcodeIO/setup-node-nvm@v4\n+ with:\n+ node-version: 8.12.0\n- name: Pre-generate API docs\nrun: ./gradlew classes testClasses -x generateApiDocs\n- name: Test WireMock\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Switched to using a GitHub action to switch Node versions
686,936
22.04.2021 17:47:45
-3,600
24d45551531130c4c9913840adc5e21d56441ea0
Limit the build to just JDK 8 for the time being (we know 11 has failing tests)
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build-and-test.yml", "new_path": ".github/workflows/build-and-test.yml", "diff": "@@ -15,7 +15,7 @@ jobs:\nfail-fast: false\nmatrix:\nos: [ubuntu-latest, macos-latest, windows-latest]\n- jdk: [8, 11]\n+ jdk: [8]\nruns-on: ${{ matrix.os }}\nenv:\nJDK_VERSION: ${{ matrix.jdk }}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Limit the build to just JDK 8 for the time being (we know 11 has failing tests)
686,936
22.04.2021 18:03:59
-3,600
e6de9743446d9b3a6d3b389cb8db7cad76d94e4c
Added some more tolerance in HTTPS tests for varying exception classes thrown, since this varies between JVM versions (and even patch versions of JDK 8)
[ { "change_type": "MODIFY", "old_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java", "new_path": "src/test/java/com/github/tomakehurst/wiremock/HttpsAcceptanceTest.java", "diff": "@@ -43,6 +43,7 @@ import org.junit.Test;\nimport org.junit.rules.ExpectedException;\nimport javax.net.ssl.SSLContext;\n+import javax.net.ssl.SSLException;\nimport javax.net.ssl.SSLHandshakeException;\nimport java.io.File;\nimport java.io.FileInputStream;\n@@ -123,9 +124,15 @@ public class HttpsAcceptanceTest {\naResponse()\n.withFault(Fault.CONNECTION_RESET_BY_PEER)));\n- exception.expect(SocketException.class);\n- exception.expectMessage(\"Connection reset\");\n+ try {\nhttpClient.execute(new HttpGet(url(\"/connection/reset\"))).getEntity();\n+ fail(\"Expected a SocketException or SSLException to be thrown\");\n+ } catch (Exception e) {\n+ assertThat(e.getClass().getName(), Matchers.anyOf(\n+ is(SocketException.class.getName()),\n+ is(SSLException.class.getName())\n+ ));\n+ }\n}\n@Test\n@@ -210,9 +217,13 @@ public class HttpsAcceptanceTest {\ntry {\ncontentFor(url(\"/https-test\")); // this lacks the required client certificate\n- fail(\"Expected a SocketException or SSLHandshakeException to be thrown\");\n+ fail(\"Expected a SocketException, SSLHandshakeException or SSLException to be thrown\");\n} catch (Exception e) {\n- assertThat(e.getClass().getName(), Matchers.anyOf(is(SocketException.class.getName()), is(SSLHandshakeException.class.getName())));\n+ assertThat(e.getClass().getName(), Matchers.anyOf(\n+ is(SocketException.class.getName()),\n+ is(SSLHandshakeException.class.getName()),\n+ is(SSLException.class.getName())\n+ ));\n}\n}\n" } ]
Java
Apache License 2.0
tomakehurst/wiremock
Added some more tolerance in HTTPS tests for varying exception classes thrown, since this varies between JVM versions (and even patch versions of JDK 8)