fix(apigatewayv2): trust Floci's own CA when fetching a JWT issuer's keys (#5933)

With TLS on, an issuer Floci serves itself, a Floci Cognito user pool for
one, presents a certificate of Floci's local CA. The JWT verifier fetched
its discovery document and JWKS with the JVM's default trust store, which
does not hold that CA, so every token of a Floci pool was refused with 401
by an HTTP API JWT authorizer (and by an AppSync OIDC provider), where the
same authorizer on a Cognito pool verifies on AWS.
FLOCI_SECURITY_ALLOW_PRIVATE_JWT_TARGETS only lets the fetch reach the
private address; the handshake still failed.

The verifier now trusts the CA bundle Floci already writes for the
containers it launches: the JVM's roots followed by Floci's own trust
anchor (the local CA, or the user's certificate file). ContainerCaBundle
gains sslContext(), an SSL context over that bundle, empty when TLS is off
or the bundle cannot be read, in which case the JVM's roots alone are
trusted as before. A readable bundle with no certificate in it is refused
the same way, since a trust store over it would trust nothing, public
issuers included. The warning for a missing bundle now also says that JWT
authorizers will refuse an issuer Floci serves.

The TLS server context of a certificate this CA issues moves from the RDS
proxy into FlociCertificateAuthority.serverSslContext, so the proxy and
the test that serves an issuer over HTTPS build it one way.

Tests: JwtSignatureVerifierTest serves an issuer over HTTPS with a
certificate Floci's CA issues, the bundle written by ContainerCaBundle and
the verifier built through its injected constructor, as in production:
refused by the JVM's roots, verified with the bundle (it fails on main).
ContainerCaBundleTest pins that the bundle's context still trusts every
JVM root and the anchor, and that an empty bundle falls back.
OidcAuthValidatorTest's mocked config now answers tls().
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-18 09:46:40 -04:00
1 parent 83bc2bd2bf
commit a90482f030
9 files changed
+258 -50

No files matched your search

@@ -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());
@@ -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.
@@ -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 {
@Inject
public 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))
@@ -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();
}