mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eventbridge): trust extra CAs from FLOCI_TLS_EXTRA_CA_PATH for API destinations (#7850)
Add floci.tls.extra-ca-path (FLOCI_TLS_EXTRA_CA_PATH): a PEM file of CA certificates that Floci's own outbound HTTPS clients trust on top of the JVM's default roots, and Floci's CA when TLS is on. It applies whether or not TLS is enabled. ContainerCaBundle.sslContext(config) merges the extra CAs and is now also built with TLS off. floci-ca-bundle.pem and its .p12 are unchanged, so containers Floci launches are unaffected in both modes. EventBridge API destination delivery uses the context, and JwtSignatureVerifier already shares it, so HTTP API JWT authorizers and AppSync OIDC providers trust the extra CAs too. TlsExtraCaStartupValidator refuses to start when the file is missing, unreadable, or holds no certificate, from any config source. A private key in the file is ignored. Closes #5259 With floci.tls.extra-ca-path set and TLS on, a bundle that could not be read or parsed made outboundTrustAnchors throw. sslContext(config) then logged the extra CA file as the unreadable one, fell back to the bundle alone, failed on it again and returned empty, so the valid extra CAs were dropped. The bundle is now read on its own: on failure Floci warns with the bundle's path and trusts the JVM roots plus the extra CAs, as the sslContext(config) Javadoc already describes. ContainerCaBundle builds every SSL context and trust manager array from a KeyStore, so sslContext(Path), trustManagers(Path) and the extra-CA context no longer repeat the JCA calls. Tests share LocalHttpsServer in testing for the localhost HTTPS server issued by a CA, the two JWT issuer-trust cases share one helper, and the JVM roots check in ContainerCaBundleTest is written once. outboundTrustAnchors and trustStore(Path) now read a certificate file through one method, which also refuses a file with no certificate. In the tests added for the extra CA file, the certificate-and-key file comes from one helper in TlsTestSupport, the two missing-file cases are one parameterized test, and the refused EventBridge delivery is checked by one helper. TlsExtraCaStartupValidator now calls ContainerCaBundle.certificates instead of reading the file and checking for a certificate on its own. outboundTrustAnchors reads the bundle through the same method, and ContainerCaBundle.extraCaFile is the one place that decides whether the setting is set, for both the SSL context and the startup check. The startup message still names the path and gives the reason. Both EventBridgeInvoker constructors now get the API destination HttpClient from one method, which adds Floci's outbound SSL context when there is one.
This commit is contained in:
1 parent
65b09d0aac
commit
9f94fcc974
15 files changed
+611
-41
No files matched your search
@@ -1,20 +1,28 @@
|
||||
package io.floci.aws.config;
|
||||
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import io.floci.aws.core.common.Pem;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.acm.model.KeyAlgorithm;
|
||||
import io.floci.aws.services.lambda.launcher.BootstrapProcess;
|
||||
import io.floci.aws.testing.LocalHttpsServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.GeneralSecurityException;
|
||||
@@ -83,21 +91,9 @@ class ContainerCaBundleTest {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
Path bundle = ContainerCaBundle.write(tlsDir, ca.certificatePath());
|
||||
|
||||
List<X509Certificate> accepted = new ArrayList<>();
|
||||
for (TrustManager manager : ContainerCaBundle.trustManagers(bundle)) {
|
||||
if (manager instanceof X509TrustManager x509) {
|
||||
accepted.addAll(List.of(x509.getAcceptedIssuers()));
|
||||
}
|
||||
}
|
||||
TrustManagerFactory jvm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
jvm.init((KeyStore) null);
|
||||
for (TrustManager manager : jvm.getTrustManagers()) {
|
||||
if (manager instanceof X509TrustManager x509) {
|
||||
for (X509Certificate root : x509.getAcceptedIssuers()) {
|
||||
assertTrue(accepted.contains(root), root.getSubjectX500Principal().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
List<X509Certificate> accepted = acceptedIssuers(ContainerCaBundle.trustManagers(bundle));
|
||||
|
||||
assertHoldsEveryJvmRoot(accepted);
|
||||
assertTrue(accepted.contains(ca.certificate()), "Floci's anchor");
|
||||
}
|
||||
|
||||
@@ -160,6 +156,75 @@ class ContainerCaBundleTest {
|
||||
() -> ContainerCaBundle.sslContext(tlsDir.resolve(ContainerCaBundle.FILE_NAME)));
|
||||
}
|
||||
|
||||
/** The reported case: TLS off, and an endpoint whose certificate chains to a private CA in the extra file. */
|
||||
@Test
|
||||
void sslContextTrustsTheExtraCasWhenTlsIsOff() throws Exception {
|
||||
FlociCertificateAuthority privateCa = privateCa();
|
||||
EmulatorConfig config = config(false, Optional.of(privateCa.certificatePath().toString()));
|
||||
|
||||
Optional<SSLContext> context = ContainerCaBundle.sslContext(config);
|
||||
|
||||
assertTrue(context.isPresent(), "an extra CA file gives Floci's own clients a context with TLS off");
|
||||
assertTrue(handshakes(context.get(), privateCa), "the extra CA is trusted");
|
||||
}
|
||||
|
||||
/** The extra CAs are added to the JVM's roots, not swapped in for them, so public endpoints keep working. */
|
||||
@Test
|
||||
void theExtraCasComeOnTopOfEveryJvmRootWhenThereIsNoBundle() throws Exception {
|
||||
FlociCertificateAuthority privateCa = privateCa();
|
||||
|
||||
List<X509Certificate> anchors = ContainerCaBundle.outboundTrustAnchors(null, privateCa.certificatePath());
|
||||
|
||||
assertHoldsEveryJvmRoot(anchors);
|
||||
assertEquals(privateCa.certificate(), anchors.get(anchors.size() - 1), "the extra CA comes last");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sslContextTrustsTheBundleAndTheExtraCasWhenTlsIsOn() throws Exception {
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
FlociCertificateAuthority flociCa = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
ContainerCaBundle.write(tlsDir, flociCa.certificatePath());
|
||||
FlociCertificateAuthority privateCa = privateCa();
|
||||
EmulatorConfig config = config(true, Optional.of(privateCa.certificatePath().toString()));
|
||||
|
||||
SSLContext context = ContainerCaBundle.sslContext(config).orElseThrow();
|
||||
|
||||
assertTrue(handshakes(context, flociCa), "Floci's CA, from the bundle");
|
||||
assertTrue(handshakes(context, privateCa), "the extra CA");
|
||||
}
|
||||
|
||||
/** A damaged bundle costs Floci's CA, not the extra CAs: the JVM's roots stand in for the bundle. */
|
||||
@Test
|
||||
void sslContextKeepsTheExtraCasWhenTheBundleIsDamaged() throws Exception {
|
||||
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
|
||||
Files.writeString(tlsDir.resolve(ContainerCaBundle.FILE_NAME),
|
||||
"-----BEGIN CERTIFICATE-----\nnot a certificate\n-----END CERTIFICATE-----\n");
|
||||
FlociCertificateAuthority privateCa = privateCa();
|
||||
EmulatorConfig config = config(true, Optional.of(privateCa.certificatePath().toString()));
|
||||
|
||||
Optional<SSLContext> context = ContainerCaBundle.sslContext(config);
|
||||
|
||||
assertTrue(context.isPresent(), "the extra CAs survive a bundle that cannot be parsed");
|
||||
assertTrue(handshakes(context.get(), privateCa), "the extra CA is trusted");
|
||||
}
|
||||
|
||||
/** With TLS off and no extra CA, nothing changes: Floci's own clients keep the JVM's default context. */
|
||||
@Test
|
||||
void sslContextIsEmptyWhenTlsIsOffAndNoExtraCaIsSet() {
|
||||
assertEquals(Optional.empty(), ContainerCaBundle.sslContext(config(false, Optional.empty())));
|
||||
}
|
||||
|
||||
/** A combined certificate-and-key file is accepted; only its certificates are trusted, the key is skipped. */
|
||||
@Test
|
||||
void anExtraCaFileHoldingAPrivateKeyIsTrustedForItsCertificates() throws Exception {
|
||||
FlociCertificateAuthority privateCa = privateCa();
|
||||
Path withKey = TlsTestSupport.caWithPrivateKey(privateCa, tempDir.resolve("ca-and-key.pem"));
|
||||
|
||||
SSLContext context = ContainerCaBundle.sslContext(config(false, Optional.of(withKey.toString()))).orElseThrow();
|
||||
|
||||
assertTrue(handshakes(context, privateCa));
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostPathIsEmptyWhenTlsIsOff() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
@@ -424,6 +489,58 @@ class ContainerCaBundleTest {
|
||||
return ended.output();
|
||||
}
|
||||
|
||||
private FlociCertificateAuthority privateCa() {
|
||||
return FlociCertificateAuthority.loadOrCreate(tempDir.resolve("private-ca"));
|
||||
}
|
||||
|
||||
private EmulatorConfig config(boolean tlsEnabled, Optional<String> extraCaPath) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.tls().enabled()).thenReturn(tlsEnabled);
|
||||
when(config.tls().extraCaPath()).thenReturn(extraCaPath);
|
||||
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
|
||||
return config;
|
||||
}
|
||||
|
||||
// Whether a client over context completes a TLS handshake with a localhost server whose certificate ca issued.
|
||||
private static boolean handshakes(SSLContext context, FlociCertificateAuthority ca) throws Exception {
|
||||
HttpsServer server = LocalHttpsServer.issuedBy(ca);
|
||||
server.createContext("/", exchange -> {
|
||||
exchange.sendResponseHeaders(204, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
HttpClient client = HttpClient.newBuilder().sslContext(context).build();
|
||||
URI uri = URI.create("https://localhost:" + server.getAddress().getPort() + "/");
|
||||
return client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.discarding())
|
||||
.statusCode() == 204;
|
||||
} catch (SSLHandshakeException e) {
|
||||
return false;
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
// The issuers that managers accept, in order.
|
||||
private static List<X509Certificate> acceptedIssuers(TrustManager[] managers) {
|
||||
List<X509Certificate> issuers = new ArrayList<>();
|
||||
for (TrustManager manager : managers) {
|
||||
if (manager instanceof X509TrustManager x509) {
|
||||
issuers.addAll(List.of(x509.getAcceptedIssuers()));
|
||||
}
|
||||
}
|
||||
return issuers;
|
||||
}
|
||||
|
||||
// Asserts that anchors holds every root the running JVM trusts by default.
|
||||
private static void assertHoldsEveryJvmRoot(List<X509Certificate> anchors) throws GeneralSecurityException {
|
||||
TrustManagerFactory jvm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
jvm.init((KeyStore) null);
|
||||
for (X509Certificate root : acceptedIssuers(jvm.getTrustManagers())) {
|
||||
assertTrue(anchors.contains(root), root.getSubjectX500Principal().getName());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<X509Certificate> parseAll(byte[] pem) throws Exception {
|
||||
List<X509Certificate> certificates = new ArrayList<>();
|
||||
for (Certificate certificate : CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(pem))) {
|
||||
|
||||
@@ -6,8 +6,11 @@ import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyStore;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -29,9 +32,35 @@ class TlsConfigSourceContainerCaBundleTest {
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.tls.cert-path");
|
||||
System.clearProperty("floci.tls.key-path");
|
||||
System.clearProperty("floci.tls.extra-ca-path");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
}
|
||||
|
||||
/** Containers keep the bundle they had: the floci.tls.extra-ca-path CAs are for Floci's own clients only. */
|
||||
@Test
|
||||
void theBundleAndTrustStoreLeaveTheExtraCasOut() throws Exception {
|
||||
FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("private-ca"));
|
||||
Path persistent = Files.createDirectories(tempDir.resolve("data"));
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", persistent.toString());
|
||||
System.setProperty("floci.tls.extra-ca-path", privateCa.certificatePath().toString());
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
String bundle = Files.readString(persistent.resolve("tls/" + ContainerCaBundle.FILE_NAME));
|
||||
assertFalse(bundle.contains(privateCa.caPem().strip()), "the extra CA stays out of the PEM bundle");
|
||||
KeyStore trustStore = KeyStore.getInstance("PKCS12");
|
||||
try (InputStream in = Files.newInputStream(
|
||||
persistent.resolve("tls/" + ContainerCaBundle.JAVA_TRUST_STORE_FILE_NAME))) {
|
||||
trustStore.load(in, null);
|
||||
}
|
||||
for (String alias : Collections.list(trustStore.aliases())) {
|
||||
assertFalse(privateCa.certificate().equals(trustStore.getCertificate(alias)),
|
||||
"the extra CA stays out of the Java trust store");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void selfSignedBootWritesTheBundleEndingWithTheLocalCa() throws Exception {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.floci.aws.config;
|
||||
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The floci.tls.extra-ca-path file is checked at startup, from whichever source sets it, with TLS on or off.
|
||||
*/
|
||||
class TlsExtraCaStartupValidatorTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void aMissingExtraCaFileStopsTheStart(boolean tlsEnabled) {
|
||||
Path missing = tempDir.resolve("missing-ca.pem");
|
||||
|
||||
String refusal = refusal(tlsEnabled, missing.toString());
|
||||
|
||||
assertTrue(refusal.contains("not found or not readable: " + missing), refusal);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExtraCaFileWithoutACertificateStopsTheStart() throws Exception {
|
||||
Path empty = Files.writeString(tempDir.resolve("empty.pem"), "nothing to trust here\n");
|
||||
|
||||
String refusal = refusal(false, empty.toString());
|
||||
|
||||
assertTrue(refusal.contains(empty + " holds no certificate"), refusal);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExtraCaPathNamingADirectoryStopsTheStart() {
|
||||
String refusal = refusal(false, tempDir.toString());
|
||||
|
||||
assertTrue(refusal.contains(tempDir.toString()), refusal);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExtraCaFileWithACertificateLetsTheStartThrough() {
|
||||
FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("private-ca"));
|
||||
|
||||
assertDoesNotThrow(() -> start(Optional.of(privateCa.certificatePath().toString())));
|
||||
}
|
||||
|
||||
/** A combined certificate-and-key file passes on its certificate; the key is ignored. */
|
||||
@Test
|
||||
void anExtraCaFileHoldingAPrivateKeyLetsTheStartThrough() throws Exception {
|
||||
FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("private-ca"));
|
||||
Path withKey = TlsTestSupport.caWithPrivateKey(privateCa, tempDir.resolve("ca-and-key.pem"));
|
||||
|
||||
assertDoesNotThrow(() -> start(Optional.of(withKey.toString())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsetOrBlankExtraCaPathIsNotChecked() {
|
||||
assertDoesNotThrow(() -> start(Optional.empty()));
|
||||
assertDoesNotThrow(() -> start(Optional.of(" ")));
|
||||
}
|
||||
|
||||
// The message the startup check stops Floci with, with TLS as tlsEnabled says and extraCaPath set.
|
||||
private static String refusal(boolean tlsEnabled, String extraCaPath) {
|
||||
return assertThrows(IllegalStateException.class,
|
||||
() -> validator(tlsEnabled, Optional.of(extraCaPath)).onStart(new StartupEvent())).getMessage();
|
||||
}
|
||||
|
||||
// Runs the startup check with TLS off and extraCaPath as the setting.
|
||||
private static void start(Optional<String> extraCaPath) {
|
||||
validator(false, extraCaPath).onStart(new StartupEvent());
|
||||
}
|
||||
|
||||
private static TlsExtraCaStartupValidator validator(boolean tlsEnabled, Optional<String> extraCaPath) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.tls().enabled()).thenReturn(tlsEnabled);
|
||||
when(config.tls().extraCaPath()).thenReturn(extraCaPath);
|
||||
return new TlsExtraCaStartupValidator(config);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package io.floci.aws.config;
|
||||
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.acm.model.KeyAlgorithm;
|
||||
import io.floci.aws.testing.TlsTrust;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.List;
|
||||
@@ -17,6 +20,13 @@ final class TlsTestSupport {
|
||||
return TlsTrust.trusting(FlociCertificateAuthority.loadOrCreate(Path.of(SelfSignedTlsProfile.TLS_DIR)).certificate());
|
||||
}
|
||||
|
||||
// Writes the certificate of ca and then a private key to file, as a combined certificate-and-key file holds.
|
||||
static Path caWithPrivateKey(FlociCertificateAuthority ca, Path file) throws Exception {
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("floci", List.of("floci"),
|
||||
KeyAlgorithm.RSA_2048, null);
|
||||
return Files.writeString(file, ca.caPem() + leaf.privateKeyPem());
|
||||
}
|
||||
|
||||
static Set<String> dnsSans(X509Certificate certificate) throws Exception {
|
||||
Set<String> names = new TreeSet<>();
|
||||
for (List<?> entry : certificate.getSubjectAlternativeNames()) {
|
||||
|
||||
@@ -5,16 +5,13 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import io.floci.aws.config.ContainerCaBundle;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.FlociCertificateAuthority;
|
||||
import io.floci.aws.config.TlsConfigSource;
|
||||
import io.floci.aws.core.common.Base64Url;
|
||||
import io.floci.aws.core.common.Pem;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.acm.model.KeyAlgorithm;
|
||||
import io.floci.aws.testing.LocalHttpsServer;
|
||||
import org.apache.hc.client5.http.DnsResolver;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
@@ -38,8 +35,8 @@ import java.security.Signature;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
|
||||
@@ -286,22 +283,43 @@ class JwtSignatureVerifierTest {
|
||||
*/
|
||||
@Test
|
||||
void trustsAnIssuerCertificateFromTheCaBundleFlociWrites(@TempDir Path dir) throws Exception {
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
Path tlsDir = dir.resolve("tls");
|
||||
FlociCertificateAuthority authority = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
ContainerCaBundle.write(tlsDir, authority.certificatePath());
|
||||
CertificateGenerator.GeneratedCertificate issued = authority.issueServerCertificate(
|
||||
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048, null);
|
||||
|
||||
assertOnlyTheInjectedVerifierTrusts(authority, httpsIssuerConfig(dir, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* The JWT issuer fetch shares Floci's outbound SSL context, so an issuer whose certificate chains to a CA in
|
||||
* floci.tls.extra-ca-path verifies too, with TLS off.
|
||||
*/
|
||||
@Test
|
||||
void trustsAnIssuerCertificateFromAnExtraCaWithTlsOff(@TempDir Path dir) throws Exception {
|
||||
FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("private-ca"));
|
||||
EmulatorConfig config = httpsIssuerConfig(dir, false);
|
||||
when(config.tls().extraCaPath()).thenReturn(Optional.of(privateCa.certificatePath().toString()));
|
||||
|
||||
assertOnlyTheInjectedVerifierTrusts(privateCa, config);
|
||||
}
|
||||
|
||||
// A configuration with TLS as tlsEnabled says, persisting under dir, that lets the verifier reach localhost.
|
||||
private static EmulatorConfig httpsIssuerConfig(Path dir, boolean tlsEnabled) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.tls().enabled()).thenReturn(true);
|
||||
when(config.tls().enabled()).thenReturn(tlsEnabled);
|
||||
when(config.storage().persistentPath()).thenReturn(dir.toString());
|
||||
when(config.security().allowPrivateJwtTargets()).thenReturn(true);
|
||||
return config;
|
||||
}
|
||||
|
||||
HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
httpsServer.setHttpsConfigurator(new HttpsConfigurator(authority.serverSslContext(
|
||||
Pem.parseCertificate(issued.certificatePem()), Pem.parsePrivateKey(issued.privateKeyPem()))));
|
||||
// Asserts that an issuer serving a certificate ca issued is refused with the JVM's roots alone and verified by
|
||||
// the verifier Floci injects with config.
|
||||
private void assertOnlyTheInjectedVerifierTrusts(FlociCertificateAuthority ca, EmulatorConfig config)
|
||||
throws Exception {
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
HttpsServer httpsServer = LocalHttpsServer.issuedBy(ca);
|
||||
String httpsIssuer = "https://localhost:" + httpsServer.getAddress().getPort();
|
||||
httpsServer.createContext("/.well-known/openid-configuration", discovery(httpsIssuer));
|
||||
httpsServer.createContext("/jwks", this::serveJwks);
|
||||
|
||||
+96
@@ -1,18 +1,26 @@
|
||||
package io.floci.aws.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.config.FlociCertificateAuthority;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.eventbridge.model.ApiDestination;
|
||||
import io.floci.aws.services.eventbridge.model.Connection;
|
||||
import io.floci.aws.services.eventbridge.model.Target;
|
||||
import io.floci.aws.services.lambda.LambdaService;
|
||||
import io.floci.aws.services.sns.SnsService;
|
||||
import io.floci.aws.services.sqs.SqsService;
|
||||
import io.floci.aws.testing.LocalHttpsServer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
@@ -20,12 +28,20 @@ import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EventBridgeInvokerApiDestinationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DESTINATION_ARN = "arn:aws:events:us-east-1:000000000000:api-destination/tls/1";
|
||||
private static final String CONNECTION_ARN = "arn:aws:events:us-east-1:000000000000:connection/tls/1";
|
||||
|
||||
@Test
|
||||
void substitutePathParameters_replacesWildcardsInOrder() {
|
||||
assertEquals("https://api.example.com/a/one/b/two",
|
||||
@@ -125,6 +141,86 @@ class EventBridgeInvokerApiDestinationTest {
|
||||
assertTrue(granted.get() >= 5 && granted.get() <= 10, "granted " + granted.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* An endpoint whose certificate chains to a private CA is refused while only the JVM's roots are trusted, and
|
||||
* delivered to once that CA is in the floci.tls.extra-ca-path file, with TLS off as in the reported case.
|
||||
*/
|
||||
@Test
|
||||
void deliversToAnEndpointWhoseCertificateChainsToAnExtraCa(@TempDir Path dir) throws Exception {
|
||||
FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("private-ca"));
|
||||
AtomicInteger delivered = new AtomicInteger();
|
||||
HttpsServer server = httpsEndpoint(privateCa, delivered);
|
||||
try {
|
||||
assertRefused(hookUrl(server), Optional.empty(), delivered);
|
||||
|
||||
assertDoesNotThrow(() -> deliver(hookUrl(server), Optional.of(privateCa.certificatePath().toString())));
|
||||
assertEquals(1, delivered.get());
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** The extra CAs add trust; they do not loosen it: a CA the endpoint's certificate does not chain to is no help. */
|
||||
@Test
|
||||
void refusesAnEndpointWhoseCaIsNotInTheExtraCaFile(@TempDir Path dir) throws Exception {
|
||||
FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("private-ca"));
|
||||
FlociCertificateAuthority unrelatedCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("unrelated-ca"));
|
||||
AtomicInteger delivered = new AtomicInteger();
|
||||
HttpsServer server = httpsEndpoint(privateCa, delivered);
|
||||
try {
|
||||
assertRefused(hookUrl(server), Optional.of(unrelatedCa.certificatePath().toString()), delivered);
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
// Asserts that delivering to endpoint fails the TLS handshake, so the endpoint never sees a request.
|
||||
private static void assertRefused(String endpoint, Optional<String> extraCaPath, AtomicInteger delivered) {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> deliver(endpoint, extraCaPath));
|
||||
assertTrue(refused.getMessage().contains("SSLHandshakeException"), refused.getMessage());
|
||||
assertEquals(0, delivered.get());
|
||||
}
|
||||
|
||||
// Sends one event to the API destination at endpoint, with extraCaPath as the extra CA setting.
|
||||
private static void deliver(String endpoint, Optional<String> extraCaPath) {
|
||||
invoker(endpoint, extraCaPath).invokeTarget(apiDestinationTarget(), "{}", REGION);
|
||||
}
|
||||
|
||||
private static String hookUrl(HttpsServer server) {
|
||||
return "https://localhost:" + server.getAddress().getPort() + "/hook";
|
||||
}
|
||||
|
||||
// An invoker built the way CDI builds it, its API destination pointing at endpoint, with TLS off.
|
||||
private static EventBridgeInvoker invoker(String endpoint, Optional<String> extraCaPath) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.tls().enabled()).thenReturn(false);
|
||||
when(config.tls().extraCaPath()).thenReturn(extraCaPath);
|
||||
EventBridgeService eventBridgeService = mock(EventBridgeService.class);
|
||||
when(eventBridgeService.findApiDestinationByArn(DESTINATION_ARN, REGION)).thenReturn(
|
||||
new ApiDestination("tls", DESTINATION_ARN, CONNECTION_ARN, endpoint, "POST", null, null));
|
||||
when(eventBridgeService.findConnectionByArn(CONNECTION_ARN, REGION)).thenReturn(new Connection());
|
||||
return new EventBridgeInvoker(mock(LambdaService.class), mock(SqsService.class), mock(SnsService.class),
|
||||
null, null, eventBridgeService, null, null, null, null, null, null, null, new ObjectMapper(), config,
|
||||
(AppSyncTargetInvoker) null);
|
||||
}
|
||||
|
||||
private static Target apiDestinationTarget() {
|
||||
return new Target("tls-target", DESTINATION_ARN, null, null);
|
||||
}
|
||||
|
||||
// An HTTPS endpoint on localhost serving a certificate the CA issued, counting the requests to /hook.
|
||||
private static HttpsServer httpsEndpoint(FlociCertificateAuthority ca, AtomicInteger requests) throws Exception {
|
||||
HttpsServer server = LocalHttpsServer.issuedBy(ca);
|
||||
server.createContext("/hook", exchange -> {
|
||||
exchange.getRequestBody().readAllBytes();
|
||||
requests.incrementAndGet();
|
||||
exchange.sendResponseHeaders(200, -1);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
return server;
|
||||
}
|
||||
|
||||
private static ApiDestination rateLimited(String name, int limit) {
|
||||
return new ApiDestination(name, "arn:aws:events:us-east-1:000000000000:api-destination/" + name + "/1",
|
||||
"arn:aws:events:us-east-1:000000000000:connection/c/1", "https://api.example.com", "POST",
|
||||
|
||||
+1
@@ -352,6 +352,7 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
@Override public boolean enabled() { return false; }
|
||||
@Override public Optional<String> certPath() { return Optional.empty(); }
|
||||
@Override public Optional<String> keyPath() { return Optional.empty(); }
|
||||
@Override public Optional<String> extraCaPath() { return Optional.empty(); }
|
||||
@Override public boolean selfSigned() { return true; }
|
||||
@Override public int awsHttpsPort() { return 443; }
|
||||
};
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import io.floci.aws.config.FlociCertificateAuthority;
|
||||
import io.floci.aws.core.common.Pem;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.acm.model.KeyAlgorithm;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.List;
|
||||
|
||||
/** An HTTPS server on a free localhost port, so a test sees a client verify a certificate a given CA issued. */
|
||||
public final class LocalHttpsServer {
|
||||
|
||||
private LocalHttpsServer() {
|
||||
}
|
||||
|
||||
/** Bound and serving a localhost certificate {@code ca} issued; not started, so the caller adds its contexts. */
|
||||
public static HttpsServer issuedBy(FlociCertificateAuthority ca) throws Exception {
|
||||
CertificateGenerator.GeneratedCertificate issued = ca.issueServerCertificate(
|
||||
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048, null);
|
||||
HttpsServer server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.setHttpsConfigurator(new HttpsConfigurator(ca.serverSslContext(
|
||||
Pem.parseCertificate(issued.certificatePem()), Pem.parsePrivateKey(issued.privateKeyPem()))));
|
||||
return server;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user