Skip to content

Commit

Permalink
test(server): fix ApplyConfigurationTest.java
Browse files Browse the repository at this point in the history
  • Loading branch information
NiccoMlt committed Oct 2, 2024
1 parent 3cde657 commit f093d48
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ public static Certificate[] readChainFromKeystore(byte[] data) throws GeneralSec
* @throws CertificateException if any of the certificates in the keystore could not be loaded
*/
public static Certificate[] readChainFromKeystore(KeyStore keystore) throws GeneralSecurityException {
if (keystore == null) {
return new Certificate[0];
}
Iterator<String> iter = keystore.aliases().asIterator();
while (iter.hasNext()) {
Certificate[] chain = keystore.getCertificateChain(iter.next());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ public SniMapper(
) {
this.parent = parent;
/*
* todo I don't think we actually need to store these data that should already be in the `parent`...
* sadly, this breaks reload of configuration after replacing the ConfigurationStore;
* todo:
* I don't think we actually need to store these data that should already be in the `parent`...
* sadly, this breaks the reload of the configuration after replacing the ConfigurationStore;
* one problem at a time though, this should be a different GitHub issue!
*/
this.runtimeConfiguration = runtimeConfiguration;
Expand Down Expand Up @@ -82,9 +83,10 @@ public SslContext computeContext(final String sniHostname) throws ConfigurationN
final var defaultCertificate = listenerConfiguration.getDefaultCertificate();
var chosen = Listeners.chooseCertificate(runtimeConfiguration, sniHostname, defaultCertificate);
if (chosen == null) {
throw new ConfigurationNotValidException("cannot find a certificate for snihostname " + sniHostname
+ ", with default cert for listener as '" + defaultCertificate
+ "', available " + runtimeConfiguration.getCertificates().keySet());
throw new ConfigurationNotValidException(
"cannot find a certificate for snihostname " + sniHostname
+ ", with default cert for listener as '" + defaultCertificate
+ "', available " + runtimeConfiguration.getCertificates().keySet());
}
int port = listenerConfiguration.getPort() + parent.getListenersOffsetPort();
try {
Expand Down Expand Up @@ -156,6 +158,7 @@ private List<String> getSslCiphers() {
}
return null;
}

public Consumer<SslProvider.SslContextSpec> sslContextSpecConsumer() {
return this::configureSpec;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import static java.util.function.Predicate.not;
import static org.carapaceproxy.configstore.ConfigurationStoreUtils.base64DecodeCertificateChain;
import static org.carapaceproxy.configstore.ConfigurationStoreUtils.base64EncodeCertificateChain;
import static org.carapaceproxy.core.ssl.CertificatesUtils.isCertificateExpired;
import static org.carapaceproxy.core.ssl.CertificatesUtils.readChainFromKeystore;
import static org.carapaceproxy.server.certificates.DynamicCertificateState.AVAILABLE;
import static org.carapaceproxy.server.certificates.DynamicCertificateState.DNS_CHALLENGE_WAIT;
import static org.carapaceproxy.server.certificates.DynamicCertificateState.DOMAIN_UNREACHABLE;
Expand All @@ -32,8 +34,6 @@
import static org.carapaceproxy.server.certificates.DynamicCertificateState.VERIFYING;
import static org.carapaceproxy.server.certificates.DynamicCertificateState.WAITING;
import static org.carapaceproxy.server.config.SSLCertificateConfiguration.CertificateMode.MANUAL;
import static org.carapaceproxy.core.ssl.CertificatesUtils.isCertificateExpired;
import static org.carapaceproxy.core.ssl.CertificatesUtils.readChainFromKeystore;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FileOutputStream;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.carapaceproxy.utils.ApacheHttpUtils.createHttpClientWithDisabledSSLValidation;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.aMapWithSize;
import static org.hamcrest.Matchers.allOf;
Expand All @@ -40,18 +42,10 @@
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Properties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.carapaceproxy.configstore.PropertiesConfigurationStore;
import org.carapaceproxy.core.HttpProxyServer;
import org.carapaceproxy.server.config.ConfigurationChangeInProgressException;
Expand Down Expand Up @@ -84,23 +78,14 @@ public class ApplyConfigurationTest {
public static void setupWireMock() {
stubFor(get(urlEqualTo("/index.html?redir"))
.willReturn(aResponse()
.withStatus(200)
.withStatus(HttpStatus.SC_OK)
.withHeader("Content-Type", "text/html")
.withHeader("Pragma", "no-cache")
.withHeader("Connection", "close")
.withBody("it <b>works</b> !!")));

}

private static CloseableHttpClient createHttpClientWithDisabledSSLValidation() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
return HttpClients.custom()
.setSSLContext(SSLContextBuilder.create()
.loadTrustMaterial((chain, authType) -> true) // Trust all certificates
.build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) // Disable hostname verification
.build();
}

@Test
public void testChangeListenersConfig() throws Exception {
try (HttpProxyServer server = new HttpProxyServer(null, tmpDir.newFolder())) {
Expand Down Expand Up @@ -173,19 +158,19 @@ public void testChangeListenersConfig() throws Exception {
"listener.2.sslprotocols", "TLSv1.2,TLSv1.3"
)));

// Test HTTPS for listener 1
testIt(1423, true, true); // Expecting valid HTTPS connection
// Test HTTPS for listener 2
testIt(1426, true, true); // Expecting valid HTTPS connection
// Expecting valid HTTPS connection
testIt(1423, true, true);
testIt(1426, true, true);

// listener with default tls version
reloadConfiguration(server, propsWithMapperAndCertificate(defaultCertificate, Map.of(
"listener.1.host", "localhost",
"listener.1.port", "1423",
"listener.1.ssl", "true"
)));
// Test HTTPS for listener 1
testIt(1423, true, true); // Expecting valid HTTPS connection

// Expecting valid HTTPS connection
testIt(1423, true, true);

// listener with wrong tls version
final IllegalStateException e = assertThrows(IllegalStateException.class, () ->
Expand Down Expand Up @@ -369,21 +354,19 @@ private void testIt(int port, boolean ok) throws Exception {
}

private void testIt(int port, final boolean https, boolean ok) throws Exception {
try (CloseableHttpClient client = createHttpClientWithDisabledSSLValidation()) {
final String protocol = https ? "https" : "http";
String url = protocol + "://localhost:" + port + "/index.html?redir";
try (final var client = createHttpClientWithDisabledSSLValidation()) {
final var protocol = https ? "https" : "http";
final var url = protocol + "://localhost:" + port + "/index.html?redir";

HttpGet request = new HttpGet(new URI(url));
try (CloseableHttpResponse response = client.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8);
final var request = new HttpGet(new URI(url));
try (final var response = client.execute(request)) {
final var statusCode = response.getStatusLine().getStatusCode();
final var responseBody = new String(response.getEntity().getContent().readAllBytes(), UTF_8);

System.out.println("RES FOR: " + url + " -> " + responseBody);

// Check that the response body matches what we expect
assertEquals("it <b>works</b> !!", responseBody);

if (!ok && statusCode == 200) {
if (!ok && statusCode == HttpStatus.SC_OK) {
fail("Expecting an error for port " + port);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.carapaceproxy.utils;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;

public class ApacheHttpUtils {

public static CloseableHttpClient createHttpClientWithDisabledSSLValidation() throws Exception {
return HttpClients.custom()
.setSSLContext(SSLContextBuilder.create()
.loadTrustMaterial((chain, authType) -> true) // Trust all certificates
.build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) // Disable hostname verification
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,21 @@
*/
package org.carapaceproxy.utils;

import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.Key;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.concurrent.Callable;
import org.junit.Assert;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.misc.Unsafe;

/**
Expand Down

0 comments on commit f093d48

Please sign in to comment.