diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 3920d71854..141ff88e69 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -60,7 +60,7 @@ Running Floci directly on a Linux host (not in a container) with services that s | `FLOCI_TLS_ENABLED` | `false` | Enable TLS/HTTPS on all endpoints (HTTP remains available simultaneously) | | `FLOCI_TLS_CERT_PATH` | _(none)_ | Path to a PEM certificate file. When set, disables auto-generation | | `FLOCI_TLS_KEY_PATH` | _(none)_ | Path to a PEM private key file. Required when `FLOCI_TLS_CERT_PATH` is set | -| `FLOCI_TLS_EXTRA_CA_PATH` | _(none)_ | Path to a PEM file of extra CA certificates that Floci's own outbound HTTPS clients (EventBridge API destinations, JWT issuer fetch) trust on top of the JVM's roots. Works with TLS on or off; containers Floci launches do not receive them | +| `FLOCI_TLS_EXTRA_CA_PATH` | _(none)_ | Path to a PEM file of extra CA certificates that Floci's own outbound HTTPS clients (EventBridge API destinations, SNS HTTPS subscriptions, JWT issuer fetch) trust on top of the JVM's roots. Works with TLS on or off; containers Floci launches do not receive them | | `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate and persist a server certificate signed by Floci's local CA when no cert/key paths are provided | See [TLS / HTTPS](./tls.md) for SDK configuration examples and WebSocket (`wss://`) support. diff --git a/docs/configuration/tls.md b/docs/configuration/tls.md index c4bfdb34af..4c738517ce 100644 --- a/docs/configuration/tls.md +++ b/docs/configuration/tls.md @@ -128,7 +128,7 @@ When custom certificate paths are provided, `FLOCI_TLS_SELF_SIGNED` is ignored a ## Trusting Your Own CAs for Outbound Calls -Some calls go out from Floci itself: an EventBridge API destination delivering an event, or Floci fetching a JWT issuer's keys. When the endpoint's certificate is issued by a private or corporate CA, Floci refuses it by default, because Floci trusts only the root CAs built into its Java runtime. Floci does not read the operating system's trust store, so adding the CA there (`update-ca-trust`, `update-ca-certificates`) has no effect. +Some calls go out from Floci itself: an EventBridge API destination delivering an event, SNS posting to an HTTPS subscription, or Floci fetching a JWT issuer's keys. When the endpoint's certificate is issued by a private or corporate CA, Floci refuses it by default, because Floci trusts only the root CAs built into its Java runtime. Floci does not read the operating system's trust store, so adding the CA there (`update-ca-trust`, `update-ca-certificates`) has no effect. Point `FLOCI_TLS_EXTRA_CA_PATH` (config key `floci.tls.extra-ca-path`) at a PEM file holding those CA certificates: @@ -145,7 +145,7 @@ services: - It works whether or not `FLOCI_TLS_ENABLED` is set. Floci does not need to serve HTTPS itself. - The CAs are added to what Floci already trusts: the JVM's root CAs, and Floci's own CA when TLS is enabled. Public endpoints keep working. -- Floci's own clients that use them: EventBridge API destination delivery, and the JWT issuer fetch for HTTP API JWT authorizers and AppSync OIDC providers. +- Floci's own clients that use them: EventBridge API destination delivery, SNS HTTPS subscriptions (the subscription confirmation and notification delivery), and the JWT issuer fetch for HTTP API JWT authorizers and AppSync OIDC providers. - Containers Floci launches do not receive these CAs. They keep `/etc/floci-ca-bundle.pem` exactly as described in [Containers Floci Launches](#containers-floci-launches); a workload that calls such an endpoint itself configures its own CAs. - The file may hold several certificates. A private key kept in it is ignored. - A file that is missing, unreadable, or holds no certificate stops Floci at startup with a message naming the path, however the setting is given. diff --git a/src/main/java/io/floci/aws/services/sns/SnsService.java b/src/main/java/io/floci/aws/services/sns/SnsService.java index b26c6ee5b7..2f08581df3 100644 --- a/src/main/java/io/floci/aws/services/sns/SnsService.java +++ b/src/main/java/io/floci/aws/services/sns/SnsService.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.ContainerCaBundle; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; @@ -43,6 +44,7 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import javax.net.ssl.SSLContext; import java.io.IOException; import java.math.BigDecimal; import java.net.InetAddress; @@ -215,7 +217,8 @@ public class SnsService implements Resettable, ResourceProvider { firehoseService, config.effectiveBaseUrl(), objectMapper, - messageSigner + messageSigner, + ContainerCaBundle.sslContext(config).orElse(null) ); } @@ -336,6 +339,22 @@ public class SnsService implements Resettable, ResourceProvider { RegionResolver regionResolver, SqsService sqsService, LambdaService lambdaService, FirehoseService firehoseService, String baseUrl, ObjectMapper objectMapper, SnsMessageSigner messageSigner) { + this(topicStore, subscriptionStore, platformAppStore, platformEndpointStore, smsStore, + smsAttributesStore, smsSandboxStore, regionResolver, sqsService, lambdaService, + firehoseService, baseUrl, objectMapper, messageSigner, null); + } + + private SnsService(StorageBackend topicStore, + StorageBackend subscriptionStore, + StorageBackend platformAppStore, + StorageBackend platformEndpointStore, + StorageBackend smsStore, + StorageBackend> smsAttributesStore, + StorageBackend smsSandboxStore, + RegionResolver regionResolver, SqsService sqsService, + LambdaService lambdaService, FirehoseService firehoseService, + String baseUrl, ObjectMapper objectMapper, SnsMessageSigner messageSigner, + SSLContext sslContext) { this.topicStore = topicStore; this.subscriptionStore = subscriptionStore; this.platformAppStore = platformAppStore; @@ -349,14 +368,23 @@ public class SnsService implements Resettable, ResourceProvider { this.firehoseService = firehoseService; this.baseUrl = baseUrl; this.objectMapper = objectMapper; - // Pin to HTTP/1.1 like AWS SNS: the default HTTP_2 sends an h2c upgrade to http:// endpoints. - this.httpClient = HttpClient.newBuilder() - .version(HttpClient.Version.HTTP_1_1) - .connectTimeout(Duration.ofSeconds(5)) - .build(); + this.httpClient = deliveryClient(sslContext); this.messageSigner = messageSigner; } + // The client HTTP and HTTPS subscriptions are posted to. Pin to HTTP/1.1 like AWS SNS: the default + // HTTP_2 sends an h2c upgrade to http:// endpoints. sslContext, when given, adds the extra CAs in + // floci.tls.extra-ca-path, and Floci's CA when TLS is on, to the JVM's roots + private static HttpClient deliveryClient(SSLContext sslContext) { + HttpClient.Builder builder = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) + .connectTimeout(Duration.ofSeconds(5)); + if (sslContext != null) { + builder.sslContext(sslContext); + } + return builder.build(); + } + public void clear() { pushCapture.clear(); fifoDeduplicationCache.clear(); diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerApiDestinationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerApiDestinationTest.java index 87658341aa..9b5dfe9004 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerApiDestinationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerApiDestinationTest.java @@ -28,6 +28,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import static io.floci.aws.testing.LocalHttpsServer.hookUrl; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -149,7 +150,7 @@ class EventBridgeInvokerApiDestinationTest { void deliversToAnEndpointWhoseCertificateChainsToAnExtraCa(@TempDir Path dir) throws Exception { FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("private-ca")); AtomicInteger delivered = new AtomicInteger(); - HttpsServer server = httpsEndpoint(privateCa, delivered); + HttpsServer server = LocalHttpsServer.hook(privateCa, exchange -> delivered.incrementAndGet()); try { assertRefused(hookUrl(server), Optional.empty(), delivered); @@ -166,7 +167,7 @@ class EventBridgeInvokerApiDestinationTest { 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); + HttpsServer server = LocalHttpsServer.hook(privateCa, exchange -> delivered.incrementAndGet()); try { assertRefused(hookUrl(server), Optional.of(unrelatedCa.certificatePath().toString()), delivered); } finally { @@ -186,10 +187,6 @@ class EventBridgeInvokerApiDestinationTest { 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 extraCaPath) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); @@ -208,19 +205,6 @@ class EventBridgeInvokerApiDestinationTest { 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", diff --git a/src/test/java/io/floci/aws/services/sns/SnsHttpsSubscriptionTrustTest.java b/src/test/java/io/floci/aws/services/sns/SnsHttpsSubscriptionTrustTest.java new file mode 100644 index 0000000000..dd74f1bdc0 --- /dev/null +++ b/src/test/java/io/floci/aws/services/sns/SnsHttpsSubscriptionTrustTest.java @@ -0,0 +1,118 @@ +package io.floci.aws.services.sns; + +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.RegionResolver; +import io.floci.aws.testing.LocalHttpsServer; +import io.floci.aws.testing.StorageFactories; +import io.floci.aws.testutil.LogCapture; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.logging.LogRecord; + +import static io.floci.aws.testing.LocalHttpsServer.hookUrl; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +/** + * An HTTPS subscription's endpoint is reached through Floci's outbound trust, so a certificate from a CA in + * floci.tls.extra-ca-path is accepted, with TLS off. + */ +class SnsHttpsSubscriptionTrustTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String BASE_URL = "http://localhost:4566"; + + @TempDir + Path dir; + + /** + * An endpoint whose certificate chains to a private CA is refused while only the JVM's roots are trusted, and + * gets the SubscriptionConfirmation once that CA is in the floci.tls.extra-ca-path file. + */ + @Test + void sendsTheConfirmationToAnEndpointWhoseCertificateChainsToAnExtraCa() throws Exception { + FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("private-ca")); + BlockingQueue received = new LinkedBlockingQueue<>(); + HttpsServer server = httpsEndpoint(privateCa, received); + try { + assertRefused(hookUrl(server), Optional.empty(), received); + + subscribe(hookUrl(server), Optional.of(privateCa.certificatePath().toString())); + assertEquals("SubscriptionConfirmation", received.poll(5, TimeUnit.SECONDS)); + } 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() throws Exception { + FlociCertificateAuthority privateCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("private-ca")); + FlociCertificateAuthority unrelatedCa = FlociCertificateAuthority.loadOrCreate(dir.resolve("unrelated-ca")); + BlockingQueue received = new LinkedBlockingQueue<>(); + HttpsServer server = httpsEndpoint(privateCa, received); + try { + assertRefused(hookUrl(server), Optional.of(unrelatedCa.certificatePath().toString()), received); + } finally { + server.stop(0); + } + } + + // Asserts that subscribing endpoint fails the TLS handshake, so the endpoint never sees a request. + private void assertRefused(String endpoint, Optional extraCaPath, BlockingQueue received) { + LogCapture.awaitRecord(SnsService.class, Duration.ofSeconds(5), record -> refuses(record, endpoint), () -> { + subscribe(endpoint, extraCaPath); + return null; + }); + assertTrue(received.isEmpty(), "the endpoint got " + received); + } + + // Whether record is the warning that a send to endpoint failed its TLS handshake. + private static boolean refuses(LogRecord record, String endpoint) { + Object[] parameters = record.getParameters(); + return record.getMessage().contains("Failed to reach SNS endpoint") + && parameters != null && parameters.length == 2 + && endpoint.equals(parameters[0]) + && String.valueOf(parameters[1]).contains("SSLHandshakeException"); + } + + // Subscribes endpoint over HTTPS to a new topic, with extraCaPath as the extra CA setting. + private void subscribe(String endpoint, Optional extraCaPath) { + SnsService service = service(extraCaPath); + String topicArn = service.createTopic("trust", null, null, REGION).getTopicArn(); + service.subscribe(topicArn, "https", endpoint, REGION, Map.of()); + } + + // A service built the way CDI builds it, with TLS off. + private SnsService service(Optional extraCaPath) { + EmulatorConfig config = StorageFactories.config(dir.resolve("data"), ACCOUNT); + when(config.effectiveBaseUrl()).thenReturn(BASE_URL); + when(config.tls().enabled()).thenReturn(false); + when(config.tls().extraCaPath()).thenReturn(extraCaPath); + return new SnsService(StorageFactories.open(config, "memory"), config, new RegionResolver(REGION, ACCOUNT), + null, null, null, new ObjectMapper(), SnsMessageSigner.inMemory(BASE_URL)); + } + + // A localhost HTTPS endpoint serving a certificate ca issued, queueing the SNS message type of each request. + private static HttpsServer httpsEndpoint(FlociCertificateAuthority ca, BlockingQueue received) + throws Exception { + return LocalHttpsServer.hook(ca, exchange -> { + List type = exchange.getRequestHeaders().get("x-amz-sns-message-type"); + received.add(type == null ? "" : type.get(0)); + }); + } +} diff --git a/src/test/java/io/floci/aws/testing/LocalHttpsServer.java b/src/test/java/io/floci/aws/testing/LocalHttpsServer.java index 006c344f6e..fc7f037e99 100644 --- a/src/test/java/io/floci/aws/testing/LocalHttpsServer.java +++ b/src/test/java/io/floci/aws/testing/LocalHttpsServer.java @@ -1,5 +1,6 @@ package io.floci.aws.testing; +import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import io.floci.aws.config.FlociCertificateAuthority; @@ -9,6 +10,7 @@ import io.floci.aws.services.acm.model.KeyAlgorithm; import java.net.InetSocketAddress; import java.util.List; +import java.util.function.Consumer; /** 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 { @@ -25,4 +27,22 @@ public final class LocalHttpsServer { Pem.parseCertificate(issued.certificatePem()), Pem.parsePrivateKey(issued.privateKeyPem())))); return server; } + + /** Started, passing each request to {@code /hook} to {@code onRequest} and answering it with 200. */ + public static HttpsServer hook(FlociCertificateAuthority ca, Consumer onRequest) throws Exception { + HttpsServer server = issuedBy(ca); + server.createContext("/hook", exchange -> { + exchange.getRequestBody().readAllBytes(); + onRequest.accept(exchange); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + server.start(); + return server; + } + + /** The URL of {@code server}'s {@code /hook}, by the name its certificate is issued for. */ + public static String hookUrl(HttpsServer server) { + return "https://localhost:" + server.getAddress().getPort() + "/hook"; + } }