Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigatewayv2): trust Floci's own CA when fetching a JWT issuer's keys (#5933)
Alessandro Lattaoa90482f03003
diff --git a/docs/configuration/tls.md b/docs/configuration/tls.mdindex 2f49b30f73..00f8b01c90 100644--- a/docs/configuration/tls.md+++ b/docs/configuration/tls.md@@ -99,7 +99,7 @@ Names are added by the custom domain operations: API Gateway `CreateDomainName`,### Containers Floci Launches-Every container Floci launches, from Lambda functions and ECS or Batch tasks to the Docker backends behind RDS, ElastiCache, MWAA and Flink, and the Kubernetes Lambda pods, receives `/etc/floci-ca-bundle.pem`: the public root CAs the Floci JVM trusts, followed by the Floci CA (or your certificate file when you provide one). `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` and `AWS_CA_BUNDLE` point at it, so curl, Python, Node.js, Go, the AWS CLI and the AWS SDKs that read `AWS_CA_BUNDLE` reach both Floci and public HTTPS sites with no setup in the workload. A variable you set on the function or task definition wins over the injected one. The JVM ignores all of these variables, so a Java workload still needs its own trust store, as shown under SDK Configuration Examples. The bundle is written to `{persistent-path}/tls/floci-ca-bundle.pem` at startup; when it is missing, or when an image has no `/etc` to copy it into, the container starts without the variables and Floci logs a warning.+Every container Floci launches, from Lambda functions and ECS or Batch tasks to the Docker backends behind RDS, ElastiCache, MWAA and Flink, and the Kubernetes Lambda pods, receives `/etc/floci-ca-bundle.pem`: the public root CAs the Floci JVM trusts, followed by the Floci CA (or your certificate file when you provide one). `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE`, `NODE_EXTRA_CA_CERTS` and `AWS_CA_BUNDLE` point at it, so curl, Python, Node.js, Go, the AWS CLI and the AWS SDKs that read `AWS_CA_BUNDLE` reach both Floci and public HTTPS sites with no setup in the workload. A variable you set on the function or task definition wins over the injected one. The JVM ignores all of these variables, so a Java workload still needs its own trust store, as shown under SDK Configuration Examples. The bundle is written to `{persistent-path}/tls/floci-ca-bundle.pem` at startup; when it is missing, or when an image has no `/etc` to copy it into, the container starts without the variables and Floci logs a warning. Floci trusts the same bundle when it fetches a JWT issuer's keys for an HTTP API authorizer or an AppSync OIDC provider, so an issuer it serves itself, a Cognito user pool for one, verifies over HTTPS.## User-Provided Certificatesdiff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.mdindex e98c152702..8f03dff012 100644--- a/docs/services/api-gateway.md+++ b/docs/services/api-gateway.md@@ -15,6 +15,12 @@ OIDC providers. The option permits private HTTPS targets and HTTP URLs that useor loopback address. It does not permit public HTTP targets. Keep it disabled when Floci canreceive untrusted API configuration.+With TLS enabled, an issuer Floci serves itself, such as a Floci Cognito user pool, presents a+certificate of Floci's local CA. The discovery document and JWKS are fetched trusting the same CA+bundle Floci gives the containers it launches (see [TLS](../configuration/tls.md)), so a JWT+authorizer on a Floci user pool verifies its tokens, as one on a Cognito user pool does on AWS. Its+address is still a private one, so it also needs `FLOCI_SECURITY_ALLOW_PRIVATE_JWT_TARGETS=true`.+## Custom API IDsAPI IDs are generated randomly, which means endpoint URLs change every time you recreate an API. To pindiff --git a/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java b/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.javaindex 952dd3783e..f61d4fd5b5 100644--- a/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java+++ b/src/main/java/io/github/hectorvent/floci/config/ContainerCaBundle.java@@ -5,6 +5,7 @@ import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;import org.bouncycastle.openssl.PEMParser;import org.jboss.logging.Logger;+import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.TrustManagerFactory;import javax.net.ssl.X509TrustManager;@@ -17,6 +18,7 @@ import java.nio.file.StandardCopyOption;import java.security.GeneralSecurityException;import java.security.KeyStore;import java.security.cert.CertificateEncodingException;+import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.Base64;@@ -111,7 +113,8 @@ public final class ContainerCaBundle {Path bundle = FlociCertificateAuthorityProducer.tlsDir(config).resolve(FILE_NAME);if (!Files.isReadable(bundle)) {if (MISSING_BUNDLE_WARNED.compareAndSet(false, true)) {- LOG.warnv("TLS is enabled but {0} is missing; containers launched now will not trust Floci HTTPS", bundle);+ LOG.warnv("TLS is enabled but {0} is missing; containers launched now will not trust Floci HTTPS,"+ + " and JWT authorizers will refuse an issuer Floci serves", bundle);} else {LOG.debugv("Container CA bundle {0} still missing", bundle);}@@ -153,6 +156,53 @@ public final class ContainerCaBundle {return merged;}+ /**+ * An SSL context that trusts what the bundle carries: the JVM's roots and Floci's own trust+ * anchor. For Floci's own outbound HTTPS to a URL Floci serves, such as a Cognito pool's issuer,+ * which on AWS is a public endpoint every client already trusts. Empty when there is no bundle,+ * or when it cannot be read, and the JVM's roots alone are trusted then.+ */+ public static Optional<SSLContext> sslContext(EmulatorConfig config) {+ Optional<Path> bundle = hostPath(config);+ if (bundle.isEmpty()) {+ return Optional.empty();+ }+ try {+ return Optional.of(sslContext(bundle.get()));+ } catch (IOException | GeneralSecurityException e) {+ LOG.warnv(e, "Cannot read {0}; Floci's own HTTPS clients trust the JVM's roots only", bundle.get());+ return Optional.empty();+ }+ }++ /**+ * An SSL context that trusts exactly the certificates in {@code bundle}.+ *+ * @throws CertificateException when the bundle holds no certificate: a context over it would+ * trust nothing, public endpoints included+ */+ public static SSLContext sslContext(Path bundle) throws IOException, GeneralSecurityException {+ SSLContext context = SSLContext.getInstance("TLS");+ context.init(null, trustManagers(bundle), null);+ return context;+ }++ /** The trust managers of {@link #sslContext(Path)}, over exactly the certificates in {@code bundle}. */+ static TrustManager[] trustManagers(Path bundle) throws IOException, GeneralSecurityException {+ List<X509Certificate> certificates = parseCertificates(Files.readString(bundle));+ if (certificates.isEmpty()) {+ throw new CertificateException(bundle + " holds no certificate");+ }+ KeyStore trustStore = KeyStore.getInstance("PKCS12");+ trustStore.load(null, null);+ for (int i = 0; i < certificates.size(); i++) {+ trustStore.setCertificateEntry("anchor-" + i, certificates.get(i));+ }+ TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ factory.init(trustStore);+ return factory.getTrustManagers();+ }+/** Every trust anchor the running JVM accepts by default. */private static List<X509Certificate> systemRoots() throws GeneralSecurityException {TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());diff --git a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.javaindex fe062668dc..a724a57171 100644--- a/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java+++ b/src/main/java/io/github/hectorvent/floci/config/FlociCertificateAuthority.java@@ -19,6 +19,9 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequest;import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;import org.jboss.logging.Logger;+import javax.net.ssl.KeyManagerFactory;+import javax.net.ssl.SSLContext;+import java.io.IOException;import java.io.StringReader;import java.nio.file.Files;@@ -26,9 +29,13 @@ import java.nio.file.Path;import java.nio.file.StandardCopyOption;import java.nio.file.attribute.PosixFileAttributeView;import java.nio.file.attribute.PosixFilePermissions;+import java.security.GeneralSecurityException;import java.security.KeyPair;+import java.security.KeyStore;import java.security.PrivateKey;import java.security.PublicKey;+import java.security.SecureRandom;+import java.security.cert.Certificate;import java.security.cert.X509Certificate;import java.time.Instant;import java.util.HexFormat;@@ -210,6 +217,23 @@ public final class FlociCertificateAuthority {CertificateGenerator.LeafUsage.SERVER);}+ /**+ * A TLS server context presenting {@code certificate}, issued by this CA, with its+ * {@code key}, the chain ending at this CA, so a client that trusts Floci's CA verifies it.+ */+ public SSLContext serverSslContext(X509Certificate certificate, PrivateKey key)+ throws GeneralSecurityException, IOException {+ char[] password = new char[0];+ KeyStore keyStore = KeyStore.getInstance("PKCS12");+ keyStore.load(null, password);+ keyStore.setKeyEntry("floci-server", key, password, new Certificate[]{certificate, certificate()});+ KeyManagerFactory keyManagers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());+ keyManagers.init(keyStore, password);+ SSLContext context = SSLContext.getInstance("TLS");+ context.init(keyManagers.getKeyManagers(), null, new SecureRandom());+ return context;+ }+/*** A {@code clientAuth} leaf for an IoT device: a fresh RSA 2048 key pair and, as on AWS, validity* until the end of 2049, never past the CA's own expiry.diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.javaindex 9c88e8944a..5ffc0ba2e3 100644--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifier.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigatewayv2;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.ContainerCaBundle;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.PublicKeys;import io.github.hectorvent.floci.core.common.SsrfProtection;@@ -16,11 +17,14 @@ import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;import org.apache.hc.client5.http.impl.classic.HttpClients;import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;+import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;import org.apache.hc.core5.http.io.entity.EntityUtils;import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;import org.apache.hc.core5.util.Timeout;import org.jboss.logging.Logger;+import javax.net.ssl.SSLContext;+import java.io.IOException;import java.math.BigInteger;import java.net.InetAddress;@@ -45,6 +49,11 @@ import java.util.concurrent.ConcurrentHashMap;* whatever issuer a JWT authorizer is configured with (Cognito, Auth0, Okta, ...), not a lookup* against Floci's own emulated Cognito keys.*+ * <p>With TLS on, an issuer Floci serves itself (a Cognito pool's URL) presents a certificate of+ * Floci's CA, which the JVM's default trust store does not hold. The issuer is fetched trusting the+ * CA bundle Floci gives every container it launches, so a JWT authorizer on a Floci pool verifies+ * its tokens as API Gateway verifies a Cognito pool's on AWS.+ ** <p>Per-issuer JWKS are cached (see {@link #CACHE_TTL}) so repeat requests to the same route* don't refetch the discovery document and key set on every call.*@@ -69,7 +78,7 @@ public class JwtSignatureVerifier implements AutoCloseable {@Injectpublic JwtSignatureVerifier(ObjectMapper objectMapper, EmulatorConfig config) {this(objectMapper, SystemDefaultDnsResolver.INSTANCE,- config.security().allowPrivateJwtTargets());+ config.security().allowPrivateJwtTargets(), ContainerCaBundle.sslContext(config).orElse(null));}/**@@ -79,6 +88,19 @@ public class JwtSignatureVerifier implements AutoCloseable {ObjectMapper objectMapper,DnsResolver dnsResolver,boolean allowPrivateNetworkTargets+ ) {+ this(objectMapper, dnsResolver, allowPrivateNetworkTargets, null);+ }++ /**+ * As above, trusting {@code sslContext}'s anchors over HTTPS, or the JVM's default ones when it+ * is null.+ */+ JwtSignatureVerifier(+ ObjectMapper objectMapper,+ DnsResolver dnsResolver,+ boolean allowPrivateNetworkTargets,+ SSLContext sslContext) {this.objectMapper = objectMapper;this.allowPrivateNetworkTargets = allowPrivateNetworkTargets;@@ -87,10 +109,15 @@ public class JwtSignatureVerifier implements AutoCloseable {.setConnectTimeout(Timeout.of(HTTP_TIMEOUT)).setSocketTimeout(Timeout.of(HTTP_TIMEOUT)).build();- PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()+ PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder.create().setDnsResolver(new JwtDnsResolver(dnsResolver, allowPrivateNetworkTargets))- .setDefaultConnectionConfig(connectionConfig)- .build();+ .setDefaultConnectionConfig(connectionConfig);+ if (sslContext != null) {+ connectionManagerBuilder.setTlsSocketStrategy(ClientTlsStrategyBuilder.create()+ .setSslContext(sslContext)+ .buildClassic());+ }+ PoolingHttpClientConnectionManager connectionManager = connectionManagerBuilder.build();RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(Timeout.of(HTTP_TIMEOUT)).setResponseTimeout(Timeout.of(HTTP_TIMEOUT))diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.javaindex 4a34f2e1e9..3996aec193 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyTlsCertificates.java@@ -11,16 +11,12 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;-import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;-import java.security.KeyStore;import java.security.PrivateKey;-import java.security.SecureRandom;-import java.security.cert.Certificate;import java.security.cert.X509Certificate;import java.time.Clock;import java.time.Instant;@@ -170,7 +166,7 @@ public class RdsProxyTlsCertificates {CertificateGenerator.LeafUsage.SERVER, notAfter);X509Certificate certificate = Pem.parseCertificate(generated.certificatePem());PrivateKey privateKey = Pem.parsePrivateKey(generated.privateKeyPem());- SSLContext context = buildSslContext(certificate, privateKey);+ SSLContext context = certificateAuthority.serverSslContext(certificate, privateKey);writeMetadata(tlsDir.resolve(METADATA_NAME), sanList);current = new ServerCertificate(context, Set.copyOf(sans), generated.notAfter());} catch (Exception e) {@@ -191,21 +187,6 @@ public class RdsProxyTlsCertificates {return !renewAt.isAfter(clock.instant());}- private SSLContext buildSslContext(X509Certificate certificate, PrivateKey privateKey) throws Exception {- char[] password = new char[0];- KeyStore keyStore = KeyStore.getInstance("PKCS12");- keyStore.load(null, password);- keyStore.setKeyEntry("floci-rds-proxy", privateKey, password,- new Certificate[]{certificate, certificateAuthority.certificate()});-- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());- keyManagerFactory.init(keyStore, password);-- SSLContext context = SSLContext.getInstance("TLS");- context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());- return context;- }-private Path tlsDir() {return certificateAuthority.certificatePath().getParent();}diff --git a/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java b/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.javaindex 7d1cd9c539..a896a9097c 100644--- a/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/ContainerCaBundleTest.java@@ -8,9 +8,14 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import javax.net.ssl.TrustManager;+import javax.net.ssl.TrustManagerFactory;+import javax.net.ssl.X509TrustManager;import java.io.ByteArrayInputStream;import java.nio.file.Files;import java.nio.file.Path;+import java.security.GeneralSecurityException;+import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.security.cert.X509Certificate;@@ -60,6 +65,34 @@ class ContainerCaBundleTest {assertEquals(1, certificates.stream().filter(ca.certificate()::equals).count());}+ /**+ * The SSL context trusts every root the JVM trusts, so a public issuer, such as a real+ * Cognito pool's, still validates, and Floci's own anchor besides.+ */+ @Test+ void theSslContextTrustsEveryJvmRootAndTheAnchor() throws Exception {+ Path tlsDir = tempDir.resolve("tls");+ 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());+ }+ }+ }+ assertTrue(accepted.contains(ca.certificate()), "Floci's anchor");+ }+@Testvoid writeIsIdempotent() throws Exception {Path tlsDir = tempDir.resolve("tls");@@ -101,6 +134,24 @@ class ContainerCaBundleTest {assertFalse(Files.exists(tlsDir.resolve("floci-ca-bundle.pem")));}+ /**+ * A bundle with no certificate in it would make a trust store that trusts nothing, and every+ * HTTPS call through it would fail, public endpoints included. Floci's own clients fall back to+ * the JVM's roots instead.+ */+ @Test+ void sslContextIsEmptyForABundleWithNoCertificate() throws Exception {+ Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));+ Files.writeString(tlsDir.resolve(ContainerCaBundle.FILE_NAME), "");+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ when(config.tls().enabled()).thenReturn(true);+ when(config.storage().persistentPath()).thenReturn(tempDir.toString());++ assertEquals(Optional.empty(), ContainerCaBundle.sslContext(config));+ assertThrows(GeneralSecurityException.class,+ () -> ContainerCaBundle.sslContext(tlsDir.resolve(ContainerCaBundle.FILE_NAME)));+ }+@Testvoid hostPathIsEmptyWhenTlsIsOff() {EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.javaindex be67e23b82..69e42fc6b1 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/JwtSignatureVerifierTest.java@@ -2,25 +2,42 @@ package io.github.hectorvent.floci.services.apigatewayv2;import com.fasterxml.jackson.databind.ObjectMapper;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.github.hectorvent.floci.config.ContainerCaBundle;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;+import io.github.hectorvent.floci.config.TlsConfigSource;import io.github.hectorvent.floci.core.common.Base64Url;+import io.github.hectorvent.floci.core.common.Pem;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;import org.apache.hc.client5.http.DnsResolver;import org.apache.hc.client5.http.SystemDefaultDnsResolver;+import org.bouncycastle.jce.provider.BouncyCastleProvider;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 java.io.IOException;import java.math.BigInteger;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.UnknownHostException;import java.nio.charset.StandardCharsets;+import java.nio.file.Path;import java.security.GeneralSecurityException;import java.security.KeyPair;import java.security.KeyPairGenerator;+import java.security.Security;import java.security.Signature;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;+import java.util.List;import java.util.Map;import java.util.concurrent.atomic.AtomicInteger;import java.util.function.Function;@@ -29,6 +46,9 @@ 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;/*** Verifies {@link JwtSignatureVerifier} against a real local OIDC discovery + JWKS server@@ -55,36 +75,25 @@ class JwtSignatureVerifierTest {publicKey = (RSAPublicKey) pair.getPublic();server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);-- server.createContext("/.well-known/openid-configuration", exchange -> {- String issuerUrl = "http://127.0.0.1:" + server.getAddress().getPort();- String body = "{\"issuer\":\"" + issuerUrl + "\",\"jwks_uri\":\"" + issuerUrl + "/jwks\"}";- byte[] bytes = body.getBytes(StandardCharsets.UTF_8);- exchange.getResponseHeaders().add("Content-Type", "application/json");- exchange.sendResponseHeaders(200, bytes.length);- exchange.getResponseBody().write(bytes);- exchange.close();- });-- server.createContext("/jwks", exchange -> {- String n = base64UrlUnsigned(publicKey.getModulus());- String e = base64UrlUnsigned(publicKey.getPublicExponent());- String body = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"test-key-1\",\"alg\":\"RS256\",\"use\":\"sig\","- + "\"n\":\"" + n + "\",\"e\":\"" + e + "\"}]}";- byte[] bytes = body.getBytes(StandardCharsets.UTF_8);- exchange.getResponseHeaders().add("Content-Type", "application/json");- exchange.sendResponseHeaders(200, bytes.length);- exchange.getResponseBody().write(bytes);- exchange.close();- });-- server.start();issuer = "http://127.0.0.1:" + server.getAddress().getPort();+ server.createContext("/.well-known/openid-configuration", discovery(issuer));+ server.createContext("/jwks", this::serveJwks);+ server.start();verifier = new JwtSignatureVerifier(objectMapper, SystemDefaultDnsResolver.INSTANCE, true);strictVerifier = new JwtSignatureVerifier(objectMapper, SystemDefaultDnsResolver.INSTANCE, false);}+ @BeforeEach+ @AfterEach+ void forgetBootstrapTlsDir() {+ // TlsConfigSource.resolvedTlsDir is static: a TLS-on bootstrap run by another test class+ // in this JVM would otherwise steer the bundle lookup at that test's directory.+ System.setProperty("floci.tls.enabled", "false");+ new TlsConfigSource();+ System.clearProperty("floci.tls.enabled");+ }+@AfterEachvoid tearDown() {verifier.close();@@ -268,6 +277,45 @@ class JwtSignatureVerifierTest {};}+ /**+ * With TLS on, the verifier Floci injects trusts the CA bundle it writes for its containers, so+ * an issuer served with a certificate of Floci's CA, as a Floci Cognito pool's is, verifies,+ * where the JVM's roots alone refuse it. Goes through the configuration and the bundle writer,+ * as production does.+ */+ @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);+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);+ when(config.tls().enabled()).thenReturn(true);+ when(config.storage().persistentPath()).thenReturn(dir.toString());+ when(config.security().allowPrivateJwtTargets()).thenReturn(true);++ 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()))));+ String httpsIssuer = "https://localhost:" + httpsServer.getAddress().getPort();+ httpsServer.createContext("/.well-known/openid-configuration", discovery(httpsIssuer));+ httpsServer.createContext("/jwks", this::serveJwks);+ httpsServer.start();+ try (JwtSignatureVerifier trustingVerifier = new JwtSignatureVerifier(objectMapper, config)) {+ String token = signToken("test-key-1", privateKey);++ assertThrows(JwtSignatureVerifier.JwtVerificationException.class,+ () -> verifier.verify(token, httpsIssuer));+ assertDoesNotThrow(() -> trustingVerifier.verify(token, httpsIssuer));+ } finally {+ httpsServer.stop(0);+ }+ }+@Testvoid doesNotFollowDiscoveryRedirects() throws Exception {AtomicInteger redirectedRequests = new AtomicInteger();@@ -295,6 +343,26 @@ class JwtSignatureVerifierTest {}}+ private static HttpHandler discovery(String issuerUrl) {+ return exchange -> respond(exchange,+ "{\"issuer\":\"" + issuerUrl + "\",\"jwks_uri\":\"" + issuerUrl + "/jwks\"}");+ }++ private void serveJwks(HttpExchange exchange) throws IOException {+ String n = base64UrlUnsigned(publicKey.getModulus());+ String e = base64UrlUnsigned(publicKey.getPublicExponent());+ respond(exchange, "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"test-key-1\",\"alg\":\"RS256\",\"use\":\"sig\","+ + "\"n\":\"" + n + "\",\"e\":\"" + e + "\"}]}");+ }++ private static void respond(HttpExchange exchange, String body) throws IOException {+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);+ exchange.getResponseHeaders().add("Content-Type", "application/json");+ exchange.sendResponseHeaders(200, bytes.length);+ exchange.getResponseBody().write(bytes);+ exchange.close();+ }+private String signToken(String kid, RSAPrivateKey signingKey) throws GeneralSecurityException {ObjectNode header = objectMapper.createObjectNode();header.put("alg", "RS256");diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.javaindex ed6fb022b8..bc49630dbe 100644--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/auth/OidcAuthValidatorTest.java@@ -70,6 +70,7 @@ class OidcAuthValidatorTest {EmulatorConfig.SecurityConfig securityConfig = mock(EmulatorConfig.SecurityConfig.class);when(config.security()).thenReturn(securityConfig);when(securityConfig.allowPrivateJwtTargets()).thenReturn(true);+ when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class));signatureVerifier = new JwtSignatureVerifier(mapper, config);validator = new OidcAuthValidator(new JwtClaimsDecoder(mapper), signatureVerifier,Clock.fixed(NOW, ZoneOffset.UTC));