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

@@ -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");
}
@Test
void 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)));
}
@Test
void hostPathIsEmptyWhenTlsIsOff() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -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");
}
@AfterEach
void 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);
}
}
@Test
void 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");
@@ -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));