feat: serve custom domains over TLS as soon as they are created (#3086)

* feat(tls): record runtime-learned hostnames in the certificate metadata

* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime

Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.

* feat(tls): keep runtime-learned hostnames across a boot regeneration

* test(tls): ensureHost is visible to the next TLS handshake without a restart

* docs(tls): custom domains learned at runtime

* test(tls): pin the certificate contracts of a runtime reissue

The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.

* fix(tls): retry a failed listener reload and keep served names across a boot

A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.

At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.

The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.

Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.

* fix(tls): carry a name whose reload failed into later reissues and resets

The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.

Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.

* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA

RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.

The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.

AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.

* refactor(acm): drop the cosmetic Amazon issuer generator

CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.

* docs(acm): certificates chain to the local CA

Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.

* test(acm): the SDK compatibility suite validates the certificate against its chain

GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.

* docs(acm): say when the CA is created and what Issuer reports

ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.

* test(acm): pin key size, an imported chain and the persisted chain

The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.

* test(acm): the python compatibility suite verifies the certificate against its chain

The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.

* fix(acm): write EC private keys as PKCS#8 and classify keys by interface

JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.

Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.

* test(acm): AcmServiceTest pins issuance from the local CA

Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.

* feat(apigateway): serve a custom domain over TLS as soon as it is created

CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.

* feat(iot): serve a customer-managed domain over TLS as soon as it is configured

CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.

* feat(cognito): serve a custom domain over TLS as soon as it is created

CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.

* docs: custom domains are served over TLS on creation

One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.

* test(compat): custom domain reachable over TLS trusting only the ACM chain

RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.

* docs(tls): say which ensureHost outcomes are logged as warnings

* test: pin the custom domain TLS hooks against the service contracts

Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.

* test(acm): build the InUseBy test service with the local CA

AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.

* test(cognito): request an issued ACM certificate in the custom domain TLS tests

Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.

* test(cognito): a concurrent create does not wait for the TLS reload

The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-05 22:05:40 -04:00
1 parent 1bf7494e99
commit 67bbd2cf13
49 files changed
+3317 -216

No files matched your search

@@ -0,0 +1,55 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
class CertificateMetadataTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void learnedHostnamesRoundTripThroughJson() throws Exception {
CertificateMetadata metadata = CertificateMetadata.create(List.of("localhost"), "dev");
metadata.setLearnedHostnames(List.of("api.example.localhost.floci.io"));
CertificateMetadata read = MAPPER.readValue(MAPPER.writeValueAsString(metadata), CertificateMetadata.class);
assertEquals(List.of("api.example.localhost.floci.io"), read.getLearnedHostnames());
assertEquals(List.of("localhost"), read.getHostnames(), "configured names stay apart from learned ones");
assertEquals(metadata, read);
}
@Test
void metadataWrittenBeforeTheFieldExistedReadsAsNoLearnedHostnames() throws Exception {
String legacyJson = "{\"hostnames\":[\"localhost\"],\"generatedAt\":\"2026-01-01T00:00:00Z\",\"flociVersion\":\"dev\"}";
CertificateMetadata read = MAPPER.readValue(legacyJson, CertificateMetadata.class);
assertEquals(List.of(), read.getLearnedHostnames());
}
@Test
void nullLearnedHostnamesReadAsEmpty() {
CertificateMetadata metadata = new CertificateMetadata();
metadata.setLearnedHostnames(null);
assertEquals(List.of(), metadata.getLearnedHostnames());
}
@Test
void learnedHostnamesTakePartInEquality() {
CertificateMetadata a = new CertificateMetadata(List.of("localhost"), "2026-01-01T00:00:00Z", "dev");
CertificateMetadata b = new CertificateMetadata(List.of("localhost"), "2026-01-01T00:00:00Z", "dev");
assertEquals(a, b);
b.setLearnedHostnames(List.of("api.example.localhost.floci.io"));
assertNotEquals(a, b);
assertNotEquals(a.hashCode(), b.hashCode());
}
}
@@ -0,0 +1,192 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.http.ContentType;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static io.github.hectorvent.floci.testing.RestAssuredJsonUtils.awsActionJson;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End to end, with TLS on and the real certificate manager: an ACM certificate is requested, the
* three custom domain operations are called over the wire with their normal responses, and a
* client that trusts only the chain ACM returned, sends each domain as SNI and verifies the
* server's identity for it completes the handshake, where it failed before the domain existed.
* A reset takes the names back. The fixture leaf carries no 127.0.0.1 SAN and the socket connects
* by IP, so the SNI name is the only one the identity check can match.
*/
@QuarkusTest
@TestProfile(CustomDomainTlsIntegrationTest.Profile.class)
class CustomDomainTlsIntegrationTest {
static final Path DATA_DIR = Path.of("target", "floci-custom-domain-tls-test").toAbsolutePath();
static final Path TLS_DIR = DATA_DIR.resolve("tls");
static final String API_DOMAIN = "api.custom-domain-it.localhost.floci.io";
static final String IOT_DOMAIN = "iot.custom-domain-it.localhost.floci.io";
static final String AUTH_DOMAIN = "auth.custom-domain-it.localhost.floci.io";
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
int sslPort;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void customDomainsAreServedUnderTheAcmChainAsSoonAsTheyExist() throws Exception {
JsonNode requested = awsActionJson("CertificateManager", "RequestCertificate",
"{\"DomainName\": \"*.custom-domain-it.localhost.floci.io\", \"ValidationMethod\": \"DNS\"}");
String certificateArn = requested.path("CertificateArn").asText();
String chain = awsActionJson("CertificateManager", "GetCertificate",
"{\"CertificateArn\": \"" + certificateArn + "\"}").path("CertificateChain").asText();
assertTrue(chain.contains("BEGIN CERTIFICATE"), chain);
for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) {
assertThrows(SSLHandshakeException.class, () -> handshake(chain, domain, true),
"precondition: " + domain + " is not served before it is created");
}
given().contentType(ContentType.JSON)
.body("{\"domainName\":\"" + API_DOMAIN + "\",\"regionalCertificateArn\":\"" + certificateArn + "\","
+ "\"endpointConfiguration\":{\"types\":[\"REGIONAL\"]}}")
.when().post("/domainnames").then().statusCode(201);
given().contentType(ContentType.JSON)
.body("{\"domainName\":\"" + IOT_DOMAIN + "\",\"serverCertificateArns\":[\"" + certificateArn + "\"]}")
.when().post("/domainConfigurations/custom-domain-it").then().statusCode(200);
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\": \"custom-domain-it\"}")
.path("UserPool").path("Id").asText();
JsonNode created = cognitoJson("CreateUserPoolDomain", "{\"Domain\": \"" + AUTH_DOMAIN + "\", \"UserPoolId\": \""
+ poolId + "\", \"CustomDomainConfig\": {\"CertificateArn\": \"" + certificateArn + "\"}}");
assertTrue(created.path("CloudFrontDomain").asText().endsWith(".cloudfront.net"), created.toString());
for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) {
X509Certificate served = handshake(chain, domain, true);
assertTrue(sans(served).contains(domain), domain + " not in " + sans(served));
assertEquals(parse(chain).get(0).getSubjectX500Principal(), served.getIssuerX500Principal(),
"the served leaf is issued by the CA in the ACM chain");
}
given().when().post("/_floci/state/reset").then().statusCode(200);
for (String domain : List.of(API_DOMAIN, IOT_DOMAIN, AUTH_DOMAIN)) {
assertThrows(SSLHandshakeException.class, () -> handshake(chain, domain, true),
"reset drops " + domain);
}
assertFalse(sans(handshake(chain, API_DOMAIN, false)).contains(API_DOMAIN));
}
/**
* TLS by IP trusting only {@code chainPem}, sending {@code sniHost} as SNI and, when asked,
* verifying the server's identity for that name the way an SDK does.
*/
private X509Certificate handshake(String chainPem, String sniHost, boolean verifyIdentity) throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
int i = 0;
for (X509Certificate ca : parse(chainPem)) {
trust.setCertificateEntry("chain-" + i++, ca);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trust);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
try (SSLSocket socket = (SSLSocket) ctx.getSocketFactory().createSocket()) {
socket.connect(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), sslPort), 5000);
SSLParameters params = socket.getSSLParameters();
params.setServerNames(List.of(new SNIHostName(sniHost)));
if (verifyIdentity) {
params.setEndpointIdentificationAlgorithm("HTTPS");
}
socket.setSSLParameters(params);
socket.startHandshake();
return (X509Certificate) socket.getSession().getPeerCertificates()[0];
}
}
private static List<X509Certificate> parse(String pem) throws Exception {
return CertificateFactory.getInstance("X.509")
.generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.UTF_8)))
.stream().map(X509Certificate.class::cast).toList();
}
private static Set<String> sans(X509Certificate leaf) throws Exception {
Set<String> sans = new TreeSet<>();
for (List<?> entry : leaf.getSubjectAlternativeNames()) {
sans.add(String.valueOf(entry.get(1)));
}
return sans;
}
/**
* Boots with TLS on and a CA-issued leaf like the one TlsConfigSource writes, in a directory
* of its own. The wildcard covers one label only, so the three-label names are uncovered
* until the operations add them.
*/
public static final class Profile implements QuarkusTestProfile {
static {
try {
Files.createDirectories(TLS_DIR);
for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {
Files.deleteIfExists(TLS_DIR.resolve(name));
}
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
List<String> sans = List.of("localhost", "*.localhost.floci.io");
var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());
Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());
Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),
new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));
} catch (IOException e) {
throw new IllegalStateException("could not prepare the TLS fixtures", e);
}
}
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.tls.enabled", "true",
"floci.tls.self-signed", "true",
"floci.tls.aws-https-port", "0",
"floci.storage.persistent-path", DATA_DIR.toString(),
"quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),
"quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),
"quarkus.http.insecure-requests", "enabled");
}
}
}
@@ -122,7 +122,8 @@ class FlociCertificateAuthorityTest {
@Test
void aLeafInPlaceOfTheCaIsRegenerated() throws Exception {
var leaf = new CertificateGenerator().generateCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048);
var leaf = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("another-ca"))
.issueServerCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null);
Files.writeString(tempDir.resolve("floci-root-ca.crt"), leaf.certificatePem());
Files.writeString(tempDir.resolve("floci-root-ca.key"), leaf.privateKeyPem());
@@ -190,7 +190,7 @@ class TlsCertificateHostnameTest {
// Generate certificate without metadata
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(
CertificateGenerator.GeneratedCertificate generated = gen.generateSelfSignedCertificate(
"localhost",
List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "localhost.floci.io", "*.localhost.floci.io"),
KeyAlgorithm.RSA_2048);
@@ -276,7 +276,7 @@ class TlsCertificateHostnameTest {
Path userKeyFile = tempDir.resolve("user-key.key");
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate userCert = gen.generateCertificate(
CertificateGenerator.GeneratedCertificate userCert = gen.generateSelfSignedCertificate(
"user-domain.com",
List.of("user-domain.com", "*.user-domain.com"),
KeyAlgorithm.RSA_2048);
@@ -390,7 +390,7 @@ class TlsCertificateHostnameTest {
Path userCert = tempDir.resolve("user.crt");
Path userKey = tempDir.resolve("user.key");
var user = new CertificateGenerator().generateCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
var user = new CertificateGenerator().generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
Files.writeString(userCert, user.certificatePem());
Files.writeString(userKey, user.privateKeyPem());
System.setProperty("floci.tls.enabled", "true");
@@ -0,0 +1,119 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.quarkus.tls.CertificateUpdatedEvent;
import io.quarkus.tls.TlsConfiguration;
import io.quarkus.tls.TlsConfigurationRegistry;
import jakarta.enterprise.event.Event;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* A server leaf on disk as {@code TlsConfigSource} leaves it, a mocked configuration, TLS registry
* and event, for the {@link TlsCertificateManager} unit tests.
*/
abstract class TlsCertificateManagerFixture {
static final List<String> CONFIGURED = List.of("localhost", "127.0.0.1", "*.localhost.floci.io", "localhost.floci.io");
static final String NEW_HOST = "api.example.localhost.floci.io";
@TempDir
Path tempDir;
Path tlsDir;
FlociCertificateAuthority ca;
EmulatorConfig config;
TlsConfigurationRegistry registry;
TlsConfiguration defaultTls;
@SuppressWarnings("unchecked")
final Event<CertificateUpdatedEvent> events = mock(Event.class);
@BeforeAll
static void bouncyCastle() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
@BeforeEach
void serverLeafOnDisk() throws Exception {
forgetBootstrapTlsDir();
tlsDir = Files.createDirectories(tempDir.resolve("tls"));
ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
var leaf = ca.issueServerCertificate("localhost", CONFIGURED, KeyAlgorithm.RSA_2048, null);
Files.writeString(tlsDir.resolve("floci-server.crt"), leaf.certificatePem());
Files.writeString(tlsDir.resolve("floci-server.key"), leaf.privateKeyPem());
Files.writeString(tlsDir.resolve("floci-server.metadata.json"),
new ObjectMapper().writeValueAsString(CertificateMetadata.create(CONFIGURED, "dev")));
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.tls().enabled()).thenReturn(true);
when(config.tls().certPath()).thenReturn(Optional.empty());
when(config.storage().persistentPath()).thenReturn(tempDir.toString());
when(config.hostname()).thenReturn(Optional.of("floci"));
when(config.baseUrl()).thenReturn("http://localhost:4566");
when(config.dns().extraSuffixes()).thenReturn(Optional.of(List.of("example.internal")));
registry = mock(TlsConfigurationRegistry.class);
defaultTls = mock(TlsConfiguration.class);
when(registry.getDefault()).thenReturn(Optional.of(defaultTls));
when(defaultTls.reload()).thenReturn(true);
}
TlsCertificateManager manager() {
return new TlsCertificateManager(config, ca, registry, events);
}
/**
* The manager resolves the TLS directory like every CDI consumer: the one the config
* bootstrap laid down, else the configured persistent path. Another test class in this JVM
* may have run a TLS-on bootstrap; a TLS-off bootstrap clears that static, as a real boot does.
*/
private static void forgetBootstrapTlsDir() {
System.setProperty("floci.tls.enabled", "false");
try {
new TlsConfigSource();
} finally {
System.clearProperty("floci.tls.enabled");
}
assertNull(TlsConfigSource.resolvedTlsDir());
}
X509Certificate read(String name) throws Exception {
return new CertificateGenerator().parseCertificate(Files.readString(tlsDir.resolve(name)));
}
byte[] servedCertificate() throws Exception {
return Files.readAllBytes(tlsDir.resolve("floci-server.crt"));
}
CertificateMetadata readMetadata() throws Exception {
return new ObjectMapper().readValue(tlsDir.resolve("floci-server.metadata.json").toFile(), CertificateMetadata.class);
}
static Set<String> sans(X509Certificate cert) throws Exception {
Set<String> out = new TreeSet<>();
for (List<?> entry : cert.getSubjectAlternativeNames()) {
out.add(String.valueOf(entry.get(1)));
}
return out;
}
}
@@ -0,0 +1,159 @@
package io.github.hectorvent.floci.config;
import org.bouncycastle.asn1.x509.GeneralName;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Which names {@code ensureHost} accepts: host name syntax, the one-label wildcard rule that
* X.509 name matching and API Gateway custom domains share, and the local-suffix allow-list.
*/
class TlsCertificateManagerNameRulesTest extends TlsCertificateManagerFixture {
@Test
void knownOrWildcardCoveredHostIsANoOp() throws Exception {
byte[] certBefore = servedCertificate();
TlsCertificateManager m = manager();
m.ensureHost("localhost");
m.ensureHost("LOCALHOST.floci.io.");
m.ensureHost("one-label.localhost.floci.io");
m.ensureHost(" 127.0.0.1 ");
assertArrayEquals(certBefore, servedCertificate());
verify(defaultTls, never()).reload();
verify(events, never()).fire(any());
}
@Test
void aWildcardCoversExactlyOneLabel() throws Exception {
TlsCertificateManager m = manager();
m.ensureHost("one.localhost.floci.io");
verify(defaultTls, never()).reload();
m.ensureHost("two.labels.localhost.floci.io");
verify(defaultTls, times(1)).reload();
m.ensureHost("other.labels.localhost.floci.io");
verify(defaultTls, times(2)).reload();
assertTrue(sans(read("floci-server.crt")).contains("*.localhost.floci.io"), "the wildcard itself is kept");
}
@Test
void wildcardIsAcceptedOnlyAsAWholeLeftmostLabel() throws Exception {
TlsCertificateManager m = manager();
m.ensureHost("*.api.example.localhost.floci.io");
assertTrue(sans(read("floci-server.crt")).contains("*.api.example.localhost.floci.io"),
"one leading *. label is a valid SAN");
verify(defaultTls, times(1)).reload();
m.ensureHost("*");
m.ensureHost("*.");
m.ensureHost("api*.example.localhost.floci.io");
m.ensureHost("*.*.example.localhost.floci.io");
m.ensureHost("example.*.localhost.floci.io");
verify(defaultTls, times(1)).reload();
Set<String> starred = new TreeSet<>(sans(read("floci-server.crt")));
starred.removeIf(n -> !n.contains("*"));
assertEquals(Set.of("*.localhost.floci.io", "*.api.example.localhost.floci.io"), starred,
"malformed wildcards must not reach the certificate");
}
@Test
void namesThatAreNotHostnamesAreRefused() throws Exception {
byte[] certBefore = servedCertificate();
TlsCertificateManager m = manager();
m.ensureHost(null);
m.ensureHost("");
m.ensureHost(" ");
m.ensureHost(".");
m.ensureHost("api.example.localhost.floci.io:443");
m.ensureHost("https://api.example.localhost.floci.io");
m.ensureHost("api example.localhost.floci.io");
m.ensureHost("api_1.example.localhost.floci.io");
m.ensureHost("api..example.localhost.floci.io");
m.ensureHost(".api.example.localhost.floci.io");
m.ensureHost("-api.example.localhost.floci.io");
m.ensureHost("api-.example.localhost.floci.io");
m.ensureHost("a".repeat(64) + ".localhost.floci.io");
m.ensureHost("a".repeat(63) + "." + "b".repeat(63) + "." + "c".repeat(63) + "." + "d".repeat(63) + ".localhost.floci.io");
assertArrayEquals(certBefore, servedCertificate());
verify(defaultTls, never()).reload();
verify(events, never()).fire(any());
}
@Test
void hostOutsideTheAllowListIsRefused() throws Exception {
byte[] certBefore = servedCertificate();
TlsCertificateManager m = manager();
m.ensureHost("accounts.google.com");
m.ensureHost("evil-localhost.floci.io");
m.ensureHost("localhost.floci.io.attacker.example");
m.ensureHost("floci.example");
m.ensureHost("*.google.com");
assertArrayEquals(certBefore, servedCertificate());
verify(defaultTls, never()).reload();
assertEquals(List.of(), readMetadata().getLearnedHostnames());
}
@Test
void allowListIncludesConfiguredHostnameBaseUrlAndExtraSuffixes() throws Exception {
when(config.baseUrl()).thenReturn("https://Floci.Corp.Example:4566");
TlsCertificateManager m = manager();
m.ensureHost("api.floci");
m.ensureHost("floci");
m.ensureHost("iot.example.internal");
m.ensureHost("data.localhost.localstack.cloud");
m.ensureHost("api.floci.corp.example");
Set<String> sans = sans(read("floci-server.crt"));
assertTrue(sans.containsAll(List.of("api.floci", "floci", "iot.example.internal",
"data.localhost.localstack.cloud", "api.floci.corp.example")), sans.toString());
}
@Test
void unusableBaseUrlAndAbsentOptionalConfigStillAllowBuiltinSuffixes() throws Exception {
when(config.baseUrl()).thenReturn("not a url");
when(config.hostname()).thenReturn(Optional.empty());
when(config.dns().extraSuffixes()).thenReturn(Optional.empty());
manager().ensureHost(NEW_HOST);
assertTrue(sans(read("floci-server.crt")).contains(NEW_HOST));
}
@Test
void anIpAddressAllowedByTheBaseUrlBecomesAnIpSan() throws Exception {
when(config.baseUrl()).thenReturn("https://192.168.1.100:4566");
manager().ensureHost("192.168.1.100");
boolean ipSan = false;
for (List<?> entry : read("floci-server.crt").getSubjectAlternativeNames()) {
if (entry.get(0).equals(GeneralName.iPAddress) && "192.168.1.100".equals(entry.get(1))) {
ipSan = true;
}
}
assertTrue(ipSan, "an IP is encoded as an iPAddress SAN, not a dNSName");
}
}
@@ -0,0 +1,360 @@
package io.github.hectorvent.floci.config;
import io.quarkus.tls.CertificateUpdatedEvent;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.file.Files;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Reissue, reload, persistence, reset, failure handling and concurrency. Name rules are next door. */
class TlsCertificateManagerTest extends TlsCertificateManagerFixture {
@Test
void newHostIsAppendedWithTheSameKeyAndReloaded() throws Exception {
byte[] keyBefore = Files.readAllBytes(tlsDir.resolve("floci-server.key"));
X509Certificate before = read("floci-server.crt");
manager().ensureHost(NEW_HOST);
X509Certificate after = read("floci-server.crt");
assertTrue(sans(after).contains(NEW_HOST), sans(after).toString());
assertTrue(sans(after).containsAll(CONFIGURED));
assertEquals(before.getPublicKey(), after.getPublicKey(), "same key pair");
assertArrayEquals(keyBefore, Files.readAllBytes(tlsDir.resolve("floci-server.key")), "key file never rewritten");
after.verify(ca.certificate().getPublicKey());
CertificateMetadata metadata = readMetadata();
assertEquals(CONFIGURED, metadata.getHostnames(), "configured list untouched");
assertEquals(List.of(NEW_HOST), metadata.getLearnedHostnames());
verify(defaultTls).reload();
ArgumentCaptor<CertificateUpdatedEvent> event = ArgumentCaptor.forClass(CertificateUpdatedEvent.class);
verify(events).fire(event.capture());
assertEquals("<default>", event.getValue().name());
assertEquals(defaultTls, event.getValue().tlsConfiguration());
assertFalse(Files.exists(tlsDir.resolve("floci-server.crt.tmp")), "temporary file renamed away");
assertFalse(Files.exists(tlsDir.resolve("floci-server.metadata.json.tmp")), "temporary file renamed away");
}
@Test
void reissuedLeafKeepsTheShapeOfTheBootLeaf() throws Exception {
X509Certificate before = read("floci-server.crt");
manager().ensureHost(NEW_HOST);
X509Certificate after = read("floci-server.crt");
assertEquals(before.getSubjectX500Principal(), after.getSubjectX500Principal(), "subject unchanged");
assertEquals(ca.certificate().getSubjectX500Principal(), after.getIssuerX500Principal(), "issued by the local CA");
assertTrue(ca.isIssuedByUs(after));
assertNotEquals(before.getSerialNumber(), after.getSerialNumber(), "a reissue is a new certificate");
assertEquals(-1, after.getBasicConstraints(), "a server leaf, not a CA");
assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), after.getExtendedKeyUsage(),
"serverAuth and clientAuth, as an ACM-issued certificate carries");
after.checkValidity();
assertTrue(after.getNotAfter().toInstant().isBefore(Instant.now().plus(366, ChronoUnit.DAYS)),
"validity is not extended beyond a normal leaf");
assertTrue(after.getNotAfter().toInstant().isAfter(Instant.now().plus(364, ChronoUnit.DAYS)));
List<String> ordered = new ArrayList<>();
for (List<?> entry : after.getSubjectAlternativeNames()) {
ordered.add(String.valueOf(entry.get(1)));
}
assertEquals(CONFIGURED, ordered.subList(0, CONFIGURED.size()), "configured names first, in their order");
assertEquals(NEW_HOST, ordered.get(ordered.size() - 1), "learned names appended");
}
@Test
void secondCallForTheSameHostDoesNotReissue() throws Exception {
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
byte[] certAfterFirst = servedCertificate();
m.ensureHost(NEW_HOST);
m.ensureHost(NEW_HOST.toUpperCase());
assertArrayEquals(certAfterFirst, servedCertificate());
verify(defaultTls, times(1)).reload();
}
@Test
void learnedHostsSurviveANewManagerInstance() throws Exception {
manager().ensureHost(NEW_HOST);
TlsCertificateManager fresh = manager();
fresh.ensureHost(NEW_HOST);
verify(defaultTls, times(1)).reload();
assertTrue(fresh.knownHostnames().contains(NEW_HOST));
assertTrue(fresh.knownHostnames().containsAll(CONFIGURED));
}
@Test
void aSecondLearnedHostKeepsTheFirst() throws Exception {
manager().ensureHost(NEW_HOST);
manager().ensureHost("auth.example.localhost.floci.io");
Set<String> sans = sans(read("floci-server.crt"));
assertTrue(sans.containsAll(List.of(NEW_HOST, "auth.example.localhost.floci.io")), sans.toString());
assertEquals(List.of(NEW_HOST, "auth.example.localhost.floci.io"), readMetadata().getLearnedHostnames());
}
@Test
void clearDropsLearnedHostsAndKeepsConfiguredOnes() throws Exception {
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
m.clear();
Set<String> sans = sans(read("floci-server.crt"));
assertFalse(sans.contains(NEW_HOST));
assertTrue(sans.containsAll(CONFIGURED));
assertEquals(List.of(), readMetadata().getLearnedHostnames());
assertEquals(CONFIGURED, readMetadata().getHostnames());
assertFalse(m.knownHostnames().contains(NEW_HOST));
verify(defaultTls, times(2)).reload();
}
@Test
void clearWithNothingLearnedTouchesNothing() throws Exception {
byte[] certBefore = servedCertificate();
manager().clear();
assertArrayEquals(certBefore, servedCertificate());
verify(defaultTls, never()).reload();
}
@Test
void doesNothingWhenTlsIsOff() throws Exception {
when(config.tls().enabled()).thenReturn(false);
byte[] certBefore = servedCertificate();
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
m.clear();
assertArrayEquals(certBefore, servedCertificate());
assertEquals(Set.of(), m.knownHostnames());
verify(defaultTls, never()).reload();
}
@Test
void doesNothingWithAUserProvidedCertificate() throws Exception {
when(config.tls().certPath()).thenReturn(Optional.of("/etc/floci/user.crt"));
byte[] certBefore = servedCertificate();
manager().ensureHost(NEW_HOST);
assertArrayEquals(certBefore, servedCertificate());
verify(defaultTls, never()).reload();
}
@Test
void doesNothingWithoutAServerLeafOnDisk() throws Exception {
Files.delete(tlsDir.resolve("floci-server.crt"));
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
assertFalse(Files.exists(tlsDir.resolve("floci-server.crt")));
assertEquals(Set.of(), m.knownHostnames());
verify(defaultTls, never()).reload();
}
@Test
void aFailedReloadIsRetriedByTheNextCall() throws Exception {
when(defaultTls.reload()).thenReturn(false);
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
assertTrue(sans(read("floci-server.crt")).contains(NEW_HOST), "the file is still written for the next boot");
verify(events, never()).fire(any());
assertFalse(m.knownHostnames().contains(NEW_HOST), "a name the listener does not serve is not known");
when(defaultTls.reload()).thenReturn(true);
m.ensureHost(NEW_HOST);
verify(defaultTls, times(2)).reload();
verify(events, times(1)).fire(any());
assertTrue(m.knownHostnames().contains(NEW_HOST));
assertEquals(List.of(NEW_HOST), readMetadata().getLearnedHostnames());
}
@Test
void aNameWhoseReloadFailedIsCarriedIntoTheNextReissue() throws Exception {
when(defaultTls.reload()).thenReturn(false);
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
assertFalse(m.knownHostnames().contains(NEW_HOST));
when(defaultTls.reload()).thenReturn(true);
m.ensureHost("auth.example.localhost.floci.io");
Set<String> sans = sans(read("floci-server.crt"));
assertTrue(sans.contains(NEW_HOST), "the name written to disk is not dropped by the next reissue: " + sans);
assertTrue(sans.contains("auth.example.localhost.floci.io"), sans.toString());
assertTrue(m.knownHostnames().containsAll(List.of(NEW_HOST, "auth.example.localhost.floci.io")));
assertEquals(List.of(NEW_HOST, "auth.example.localhost.floci.io"), readMetadata().getLearnedHostnames());
verify(defaultTls, times(2)).reload();
verify(events, times(1)).fire(any());
}
@Test
void aResetWhoseReloadFailedIsRetriedByTheNextReset() throws Exception {
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
when(defaultTls.reload()).thenReturn(false);
m.clear();
assertEquals(List.of(), readMetadata().getLearnedHostnames(), "the files are reset");
assertTrue(m.knownHostnames().contains(NEW_HOST), "the listener still serves the name");
when(defaultTls.reload()).thenReturn(true);
m.clear();
verify(defaultTls, times(3)).reload();
assertFalse(m.knownHostnames().contains(NEW_HOST));
assertFalse(sans(read("floci-server.crt")).contains(NEW_HOST));
}
@Test
void aMissingDefaultTlsConfigurationIsRetriedByTheNextCall() throws Exception {
when(registry.getDefault()).thenReturn(Optional.empty());
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
verify(events, never()).fire(any());
assertFalse(m.knownHostnames().contains(NEW_HOST));
when(registry.getDefault()).thenReturn(Optional.of(defaultTls));
m.ensureHost(NEW_HOST);
verify(defaultTls, times(1)).reload();
verify(events, times(1)).fire(any());
assertTrue(m.knownHostnames().contains(NEW_HOST));
}
@Test
void aFailingListenerIsRetriedByTheNextCall() throws Exception {
doThrow(new IllegalStateException("observer failed")).when(events).fire(any());
TlsCertificateManager m = manager();
m.ensureHost(NEW_HOST);
assertFalse(m.knownHostnames().contains(NEW_HOST));
doNothing().when(events).fire(any());
m.ensureHost(NEW_HOST);
verify(defaultTls, times(2)).reload();
assertTrue(m.knownHostnames().contains(NEW_HOST));
}
@Test
void aFailedReissueLeavesTheServedFilesIntactAndDoesNotThrow() throws Exception {
FlociCertificateAuthority broken = spy(ca);
doThrow(new IllegalStateException("boom")).when(broken).issueServerCertificate(anyString(), anyList(), any(), any());
byte[] certBefore = servedCertificate();
String metadataBefore = Files.readString(tlsDir.resolve("floci-server.metadata.json"));
TlsCertificateManager m = new TlsCertificateManager(config, broken, registry, events);
m.ensureHost(NEW_HOST);
assertArrayEquals(certBefore, servedCertificate());
assertEquals(metadataBefore, Files.readString(tlsDir.resolve("floci-server.metadata.json")));
assertFalse(m.knownHostnames().contains(NEW_HOST), "a name that was never served is not known");
verify(defaultTls, never()).reload();
doCallRealMethod().when(broken).issueServerCertificate(anyString(), anyList(), any(), any());
m.ensureHost("auth.example.localhost.floci.io");
Set<String> sans = sans(read("floci-server.crt"));
assertTrue(sans.contains("auth.example.localhost.floci.io"), sans.toString());
assertFalse(sans.contains(NEW_HOST), "the failed name is not carried into later reissues");
assertEquals(List.of("auth.example.localhost.floci.io"), readMetadata().getLearnedHostnames());
}
@Test
void concurrentCallsForDistinctHostsAllLandInTheCertificate() throws Exception {
TlsCertificateManager m = manager();
List<String> hosts = new ArrayList<>();
for (int i = 0; i < 8; i++) {
hosts.add("svc" + i + ".example.localhost.floci.io");
}
runConcurrently(hosts, m);
Set<String> sans = sans(read("floci-server.crt"));
assertTrue(sans.containsAll(hosts), sans.toString());
assertTrue(sans.containsAll(CONFIGURED));
assertEquals(new TreeSet<>(hosts), new TreeSet<>(readMetadata().getLearnedHostnames()));
assertTrue(m.knownHostnames().containsAll(hosts));
verify(defaultTls, times(8)).reload();
}
@Test
void concurrentCallsForTheSameHostReissueOnce() throws Exception {
TlsCertificateManager m = manager();
List<String> hosts = new ArrayList<>();
for (int i = 0; i < 8; i++) {
hosts.add(NEW_HOST);
}
runConcurrently(hosts, m);
assertEquals(List.of(NEW_HOST), readMetadata().getLearnedHostnames());
verify(defaultTls, times(1)).reload();
}
private static void runConcurrently(List<String> hosts, TlsCertificateManager m) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(hosts.size());
CountDownLatch start = new CountDownLatch(1);
List<Future<?>> futures = new ArrayList<>();
try {
for (String host : hosts) {
futures.add(pool.submit(() -> {
start.await();
m.ensureHost(host);
return null;
}));
}
start.countDown();
for (Future<?> f : futures) {
f.get(60, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
}
}
@@ -0,0 +1,177 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Hostnames {@link TlsCertificateManager} learned at runtime must survive every boot path of
* {@link TlsConfigSource}: a reused certificate, a regeneration after a configuration change,
* a reissue of an expired leaf, and a certificate whose metadata write did not complete.
*/
class TlsConfigSourceLearnedHostnamesTest {
private static final String LEARNED = "api.example.localhost.floci.io";
private static final List<String> DEFAULTS = List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
"localhost.floci.io", "*.localhost.floci.io", "*.execute-api.localhost.floci.io",
"*.execute-api.localhost.localstack.cloud", "host.docker.internal");
private static final ObjectMapper MAPPER = new ObjectMapper();
@TempDir
Path tempDir;
private Path tlsDir;
private Path metadataFile;
@BeforeAll
static void bouncyCastle() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
@BeforeEach
void tlsOn() {
System.setProperty("floci.tls.enabled", "true");
System.setProperty("floci.tls.self-signed", "true");
System.setProperty("floci.storage.persistent-path", tempDir.toString());
tlsDir = tempDir.resolve("tls");
metadataFile = tlsDir.resolve("floci-server.metadata.json");
}
@AfterEach
void clearProperties() {
System.clearProperty("floci.hostname");
System.clearProperty("floci.tls.enabled");
System.clearProperty("floci.tls.self-signed");
System.clearProperty("floci.storage.persistent-path");
}
@Test
void learnedHostnamesAreKeptWhenBootRegeneratesTheCertificate() throws Exception {
System.setProperty("floci.hostname", "host1");
new TlsConfigSource();
recordAsLearned(LEARNED);
System.setProperty("floci.hostname", "host2");
new TlsConfigSource();
List<String> sans = servedSans();
assertTrue(sans.contains("host2"), sans.toString());
assertFalse(sans.contains("host1"), sans.toString());
assertTrue(sans.contains(LEARNED), "learned name must survive: " + sans);
CertificateMetadata after = readMetadata();
assertEquals(List.of(LEARNED), after.getLearnedHostnames());
assertFalse(after.getHostnames().contains(LEARNED), "learned names stay out of the configured list");
}
@Test
void aLearnedHostnameDoesNotCountAsAConfigurationChange() throws Exception {
new TlsConfigSource();
recordAsLearned(LEARNED);
String certBefore = Files.readString(tlsDir.resolve("floci-server.crt"));
new TlsConfigSource();
assertEquals(certBefore, Files.readString(tlsDir.resolve("floci-server.crt")),
"same configuration: the certificate is reused, not regenerated");
}
@Test
void learnedHostnamesAreKeptWhenAnExpiredLeafIsReissued() throws Exception {
Files.createDirectories(tlsDir);
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
CertificateGenerator gen = new CertificateGenerator();
List<String> sans = new ArrayList<>(DEFAULTS);
sans.add(LEARNED);
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
X509Certificate expired = gen.signCertificate(new X500Name("CN=localhost"), keyPair.getPublic(),
X500Name.getInstance(ca.certificate().getSubjectX500Principal().getEncoded()), ca.key(), sans, false,
CertificateGenerator.LeafUsage.SERVER, -1);
Files.writeString(tlsDir.resolve("floci-server.crt"), gen.toPem(expired));
Files.writeString(tlsDir.resolve("floci-server.key"), gen.toPem(keyPair.getPrivate()));
CertificateMetadata metadata = CertificateMetadata.create(DEFAULTS, "dev");
metadata.setLearnedHostnames(List.of(LEARNED));
Files.writeString(metadataFile, MAPPER.writeValueAsString(metadata));
new TlsConfigSource();
X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));
leaf.checkValidity();
assertNotEquals(expired.getSerialNumber(), leaf.getSerialNumber(), "the expired leaf was reissued");
List<String> reissued = servedSans();
assertTrue(reissued.contains(LEARNED), "learned name must survive: " + reissued);
assertTrue(reissued.containsAll(DEFAULTS), reissued.toString());
}
@Test
void aSanTheMetadataDoesNotListIsKeptAsLearnedWhenBootRegenerates() throws Exception {
System.setProperty("floci.hostname", "host1");
new TlsConfigSource();
CertificateMetadata bootMetadata = readMetadata();
// A runtime reissue whose certificate rename succeeded and whose metadata rename did not:
// the served leaf carries the learned name, the metadata knows nothing about it.
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
CertificateGenerator gen = new CertificateGenerator();
X509Certificate served = parseCertificate(tlsDir.resolve("floci-server.crt"));
KeyPair keyPair = new KeyPair(served.getPublicKey(),
gen.parsePrivateKey(Files.readString(tlsDir.resolve("floci-server.key"))));
List<String> sans = new ArrayList<>(bootMetadata.getHostnames());
sans.add(LEARNED);
Files.writeString(tlsDir.resolve("floci-server.crt"),
ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, keyPair).certificatePem());
System.setProperty("floci.hostname", "host2");
new TlsConfigSource();
List<String> regenerated = servedSans();
assertTrue(regenerated.contains(LEARNED), "served name must survive: " + regenerated);
assertTrue(regenerated.contains("host2"), regenerated.toString());
assertFalse(regenerated.contains("host1"), "a previously configured name is not mistaken for a learned one");
assertEquals(List.of(LEARNED), readMetadata().getLearnedHostnames());
}
private void recordAsLearned(String name) throws Exception {
CertificateMetadata metadata = readMetadata();
metadata.setLearnedHostnames(List.of(name));
Files.writeString(metadataFile, MAPPER.writeValueAsString(metadata));
}
private CertificateMetadata readMetadata() throws Exception {
return MAPPER.readValue(metadataFile.toFile(), CertificateMetadata.class);
}
private List<String> servedSans() throws Exception {
List<String> sans = new ArrayList<>();
for (List<?> entry : parseCertificate(tlsDir.resolve("floci-server.crt")).getSubjectAlternativeNames()) {
sans.add(String.valueOf(entry.get(1)));
}
return sans;
}
private static X509Certificate parseCertificate(Path certFile) throws Exception {
return new CertificateGenerator().parseCertificate(Files.readString(certFile));
}
}
@@ -0,0 +1,183 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.Test;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* End to end: after {@code ensureHost}, a TLS client that trusts only the local CA and sends the
* new name as SNI receives a leaf whose SAN list contains it, and a client that also verifies the
* server's identity for that name (what every SDK does) completes the handshake, with no restart
* in between. A file assertion cannot show that the reload reached the listener; only a
* handshake can.
*/
@QuarkusTest
@TestProfile(TlsEnsureHostIntegrationTest.Profile.class)
class TlsEnsureHostIntegrationTest {
static final Path DATA_DIR = Path.of("target", "floci-tls-ensure-host-test").toAbsolutePath();
static final Path TLS_DIR = DATA_DIR.resolve("tls");
static final String NEW_HOST = "api.example.localhost.floci.io";
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
int sslPort;
@Inject
TlsCertificateManager manager;
@Test
void ensureHostIsVisibleToTheNextHandshakeAndResetTakesItBack() throws Exception {
X509Certificate boot = peerLeaf();
assertFalse(sans(boot).contains(NEW_HOST), "precondition: the boot leaf does not cover " + NEW_HOST);
assertThrows(SSLHandshakeException.class, this::handshakeVerifyingNewHost,
"precondition: a client verifying the new name rejects the boot leaf");
assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is served before");
manager.ensureHost(NEW_HOST);
X509Certificate extended = peerLeaf();
Set<String> sans = sans(extended);
assertTrue(sans.contains(NEW_HOST), sans.toString());
assertTrue(sans.contains("localhost"), "configured names are still served: " + sans);
assertEquals(boot.getPublicKey(), extended.getPublicKey(), "same key pair across the reload");
handshakeVerifyingNewHost();
assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is still served after the swap");
given().when().post("/_floci/state/reset").then().statusCode(200);
Set<String> afterReset = sans(peerLeaf());
assertFalse(afterReset.contains(NEW_HOST), "reset drops the learned name: " + afterReset);
assertTrue(afterReset.contains("localhost"), afterReset.toString());
assertThrows(SSLHandshakeException.class, this::handshakeVerifyingNewHost, "reset: the new name is rejected again");
assertEquals(200, healthOverHttpsAsLocalhost(), "the configured name is served after reset");
}
/** The leaf the server presents for SNI {@code NEW_HOST}, with no identity check. */
private X509Certificate peerLeaf() throws Exception {
return handshake(false);
}
/** A handshake as an SDK would do it: SNI {@code NEW_HOST} and RFC 6125 identity verification. */
private void handshakeVerifyingNewHost() throws Exception {
handshake(true);
}
/**
* Connects by IP so the JDK has no peer host of its own and verifies the certificate against
* the SNI name; the fixture leaf carries no {@code 127.0.0.1} SAN, so nothing else can match.
*/
private X509Certificate handshake(boolean verifyIdentity) throws Exception {
try (SSLSocket socket = (SSLSocket) trustOnlyTheCa().getSocketFactory().createSocket()) {
socket.connect(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), sslPort), 5000);
SSLParameters params = socket.getSSLParameters();
params.setServerNames(List.of(new SNIHostName(NEW_HOST)));
if (verifyIdentity) {
params.setEndpointIdentificationAlgorithm("HTTPS");
}
socket.setSSLParameters(params);
socket.startHandshake();
return (X509Certificate) socket.getSession().getPeerCertificates()[0];
}
}
/** A plain HTTPS client with the JDK's default hostname verifier, for the configured name. */
private int healthOverHttpsAsLocalhost() throws Exception {
HttpsURLConnection connection = (HttpsURLConnection) URI.create(
"https://localhost:" + sslPort + "/_floci/health").toURL().openConnection();
connection.setSSLSocketFactory(trustOnlyTheCa().getSocketFactory());
try {
return connection.getResponseCode();
} finally {
connection.disconnect();
}
}
private static SSLContext trustOnlyTheCa() throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci", FlociCertificateAuthority.loadOrCreate(TLS_DIR).certificate());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trust);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
return ctx;
}
private static Set<String> sans(X509Certificate leaf) throws Exception {
Set<String> sans = new TreeSet<>();
for (List<?> entry : leaf.getSubjectAlternativeNames()) {
sans.add(String.valueOf(entry.get(1)));
}
return sans;
}
/**
* Boots with TLS on and a CA-issued leaf like the one TlsConfigSource writes. TlsConfigSource
* itself reads system properties, not profile overrides, so the profile lays the files down
* and points the TLS registry's default entry at them. The wildcard covers one label only
* (RFC 6125), so the three-label name is genuinely uncovered before ensureHost.
*/
public static final class Profile implements QuarkusTestProfile {
static {
try {
Files.createDirectories(TLS_DIR);
for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {
Files.deleteIfExists(TLS_DIR.resolve(name));
}
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
List<String> sans = List.of("localhost", "*.localhost.floci.io");
var leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);
Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());
Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());
Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),
new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));
} catch (IOException e) {
throw new IllegalStateException("could not prepare the TLS fixtures", e);
}
}
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.tls.enabled", "true",
"floci.tls.self-signed", "true",
"floci.tls.aws-https-port", "0",
"floci.storage.persistent-path", DATA_DIR.toString(),
"quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString(),
"quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString(),
"quarkus.http.insecure-requests", "enabled");
}
}
}
@@ -131,7 +131,7 @@ class TlsIntegrationTest {
Security.addProvider(new BouncyCastleProvider());
}
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(
CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate(
"localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);
Files.writeString(CERT_FILE, cert.certificatePem());
Files.writeString(KEY_FILE, cert.privateKeyPem());
@@ -116,7 +116,7 @@ class TlsUserCertIntegrationTest {
Security.addProvider(new BouncyCastleProvider());
}
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(
CertificateGenerator.GeneratedCertificate cert = gen.generateSelfSignedCertificate(
"localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);
Files.writeString(CERT_FILE, cert.certificatePem());
Files.writeString(KEY_FILE, cert.privateKeyPem());
@@ -1,9 +1,9 @@
package io.github.hectorvent.floci.services.acm;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.file.Files;
import java.util.Base64;
import java.util.List;
@@ -24,29 +25,29 @@ class AcmImportExportTest {
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
@Inject
CertificateGenerator certificateGenerator;
// Generated test certificate data
// A server certificate from a CA that is not Floci's, with that CA as its chain: what a user imports
private String validTestCertificate;
private String validTestPrivateKey;
private String validTestChain;
private String importedCertificateArn;
private String exportableCertificateArn;
@BeforeAll
void setupTestCertificates() {
void setupTestCertificates() throws Exception {
RestAssuredJsonUtils.configureAwsContentTypes();
// Generate a valid test certificate using CertificateGenerator
CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(
FlociCertificateAuthority otherCa = FlociCertificateAuthority.loadOrCreate(Files.createTempDirectory("acm-import-ca"));
CertificateGenerator.GeneratedCertificate generated = otherCa.issueServerCertificate(
"test-import.example.com",
List.of("www.test-import.example.com"),
KeyAlgorithm.RSA_2048
KeyAlgorithm.RSA_2048,
null
);
validTestCertificate = generated.certificatePem().replace("\r\n", "\n");
validTestPrivateKey = generated.privateKeyPem().replace("\r\n", "\n");
validTestChain = otherCa.caPem().replace("\r\n", "\n");
}
// ==================== ImportCertificate Tests ====================
@@ -57,6 +58,7 @@ class AcmImportExportTest {
// Escape newlines for JSON
String certJson = validTestCertificate.replace("\n", "\\n");
String keyJson = validTestPrivateKey.replace("\n", "\\n");
String chainJson = validTestChain.replace("\n", "\\n");
importedCertificateArn = given()
.header("X-Amz-Target", "CertificateManager.ImportCertificate")
@@ -64,9 +66,10 @@ class AcmImportExportTest {
.body("""
{
"Certificate": "%s",
"PrivateKey": "%s"
"PrivateKey": "%s",
"CertificateChain": "%s"
}
""".formatted(certJson, keyJson))
""".formatted(certJson, keyJson, chainJson))
.when()
.post("/")
.then()
@@ -98,6 +101,22 @@ class AcmImportExportTest {
.body("Certificate.KeyAlgorithm", equalTo("RSA-2048"))
.body("Certificate.Serial", matchesPattern("([0-9a-f]{2}:)+[0-9a-f]{2}"))
.body("Certificate.SignatureAlgorithm", matchesPattern("SHA[0-9]+WITH[A-Z]+"));
// An import keeps the certificate and the chain exactly as uploaded
given()
.header("X-Amz-Target", "CertificateManager.GetCertificate")
.contentType(ACM_CONTENT_TYPE)
.body("""
{
"CertificateArn": "%s"
}
""".formatted(importedCertificateArn))
.when()
.post("/")
.then()
.statusCode(200)
.body("Certificate", equalTo(validTestCertificate))
.body("CertificateChain", equalTo(validTestChain));
}
@Test
@@ -193,6 +212,7 @@ class AcmImportExportTest {
@Order(11)
void exportCertificate() {
String passphrase = Base64.getEncoder().encodeToString("testpassphrase".getBytes());
String localCa = given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString();
given()
.header("X-Amz-Target", "CertificateManager.ExportCertificate")
@@ -208,6 +228,7 @@ class AcmImportExportTest {
.then()
.statusCode(200)
.body("Certificate", startsWith("-----BEGIN CERTIFICATE-----"))
.body("CertificateChain", equalTo(localCa))
.body("PrivateKey", startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"));
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.acm;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
@@ -9,7 +10,9 @@ import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.security.Security;
import java.util.List;
import java.util.Map;
@@ -33,6 +36,9 @@ class AcmInUseByTest {
private static CertificateGenerator generator;
private AcmService service;
@TempDir
Path tempDir;
@BeforeAll
static void registerProvider() {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
@@ -45,7 +51,8 @@ class AcmInUseByTest {
void setUp() {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
service = new AcmService(new InMemoryStorage<>(), generator, regionResolver, 0);
service = new AcmService(new InMemoryStorage<>(), generator,
FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), regionResolver, 0);
}
private String requestCertificate() {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.acm;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
@@ -9,8 +10,21 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertPathValidator;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -19,6 +33,7 @@ class AcmIntegrationTest {
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
private static String createdCertificateArn;
private static String ecCertificateArn;
@BeforeAll
static void configureRestAssured() {
@@ -107,7 +122,7 @@ class AcmIntegrationTest {
@Test
@Order(5)
void requestCertificateWithKeyAlgorithm() {
given()
ecCertificateArn = given()
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
.contentType(ACM_CONTENT_TYPE)
.body("""
@@ -120,7 +135,8 @@ class AcmIntegrationTest {
.post("/")
.then()
.statusCode(200)
.body("CertificateArn", startsWith("arn:aws:acm:"));
.body("CertificateArn", startsWith("arn:aws:acm:"))
.extract().jsonPath().getString("CertificateArn");
}
@Test
@@ -224,7 +240,7 @@ class AcmIntegrationTest {
.body("Certificate.Type", equalTo("AMAZON_ISSUED"))
.body("Certificate.Serial", notNullValue())
.body("Certificate.Subject", startsWith("CN="))
.body("Certificate.Issuer", notNullValue())
.body("Certificate.Issuer", equalTo("CN=Floci Local CA"))
.body("Certificate.KeyAlgorithm", equalTo("RSA-2048"))
.body("Certificate.NotBefore", notNullValue())
.body("Certificate.NotAfter", notNullValue());
@@ -252,21 +268,14 @@ class AcmIntegrationTest {
@Test
@Order(12)
void getCertificate() {
given()
.header("X-Amz-Target", "CertificateManager.GetCertificate")
.contentType(ACM_CONTENT_TYPE)
.body("""
{
"CertificateArn": "%s"
}
""".formatted(createdCertificateArn))
.when()
.post("/")
.then()
.statusCode(200)
.body("Certificate", startsWith("-----BEGIN CERTIFICATE-----"))
.body("CertificateChain", startsWith("-----BEGIN CERTIFICATE-----"));
void getCertificate() throws Exception {
var response = getCertificatePems(createdCertificateArn);
X509Certificate leaf = assertLeafChainsToLocalCa(response.getString("Certificate"),
response.getString("CertificateChain"));
assertEquals("RSA", leaf.getPublicKey().getAlgorithm());
assertEquals(2048, ((RSAPublicKey) leaf.getPublicKey()).getModulus().bitLength(),
"RSA_2048 is the default KeyAlgorithm");
}
// ==================== User Story 2: ListCertificates ====================
@@ -324,6 +333,41 @@ class AcmIntegrationTest {
.body("CertificateSummaryList", notNullValue());
}
@Test
@Order(16)
void privateCertificateChainsToTheSameCa() throws Exception {
String arn = given()
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
.contentType(ACM_CONTENT_TYPE)
.body("""
{
"DomainName": "internal.example.com",
"CertificateAuthorityArn": "arn:aws:acm-pca:us-east-1:000000000000:certificate-authority/11111111-2222-3333-4444-555555555555"
}
""")
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath().getString("CertificateArn");
var response = getCertificatePems(arn);
assertLeafChainsToLocalCa(response.getString("Certificate"), response.getString("CertificateChain"));
}
@Test
@Order(17)
void ecCertificateKeepsItsKeyAlgorithmAndChainsToTheSameCa() throws Exception {
var response = getCertificatePems(ecCertificateArn);
X509Certificate leaf = assertLeafChainsToLocalCa(response.getString("Certificate"),
response.getString("CertificateChain"));
assertEquals("EC", leaf.getPublicKey().getAlgorithm(), "the requested KeyAlgorithm is honoured");
assertEquals(256, ((ECPublicKey) leaf.getPublicKey()).getParams().getCurve().getField().getFieldSize(),
"EC_prime256v1 is a P-256 key");
}
// ==================== User Story 5: Tagging ====================
@Test
@@ -695,4 +739,48 @@ class AcmIntegrationTest {
.statusCode(400)
.body("__type", equalTo("UnsupportedOperation"));
}
private static JsonPath getCertificatePems(String certificateArn) {
return given()
.header("X-Amz-Target", "CertificateManager.GetCertificate")
.contentType(ACM_CONTENT_TYPE)
.body("""
{
"CertificateArn": "%s"
}
""".formatted(certificateArn))
.when()
.post("/")
.then()
.statusCode(200)
.extract().jsonPath();
}
/**
* Certificate is a TLS server leaf, CertificateChain is exactly the local CA served at
* /_floci/ca.pem, and the pair builds a PKIX path with that CA as the only trust anchor: what a
* client that pins Certificate plus CertificateChain does, so a signature check alone is not enough.
*/
private static X509Certificate assertLeafChainsToLocalCa(String leafPem, String chainPem) throws Exception {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate leaf = parse(factory, leafPem);
X509Certificate chain = parse(factory, chainPem);
String servedCa = given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString();
assertEquals(servedCa.strip(), chainPem.strip(), "CertificateChain must be the local CA PEM");
assertEquals(chain.getSubjectX500Principal(), leaf.getIssuerX500Principal());
assertEquals(-1, leaf.getBasicConstraints(), "a leaf, not a CA");
assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), leaf.getExtendedKeyUsage(),
"serverAuth and clientAuth, as DescribeCertificate advertises");
PKIXParameters params = new PKIXParameters(Set.of(new TrustAnchor(chain, null)));
params.setRevocationEnabled(false);
CertPathValidator.getInstance("PKIX").validate(factory.generateCertPath(List.of(leaf)), params);
return leaf;
}
private static X509Certificate parse(CertificateFactory factory, String pem) throws Exception {
return (X509Certificate) factory.generateCertificate(
new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
}
}
@@ -91,7 +91,9 @@ class AcmPaginationTest {
Set<String> allArns = new HashSet<>();
String nextToken = null;
int pageCount = 0;
int maxPages = 10; // Safety limit
// Safety limit against a NextToken that never ends. The store is shared with every other ACM
// test class in the JVM, so the real page count grows with the suite.
int maxPages = 200;
do {
String body = nextToken == null
@@ -27,7 +27,7 @@ class AcmRevokeCertificateGuardTest {
@Test
void revokeCertificateRejectsImportedCertificateWithoutExportEnabled() {
CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateCertificate(
CertificateGenerator.GeneratedCertificate generated = certificateGenerator.generateSelfSignedCertificate(
"revoke-guard-imported.example.com", List.of(), KeyAlgorithm.RSA_2048);
String certJson = generated.certificatePem().replace("\r\n", "\n").replace("\n", "\\n");
String keyJson = generated.privateKeyPem().replace("\r\n", "\n").replace("\n", "\\n");
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.acm;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -19,6 +20,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -63,6 +65,8 @@ class AcmServicePersistenceTest {
assertEquals("example.com", loaded.getDomainName());
assertEquals(List.of("example.com", "www.example.com"), loaded.getSubjectAlternativeNames());
assertEquals("test", loaded.getTags().get("Env"));
assertTrue(loaded.getCertificateChain().startsWith("-----BEGIN CERTIFICATE-----"), "the CA chain is persisted");
assertEquals(cert.getCertificateChain(), loaded.getCertificateChain());
}
private AcmService newService(Path dir) {
@@ -70,7 +74,8 @@ class AcmServicePersistenceTest {
when(regionResolver.getAccountId()).thenReturn("000000000000");
StorageBackend<String, Certificate> store = load(dir, "acm-certificates.json");
return new AcmService(store, generator, regionResolver, 0);
return new AcmService(store, generator, FlociCertificateAuthority.loadOrCreate(dir.resolve("tls")),
regionResolver, 0);
}
private StorageBackend<String, Certificate> load(Path dir, String file) {
@@ -0,0 +1,246 @@
package io.github.hectorvent.floci.services.acm;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.model.Certificate;
import io.github.hectorvent.floci.services.acm.model.CertificateOptions;
import io.github.hectorvent.floci.services.acm.model.CertificateStatus;
import io.github.hectorvent.floci.services.acm.model.CertificateType;
import io.github.hectorvent.floci.services.acm.model.DomainValidation;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import io.github.hectorvent.floci.services.acm.model.ValidationMethod;
import org.junit.jupiter.api.BeforeEach;
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.EnumSource;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.security.cert.CertPathValidator;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The issuance path of {@link AcmService} against a real local CA and no Quarkus: every
* certificate the service issues chains to that CA, whatever the key algorithm, type or
* validation state, and its metadata is read from the certificate rather than from the request.
*/
class AcmServiceTest {
private static final String REGION = "us-east-1";
private static final String PCA_ARN =
"arn:aws:acm-pca:us-east-1:000000000000:certificate-authority/11111111-2222-3333-4444-555555555555";
private static final List<String> SERVER_AND_CLIENT_AUTH = List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2");
@TempDir
Path tempDir;
private FlociCertificateAuthority ca;
private CertificateGenerator generator;
private AcmService service;
@BeforeEach
void setUp() {
ca = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls"));
generator = new CertificateGenerator();
service = newService(0);
}
private AcmService newService(int validationWaitSeconds) {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
return new AcmService(new InMemoryStorage<>(), generator, ca, regionResolver, validationWaitSeconds);
}
@ParameterizedTest
@EnumSource(KeyAlgorithm.class)
void issuesALeafOfTheRequestedAlgorithmSignedByTheLocalCa(KeyAlgorithm algorithm) throws Exception {
Certificate cert = service.requestCertificate("api.example.test", List.of("*.example.test"),
ValidationMethod.DNS, null, algorithm, null, null, Map.of(), REGION);
X509Certificate leaf = assertChainsToTheCa(cert);
assertEquals(CertificateType.AMAZON_ISSUED, cert.getType());
assertEquals(CertificateStatus.ISSUED, cert.getStatus());
assertEquals(algorithm, cert.getKeyAlgorithm());
assertEquals(algorithm.getAlgorithm(), leaf.getPublicKey().getAlgorithm());
if (leaf.getPublicKey() instanceof RSAPublicKey rsa) {
assertEquals(algorithm.getKeySize(), rsa.getModulus().bitLength());
} else {
assertEquals(algorithm.getKeySize(),
((ECPublicKey) leaf.getPublicKey()).getParams().getCurve().getField().getFieldSize());
}
assertEquals(List.of("api.example.test", "*.example.test"), cert.getSubjectAlternativeNames());
assertEquals(List.of("api.example.test", "*.example.test"),
leaf.getSubjectAlternativeNames().stream().map(san -> san.get(1)).toList());
}
@Test
void privateCertificateChainsToTheSameCaAndIsIssuedAtOnce() throws Exception {
Certificate cert = newService(30).requestCertificate("internal.example.test", null, ValidationMethod.DNS,
null, null, PCA_ARN, null, null, REGION);
assertChainsToTheCa(cert);
assertEquals(CertificateType.PRIVATE, cert.getType());
assertEquals(CertificateStatus.ISSUED, cert.getStatus(), "a private certificate waits for no validation");
assertEquals(KeyAlgorithm.RSA_2048, cert.getKeyAlgorithm(), "the default algorithm");
assertEquals(List.of("SUCCESS"),
cert.getDomainValidationOptions().stream().map(DomainValidation::validationStatus).toList());
}
@Test
void pendingValidationCertificateAlreadyHoldsItsLeafAndChain() throws Exception {
Certificate cert = newService(30).requestCertificate("pending.example.test", List.of(),
ValidationMethod.EMAIL, null, KeyAlgorithm.RSA_2048, null, null, null, REGION);
assertEquals(CertificateStatus.PENDING_VALIDATION, cert.getStatus());
assertNull(cert.getIssuedAt());
assertChainsToTheCa(cert);
}
@Test
void anIdempotentReplayReturnsTheSameCertificateInsteadOfIssuingAnother() {
Certificate first = service.requestCertificate("same.example.test", List.of(), ValidationMethod.DNS,
"token-1", KeyAlgorithm.RSA_2048, null, null, null, REGION);
Certificate replay = service.requestCertificate("same.example.test", List.of(), ValidationMethod.DNS,
"token-1", KeyAlgorithm.RSA_2048, null, null, null, REGION);
assertEquals(first.getArn(), replay.getArn());
assertEquals(first.getCertificateBody(), replay.getCertificateBody(), "no second leaf is minted");
assertEquals(1, service.listCertificates(null, null, REGION, 100, null).certificates().size());
AwsException refused = assertThrows(AwsException.class, () -> service.requestCertificate(
"same.example.test", List.of(), ValidationMethod.DNS, "token-1", KeyAlgorithm.EC_prime256v1,
null, null, null, REGION));
assertEquals("IdempotencyException", refused.getErrorCode());
}
@Test
void anImportKeepsTheUploadedChainAndAnImportWithoutOneHasNone() {
FlociCertificateAuthority otherCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("other-ca"));
CertificateGenerator.GeneratedCertificate leaf = otherCa.issueServerCertificate(
"imported.example.test", List.of(), KeyAlgorithm.RSA_2048, null);
Certificate withChain = service.importCertificate(leaf.certificatePem(), leaf.privateKeyPem(),
otherCa.caPem(), null, null, REGION);
Certificate withoutChain = service.importCertificate(leaf.certificatePem(), leaf.privateKeyPem(),
null, null, null, REGION);
assertEquals(CertificateType.IMPORTED, withChain.getType());
assertEquals(otherCa.caPem(), withChain.getCertificateChain(), "an import keeps the chain it was given");
assertEquals(otherCa.certificate().getSubjectX500Principal().getName(), withChain.getIssuer());
assertEquals(leaf.certificatePem(), withChain.getCertificateBody());
assertNull(withoutChain.getCertificateChain());
}
@Test
void exportReturnsTheStoredChainForPrivateAndForExportEnabledPublicCertificates() {
String passphrase = Base64.getEncoder().encodeToString("abcd1234".getBytes(StandardCharsets.US_ASCII));
Certificate privateCert = service.requestCertificate("export-private.example.test", null,
ValidationMethod.DNS, null, null, PCA_ARN, null, null, REGION);
Certificate publicCert = service.requestCertificate("export-public.example.test", null,
ValidationMethod.DNS, null, null, null, new CertificateOptions(null, "ENABLED"), null, REGION);
Certificate ecCert = service.requestCertificate("export-ec.example.test", null, ValidationMethod.DNS, null,
KeyAlgorithm.EC_prime256v1, PCA_ARN, null, null, REGION);
Certificate exportedPrivate = service.exportCertificate(privateCert.getArn(), passphrase, REGION);
Certificate exportedPublic = service.exportCertificate(publicCert.getArn(), passphrase, REGION);
Certificate exportedEc = service.exportCertificate(ecCert.getArn(), passphrase, REGION);
assertEquals(privateCert.getCertificateBody(), exportedPrivate.getCertificateBody());
assertEquals(ca.caPem(), exportedPrivate.getCertificateChain());
assertEquals(ca.caPem(), exportedPublic.getCertificateChain());
assertEquals(ca.caPem(), exportedEc.getCertificateChain());
assertTrue(exportedPrivate.getPrivateKey().startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"));
assertTrue(exportedEc.getPrivateKey().startsWith("-----BEGIN ENCRYPTED PRIVATE KEY-----"),
"an EC private key is exportable too");
}
@Test
void concurrentRequestsEachGetTheirOwnCertificateChainedToTheCa() throws Exception {
int threads = 16;
ExecutorService pool = Executors.newFixedThreadPool(threads);
CountDownLatch start = new CountDownLatch(1);
List<Future<Certificate>> futures = new ArrayList<>();
try {
for (int i = 0; i < threads; i++) {
String domain = "burst-" + i + ".example.test";
futures.add(pool.submit(() -> {
start.await();
return service.requestCertificate(domain, List.of(), ValidationMethod.DNS, null,
KeyAlgorithm.RSA_2048, null, null, null, REGION);
}));
}
start.countDown();
Set<String> arns = new HashSet<>();
Set<String> serials = new HashSet<>();
for (Future<Certificate> future : futures) {
Certificate cert = future.get(60, TimeUnit.SECONDS);
assertChainsToTheCa(cert);
arns.add(cert.getArn());
serials.add(cert.getSerial());
}
assertEquals(threads, arns.size(), "every request gets its own ARN");
assertEquals(threads, serials.size(), "every leaf gets its own serial");
assertEquals(threads, service.listCertificates(null, null, REGION, 100, null).certificates().size());
} finally {
pool.shutdownNow();
}
}
/**
* The certificate is a server leaf issued by the CA, the chain is exactly the CA's PEM, the pair
* builds a PKIX path with that chain as the only trust anchor, the stored private key belongs to
* the leaf, and every metadata field equals what the certificate itself says.
*/
private X509Certificate assertChainsToTheCa(Certificate cert) throws Exception {
X509Certificate leaf = generator.parseCertificate(cert.getCertificateBody());
assertEquals(ca.caPem(), cert.getCertificateChain(), "CertificateChain is the CA PEM");
assertEquals(ca.certificate().getSubjectX500Principal(), leaf.getIssuerX500Principal());
assertTrue(ca.isIssuedByUs(leaf), "signed by the CA key");
assertEquals(-1, leaf.getBasicConstraints(), "a leaf, not a CA");
assertEquals(SERVER_AND_CLIENT_AUTH, leaf.getExtendedKeyUsage());
X509Certificate anchor = generator.parseCertificate(cert.getCertificateChain());
PKIXParameters params = new PKIXParameters(Set.of(new TrustAnchor(anchor, null)));
params.setRevocationEnabled(false);
CertPathValidator.getInstance("PKIX").validate(
CertificateFactory.getInstance("X.509").generateCertPath(List.of(leaf)), params);
assertTrue(CertificateGenerator.isPair(generator.parsePrivateKey(cert.getPrivateKey()), leaf.getPublicKey()),
"the stored private key matches the certificate");
assertEquals(leaf.getSubjectX500Principal().getName(), cert.getSubject());
assertEquals(ca.certificate().getSubjectX500Principal().getName(), cert.getIssuer());
assertEquals(leaf.getSerialNumber(), new BigInteger(cert.getSerial().replace(":", ""), 16));
assertEquals(leaf.getNotBefore().toInstant(), cert.getNotBefore());
assertEquals(leaf.getNotAfter().toInstant(), cert.getNotAfter());
assertEquals("SHA512WITHRSA", cert.getSignatureAlgorithm(), "the RSA CA's signature, whatever the leaf key");
return leaf;
}
}
@@ -193,20 +193,28 @@ class CertificateGeneratorIssuerTest {
}
@Test
void existingSelfSignedAndAcmStylePathsAreUnchanged() throws Exception {
void existingSelfSignedPathIsUnchanged() throws Exception {
var selfSigned = generator.generateSelfSignedCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
X509Certificate ss = generator.parseCertificate(selfSigned.certificatePem());
assertEquals(ss.getSubjectX500Principal(), ss.getIssuerX500Principal());
assertTrue(ss.getBasicConstraints() >= 0);
assertNull(ss.getExtendedKeyUsage(), "the self-signed trust anchor carries no EKU, as before");
assertEquals(selfSigned.subject(), selfSigned.issuer());
assertTrue(selfSigned.serial().matches("([0-9a-f]{2}:)+[0-9a-f]{2}"));
ss.verify(ss.getPublicKey());
}
var acmStyle = generator.generateCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
X509Certificate acm = generator.parseCertificate(acmStyle.certificatePem());
assertTrue(acm.getIssuerX500Principal().getName().contains("Amazon"));
assertEquals(-1, acm.getBasicConstraints());
assertEquals("CN=Amazon,OU=Server CA 1B,O=Amazon,C=US", acmStyle.issuer());
assertTrue(acmStyle.serial().matches("([0-9a-f]{2}:)+[0-9a-f]{2}"));
@Test
void ecPrivateKeysAreWrittenAsPkcs8AndReadBack() throws Exception {
var ec = generator.generateIssuedCertificate("ec.example.test", List.of(), KeyAlgorithm.EC_secp384r1, null,
newIssuer(), CertificateGenerator.LeafUsage.SERVER);
var rsa = generator.generateIssuedCertificate("rsa.example.test", List.of(), KeyAlgorithm.RSA_2048, null,
newIssuer(), CertificateGenerator.LeafUsage.CLIENT);
assertTrue(ec.privateKeyPem().startsWith("-----BEGIN PRIVATE KEY-----"), "PKCS#8 carries the curve");
assertTrue(rsa.privateKeyPem().startsWith("-----BEGIN RSA PRIVATE KEY-----"), "RSA stays PKCS#1, as AWS IoT hands out");
assertTrue(CertificateGenerator.isPair(generator.parsePrivateKey(ec.privateKeyPem()),
generator.parseCertificate(ec.certificatePem()).getPublicKey()), "the EC key reads back and matches");
}
@Test
@@ -37,7 +37,7 @@ class CertificateGeneratorSanTypeTest {
@Test
void ipv4AddressEncodedAsIpAddressSanType() throws Exception {
var cert = generator.generateCertificate(
var cert = generator.generateSelfSignedCertificate(
"localhost",
List.of("localhost", "192.168.1.100"),
KeyAlgorithm.RSA_2048);
@@ -56,7 +56,7 @@ class CertificateGeneratorSanTypeTest {
@Test
void ipv6LoopbackEncodedAsIpAddressSanType() throws Exception {
var cert = generator.generateCertificate(
var cert = generator.generateSelfSignedCertificate(
"localhost",
List.of("localhost", "0.0.0.0", "::1"),
KeyAlgorithm.RSA_2048);
@@ -81,7 +81,7 @@ class CertificateGeneratorSanTypeTest {
@Test
void dnsNamesEncodedAsDnsNameSanType() throws Exception {
var cert = generator.generateCertificate(
var cert = generator.generateSelfSignedCertificate(
"localhost",
List.of("myhost.example.com", "floci"),
KeyAlgorithm.RSA_2048);
@@ -106,7 +106,7 @@ class CertificateGeneratorSanTypeTest {
@Test
void wildcardEncodedAsDnsNameSanType() throws Exception {
var cert = generator.generateCertificate(
var cert = generator.generateSelfSignedCertificate(
"localhost",
List.of("localhost", "*.localhost"),
KeyAlgorithm.RSA_2048);
@@ -123,7 +123,7 @@ class CertificateGeneratorSanTypeTest {
@Test
void mixedIpsAndDnsNamesEncodedCorrectly() throws Exception {
var cert = generator.generateCertificate(
var cert = generator.generateSelfSignedCertificate(
"localhost",
List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "floci", "10.0.0.5"),
KeyAlgorithm.RSA_2048);
@@ -10,18 +10,12 @@ import java.security.cert.X509Certificate;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies the distinction between the two certificate flavors:
* <ul>
* <li>{@code generateCertificate} mimics an ACM-issued cert (cosmetic Amazon issuer, not a CA)
* — unchanged legacy behavior, not verifiable as a trust anchor.</li>
* <li>{@code generateSelfSignedCertificate} is genuinely self-signed (issuer == subject) and a
* CA, so a client that trusts it can verify a TLS connection presenting it. This is what
* lets Floci's HTTPS endpoint be trusted by Lambda containers (CDK cfn-response callbacks).</li>
* </ul>
* {@code generateSelfSignedCertificate} is genuinely self-signed (issuer == subject) and a CA, so
* a client that trusts it can verify a TLS connection presenting it. Leaves that clients must
* validate are issued by a CA through {@code generateIssuedCertificate} instead.
*/
class CertificateGeneratorSelfSignedTest {
@@ -51,18 +45,4 @@ class CertificateGeneratorSelfSignedTest {
// Sanity: the self-signature verifies against the cert's own public key.
cert.verify(cert.getPublicKey());
}
@Test
void acmStyleCertificateKeepsCosmeticAmazonIssuerAndIsNotACa() throws Exception {
var generated = generator.generateCertificate(
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
X509Certificate cert = generator.parseCertificate(generated.certificatePem());
assertNotEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal(),
"ACM-style cert keeps a cosmetic Amazon issuer distinct from the subject");
assertTrue(cert.getIssuerX500Principal().getName().contains("Amazon"),
"ACM-style issuer should still be the Amazon CA DN");
assertEquals(-1, cert.getBasicConstraints(), "ACM-style leaf cert must not be a CA");
}
}
@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* CreateDomainName hands the new hostname to the TLS certificate manager on the real wire path,
* so a client that verifies the domain's name over HTTPS is served without a restart. The
* manager is mocked: what it does with the name is its own test's business.
*/
@QuarkusTest
class ApiGatewayDomainEnsureHostIntegrationTest {
@InjectMock
TlsCertificateManager certificateManager;
@Test
void regionalDomainRegistersTheHostnameForTls() {
String domain = "api-" + System.nanoTime() + ".dev.localhost.floci.io";
given()
.contentType(ContentType.JSON)
.body("{\"domainName\":\"" + domain + "\","
+ "\"regionalCertificateArn\":\"arn:aws:acm:us-east-1:000000000000:certificate/abc\","
+ "\"endpointConfiguration\":{\"types\":[\"REGIONAL\"]}}")
.when().post("/domainnames")
.then()
.statusCode(201);
verify(certificateManager).ensureHost(domain);
}
@Test
void edgeDomainRegistersTheHostnameForTls() {
String domain = "edge-" + System.nanoTime() + ".dev.localhost.floci.io";
given()
.contentType(ContentType.JSON)
.body("{\"domainName\":\"" + domain + "\","
+ "\"certificateArn\":\"arn:aws:acm:us-east-1:000000000000:certificate/abc\","
+ "\"endpointConfiguration\":{\"types\":[\"EDGE\"]}}")
.when().post("/domainnames")
.then()
.statusCode(201);
verify(certificateManager).ensureHost(domain);
}
@Test
void rejectedCreateRegistersNothing() {
given()
.contentType(ContentType.JSON)
.body("{\"domainName\":\"private-" + System.nanoTime() + ".dev.localhost.floci.io\","
+ "\"endpointConfiguration\":{\"types\":[\"PRIVATE\"]}}")
.when().post("/domainnames")
.then()
.statusCode(400);
verify(certificateManager, never()).ensureHost(anyString());
}
}
@@ -0,0 +1,148 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* The contract between CreateDomainName and the TLS certificate manager: the exact domain name
* is handed over once, after the domain is stored and with no service lock held, and never for a
* request AWS would reject. Later operations on the domain do not register anything again.
*/
class ApiGatewayDomainTlsServiceTest {
private static final String REGION = "us-east-1";
private static final String CERTIFICATE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";
private TlsCertificateManager certificateManager;
private ApiGatewayService service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
certificateManager = mock(TlsCertificateManager.class);
service = new ApiGatewayService(storageFactory, mock(EmulatorConfig.class), certificateManager);
}
private static Map<String, Object> regional(String domain) {
return Map.of("domainName", domain, "regionalCertificateArn", CERTIFICATE_ARN,
"endpointConfiguration", Map.of("types", List.of("REGIONAL")));
}
@Test
void createHandsTheExactDomainNameOverOnce() {
service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));
verify(certificateManager).ensureHost("api.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
@Test
void wildcardDomainIsHandedOverAsApiGatewaySpellsIt() {
service.createDomainName(REGION, regional("*.dev.localhost.floci.io"));
verify(certificateManager).ensureHost("*.dev.localhost.floci.io");
}
@Test
void edgeDomainIsHandedOverToo() {
service.createDomainName(REGION, Map.of("domainName", "edge.dev.localhost.floci.io",
"certificateArn", CERTIFICATE_ARN, "endpointConfiguration", Map.of("types", List.of("EDGE"))));
verify(certificateManager).ensureHost("edge.dev.localhost.floci.io");
}
@Test
void domainIsStoredBeforeTheCertificateIsExtended() {
doAnswer(invocation -> {
assertNotNull(service.getDomainName(REGION, "api.dev.localhost.floci.io"),
"GetDomainName must already find the domain while the certificate reloads");
return null;
}).when(certificateManager).ensureHost(anyString());
service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));
verify(certificateManager).ensureHost("api.dev.localhost.floci.io");
}
@Test
void duplicateNameIsRejectedBeforeTheHook() {
service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));
AwsException failure = assertThrows(AwsException.class,
() -> service.createDomainName("eu-west-1", regional("api.dev.localhost.floci.io")));
assertEquals("BadRequestException", failure.getErrorCode());
verify(certificateManager).ensureHost("api.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
@Test
void privateEndpointTypeIsRejectedBeforeTheHook() {
assertThrows(AwsException.class, () -> service.createDomainName(REGION, Map.of(
"domainName", "private.dev.localhost.floci.io",
"endpointConfiguration", Map.of("types", List.of("PRIVATE")))));
verifyNoInteractions(certificateManager);
}
@Test
void laterOperationsOnTheDomainRegisterNothingAgain() {
service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));
service.updateDomainName(REGION, "api.dev.localhost.floci.io",
List.of(Map.of("op", "replace", "path", "/securityPolicy", "value", "TLS_1_0")));
service.getDomainName(REGION, "api.dev.localhost.floci.io");
service.deleteDomainName(REGION, "api.dev.localhost.floci.io");
verify(certificateManager).ensureHost("api.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
/**
* The reissue blocks until the HTTPS listener has switched certificates. A second create that
* arrives meanwhile must not queue behind it, so the hook runs outside the uniqueness lock.
*/
@Test
void noServiceLockIsHeldWhileTheCertificateReloads() throws Exception {
AtomicBoolean nested = new AtomicBoolean();
Thread[] concurrent = new Thread[1];
doAnswer(invocation -> {
if (nested.compareAndSet(false, true)) {
concurrent[0] = new Thread(() -> service.createDomainName(REGION, regional("other.dev.localhost.floci.io")));
concurrent[0].start();
concurrent[0].join(5000);
assertFalse(concurrent[0].isAlive(), "a create must not wait for another create's TLS reload");
}
return null;
}).when(certificateManager).ensureHost(anyString());
service.createDomainName(REGION, regional("api.dev.localhost.floci.io"));
verify(certificateManager).ensureHost("api.dev.localhost.floci.io");
verify(certificateManager).ensureHost("other.dev.localhost.floci.io");
assertNotNull(service.getDomainName(REGION, "other.dev.localhost.floci.io"));
}
}
@@ -0,0 +1,170 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* A stack that creates the three custom domain types hands every domain to the TLS certificate
* manager through the same service methods the API uses. A rename replaces the domain, so the
* new name is registered too; an in-place update and the stack delete register nothing.
*/
@QuarkusTest
class CfnCustomDomainEnsureHostIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
private static final String STACK = "custom-domain-ensure-host-cfn-it";
private static final String SUFFIX = ".ensure-host-cfn-it.localhost.floci.io";
private static final String API_DOMAIN = "api" + SUFFIX;
private static final String RENAMED_API_DOMAIN = "gateway" + SUFFIX;
private static final String IOT_DOMAIN = "iot" + SUFFIX;
private static final String AUTH_DOMAIN = "auth" + SUFFIX;
private static final String TEMPLATE = """
{
"Parameters": {
"ApiDomainName": {"Type": "String"},
"IotStatus": {"Type": "String", "Default": "ENABLED"}
},
"Resources": {
"Cert": {
"Type": "AWS::CertificateManager::Certificate",
"Properties": {"DomainName": "*%1$s", "ValidationMethod": "DNS"}
},
"ApiDomain": {
"Type": "AWS::ApiGateway::DomainName",
"Properties": {
"DomainName": {"Ref": "ApiDomainName"},
"EndpointConfiguration": {"Types": ["REGIONAL"]},
"RegionalCertificateArn": {"Ref": "Cert"}
}
},
"IotDomain": {
"Type": "AWS::IoT::DomainConfiguration",
"Properties": {
"DomainConfigurationName": "ensure-host-cfn-it",
"DomainName": "%2$s",
"ServerCertificateArns": [{"Ref": "Cert"}],
"DomainConfigurationStatus": {"Ref": "IotStatus"}
}
},
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {"UserPoolName": "ensure-host-cfn-it-pool"}
},
"AuthDomain": {
"Type": "AWS::Cognito::UserPoolDomain",
"Properties": {
"Domain": "%3$s",
"UserPoolId": {"Ref": "Pool"},
"CustomDomainConfig": {"CertificateArn": {"Fn::GetAtt": ["Cert", "CertificateArn"]}}
}
}
}
}
""".formatted(SUFFIX, IOT_DOMAIN, AUTH_DOMAIN);
@InjectMock
TlsCertificateManager certificateManager;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void stackRegistersEveryCustomDomainAndAReplacementButNotAnInPlaceUpdateOrTheDelete() throws Exception {
cloudFormation("CreateStack", Map.of("ApiDomainName", API_DOMAIN));
awaitStackStatus("CREATE_COMPLETE");
verify(certificateManager).ensureHost(API_DOMAIN);
verify(certificateManager).ensureHost(IOT_DOMAIN);
verify(certificateManager).ensureHost(AUTH_DOMAIN);
verifyNoMoreInteractions(certificateManager);
cloudFormation("UpdateStack", Map.of("ApiDomainName", API_DOMAIN, "IotStatus", "DISABLED"));
awaitStackStatus("UPDATE_COMPLETE");
verifyNoMoreInteractions(certificateManager);
cloudFormation("UpdateStack", Map.of("ApiDomainName", RENAMED_API_DOMAIN, "IotStatus", "DISABLED"));
awaitStackStatus("UPDATE_COMPLETE");
verify(certificateManager).ensureHost(RENAMED_API_DOMAIN);
verifyNoMoreInteractions(certificateManager);
cloudFormation("DeleteStack", Map.of());
awaitStackDeleted();
verifyNoMoreInteractions(certificateManager);
}
private static void cloudFormation(String action, Map<String, String> parameters) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", STACK);
if (!"DeleteStack".equals(action)) {
request.formParam("TemplateBody", TEMPLATE);
}
int index = 1;
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
index++;
}
request.when().post("/").then().statusCode(200);
}
private static String describeStack() {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().extract().asString();
}
/** Stack operations run on a background executor; wait for the terminal status. */
private static void awaitStackStatus(String expected) throws InterruptedException {
String body = "";
for (int i = 0; i < 200; i++) {
body = describeStack();
if (body.contains("<StackStatus>" + expected + "</StackStatus>")) {
return;
}
if (body.contains("FAILED</StackStatus>") || body.contains("ROLLBACK_COMPLETE</StackStatus>")) {
fail("stack did not reach " + expected + ": " + body);
}
Thread.sleep(50);
}
fail("stack did not reach " + expected + " within the timeout: " + body);
}
private static void awaitStackDeleted() throws InterruptedException {
for (int i = 0; i < 200; i++) {
String body = describeStack();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("stack " + STACK + " was not deleted within the timeout");
}
}
@@ -0,0 +1,108 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* CreateUserPoolDomain hands a custom domain to the TLS certificate manager on the real wire
* path. A prefix domain lives under {@code auth.<region>.amazoncognito.com} on AWS, a name Floci
* does not serve, so it is left alone. The certificate must be an issued ACM certificate, as on
* AWS, so each custom domain requests one first.
*/
@QuarkusTest
class CognitoDomainEnsureHostIntegrationTest {
private static final String UNKNOWN_CERTIFICATE_ARN =
"arn:aws:acm:us-east-1:000000000000:certificate/00000000-0000-0000-0000-000000000000";
@InjectMock
TlsCertificateManager certificateManager;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void customDomainRegistersTheHostnameForTls() throws Exception {
String poolId = createPool();
String domain = "auth-" + System.nanoTime() + ".dev.localhost.floci.io";
cognitoJson("CreateUserPoolDomain", """
{
"Domain": "%s",
"UserPoolId": "%s",
"CustomDomainConfig": {"CertificateArn": "%s"}
}
""".formatted(domain, poolId, requestCertificate(domain)));
verify(certificateManager).ensureHost(domain);
}
@Test
void certificateUnknownToAcmRegistersNothing() throws Exception {
String poolId = createPool();
cognitoAction("CreateUserPoolDomain", """
{
"Domain": "nocert-%s.dev.localhost.floci.io",
"UserPoolId": "%s",
"CustomDomainConfig": {"CertificateArn": "%s"}
}
""".formatted(System.nanoTime(), poolId, UNKNOWN_CERTIFICATE_ARN))
.then()
.statusCode(400);
verify(certificateManager, never()).ensureHost(anyString());
}
@Test
void prefixDomainRegistersNothing() throws Exception {
String poolId = createPool();
cognitoJson("CreateUserPoolDomain", """
{
"Domain": "prefix-%s",
"UserPoolId": "%s"
}
""".formatted(System.nanoTime(), poolId));
verify(certificateManager, never()).ensureHost(anyString());
}
@Test
void rejectedCreateRegistersNothing() {
cognitoAction("CreateUserPoolDomain", """
{
"Domain": "orphan-%s.dev.localhost.floci.io",
"UserPoolId": "us-east-1_missing",
"CustomDomainConfig": {"CertificateArn": "%s"}
}
""".formatted(System.nanoTime(), UNKNOWN_CERTIFICATE_ARN))
.then()
.statusCode(400);
verify(certificateManager, never()).ensureHost(anyString());
}
private static String requestCertificate(String domain) throws Exception {
return RestAssuredJsonUtils.awsActionJson("CertificateManager", "RequestCertificate",
"{\"DomainName\": \"" + domain + "\", \"ValidationMethod\": \"DNS\"}").path("CertificateArn").asText();
}
private static String createPool() throws Exception {
JsonNode pool = cognitoJson("CreateUserPool", "{\"PoolName\": \"EnsureHostPool\"}");
return pool.path("UserPool").path("Id").asText();
}
}
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.services.cognito;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.acm.model.Certificate;
import io.github.hectorvent.floci.services.acm.model.CertificateStatus;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* The contract between CreateUserPoolDomain and the TLS certificate manager: a custom domain is
* handed over once, after it is stored and with no service lock held; a prefix domain, a rejected
* request and every later operation register nothing. The test-only constructor without a manager keeps working. A
* certificate ACM does not know, or has not issued, is refused before the hook, as on AWS.
*/
class CognitoDomainTlsServiceTest {
private static final String REGION = "us-east-1";
private static final String CERTIFICATE_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/abc";
private static final Map<String, Object> CUSTOM = Map.of("CertificateArn", CERTIFICATE_ARN);
private final RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
private final TlsCertificateManager certificateManager = mock(TlsCertificateManager.class);
private final AcmService acmService = mock(AcmService.class);
private CognitoService service;
private String poolId;
@BeforeEach
void setUp() {
// Every certificate exists and is issued unless a test says otherwise.
when(acmService.describeCertificate(anyString(), eq(REGION))).thenAnswer(invocation -> {
Certificate certificate = new Certificate();
certificate.setArn(invocation.getArgument(0));
certificate.setStatus(CertificateStatus.ISSUED);
return certificate;
});
service = new CognitoService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
"http://localhost:4566", regionResolver, null, acmService, null, null, certificateManager);
poolId = service.createUserPool(Map.of("PoolName", "tls-pool"), REGION).getId();
}
@Test
void customDomainIsHandedOverOnce() {
UserPoolDomain created = service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);
assertTrue(created.isCustomDomain());
verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
@Test
void prefixDomainRegistersNothing() {
service.createUserPoolDomain("my-prefix", poolId, null, null);
verifyNoInteractions(certificateManager);
}
@Test
void customDomainWithoutACertificateIsRejectedBeforeTheHook() {
Map<String, Object> noCertificate = new HashMap<>();
noCertificate.put("CertificateArn", null);
AwsException failure = assertThrows(AwsException.class,
() -> service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, noCertificate, null));
assertEquals("InvalidParameterException", failure.getErrorCode());
verifyNoInteractions(certificateManager);
}
@Test
void certificateUnknownToAcmIsRejectedBeforeTheHook() {
when(acmService.describeCertificate(anyString(), eq(REGION)))
.thenThrow(new AwsException("ResourceNotFoundException", "no such certificate", 400));
AwsException failure = assertThrows(AwsException.class,
() -> service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null));
assertEquals("InvalidParameterException", failure.getErrorCode());
verifyNoInteractions(certificateManager);
}
@Test
void certificateNotYetIssuedIsRejectedBeforeTheHook() {
when(acmService.describeCertificate(anyString(), eq(REGION))).thenAnswer(invocation -> {
Certificate pending = new Certificate();
pending.setArn(invocation.getArgument(0));
pending.setStatus(CertificateStatus.PENDING_VALIDATION);
return pending;
});
assertThrows(AwsException.class,
() -> service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null));
verifyNoInteractions(certificateManager);
}
@Test
void unknownPoolIsRejectedBeforeTheHook() {
assertThrows(AwsException.class,
() -> service.createUserPoolDomain("auth.dev.localhost.floci.io", "us-east-1_missing", CUSTOM, null));
verifyNoInteractions(certificateManager);
}
@Test
void duplicateDomainIsRejectedBeforeTheHook() {
service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);
String otherPool = service.createUserPool(Map.of("PoolName", "other-pool"), REGION).getId();
AwsException failure = assertThrows(AwsException.class,
() -> service.createUserPoolDomain("auth.dev.localhost.floci.io", otherPool, CUSTOM, null));
assertEquals("InvalidParameterException", failure.getErrorCode());
verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
@Test
void domainIsStoredBeforeTheCertificateIsExtended() {
doAnswer(invocation -> {
assertNotNull(service.describeUserPoolDomain("auth.dev.localhost.floci.io"),
"DescribeUserPoolDomain must already find the domain while the certificate reloads");
return null;
}).when(certificateManager).ensureHost(anyString());
service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);
verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");
}
@Test
void laterOperationsOnTheDomainRegisterNothingAgain() {
service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);
service.updateUserPoolDomain("auth.dev.localhost.floci.io", poolId,
Map.of("CertificateArn", CERTIFICATE_ARN + "-renewed"), 2);
service.describeUserPoolDomain("auth.dev.localhost.floci.io");
service.deleteUserPoolDomain("auth.dev.localhost.floci.io", poolId);
verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
/** The reissue blocks on the HTTPS listener; a concurrent create must not queue behind it. */
@Test
void noServiceLockIsHeldWhileTheCertificateReloads() throws Exception {
String otherPool = service.createUserPool(Map.of("PoolName", "other-pool"), REGION).getId();
AtomicBoolean nested = new AtomicBoolean();
Thread[] concurrent = new Thread[1];
doAnswer(invocation -> {
if (nested.compareAndSet(false, true)) {
concurrent[0] = new Thread(() -> service.createUserPoolDomain("other.dev.localhost.floci.io", otherPool, CUSTOM, null));
concurrent[0].start();
concurrent[0].join(5000);
assertFalse(concurrent[0].isAlive(), "a create must not wait for another create's TLS reload");
}
return null;
}).when(certificateManager).ensureHost(anyString());
service.createUserPoolDomain("auth.dev.localhost.floci.io", poolId, CUSTOM, null);
verify(certificateManager).ensureHost("auth.dev.localhost.floci.io");
verify(certificateManager).ensureHost("other.dev.localhost.floci.io");
assertNotNull(service.describeUserPoolDomain("other.dev.localhost.floci.io"));
}
@Test
void constructorWithoutAManagerStillCreatesCustomDomains() {
CognitoService bare = new CognitoService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", regionResolver, null, acmService);
String pool = bare.createUserPool(Map.of("PoolName", "bare-pool"), REGION).getId();
UserPoolDomain created = bare.createUserPoolDomain("auth.dev.localhost.floci.io", pool, CUSTOM, null);
assertTrue(created.isCustomDomain());
assertNotNull(created.getCloudFrontDistribution());
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
@@ -1410,7 +1411,8 @@ class CognitoServiceTest {
null,
acmService,
verificationCodeService,
messageDispatcher
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
@@ -1450,7 +1452,8 @@ class CognitoServiceTest {
null,
acmService,
verificationCodeService,
messageDispatcher
messageDispatcher,
mock(TlsCertificateManager.class)
);
UserPool pool = serviceWithVerification.createUserPool(Map.of("PoolName", "TestPool"), "us-east-1");
@@ -2921,7 +2924,8 @@ class CognitoServiceTest {
null,
acmService,
verificationCodeService,
messageDispatcher
messageDispatcher,
mock(TlsCertificateManager.class)
);
}
}
@@ -3508,7 +3512,7 @@ class CognitoServiceTest {
CognitoService ambiguous = new CognitoService(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), domains, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", regionResolver, null,
acmService, null, null);
acmService, null, null, mock(TlsCertificateManager.class));
assertTrue(ambiguous.findCustomDomain("auth.dup.localhost.floci.io").isEmpty());
}
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* CreateDomainConfiguration hands a customer-managed domain name to the TLS certificate manager
* on the real wire path. A configuration without a domain name describes the account's default
* endpoint, which Floci already serves, so nothing is registered for it.
*/
@QuarkusTest
class IotDomainConfigurationEnsureHostIntegrationTest {
private static final String CERTIFICATE_ARN =
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
@InjectMock
TlsCertificateManager certificateManager;
@Test
void customerManagedDomainRegistersTheHostnameForTls() {
String domain = "iot-" + System.nanoTime() + ".dev.localhost.floci.io";
given()
.contentType("application/json")
.body("""
{
"domainName": "%s",
"serverCertificateArns": ["%s"]
}
""".formatted(domain, CERTIFICATE_ARN))
.when()
.post("/domainConfigurations/ensure-host-" + System.nanoTime())
.then()
.statusCode(200);
verify(certificateManager).ensureHost(domain);
}
@Test
void endpointTypeConfigurationWithoutADomainNameRegistersNothing() {
given()
.contentType("application/json")
.body("{}")
.when()
.post("/domainConfigurations/ensure-host-endpoint-" + System.nanoTime())
.then()
.statusCode(200);
verify(certificateManager, never()).ensureHost(anyString());
}
@Test
void rejectedCreateRegistersNothing() {
given()
.contentType("application/json")
.body("""
{
"domainName": "no-cert-%s.dev.localhost.floci.io"
}
""".formatted(System.nanoTime()))
.when()
.post("/domainConfigurations/ensure-host-no-cert-" + System.nanoTime())
.then()
.statusCode(400);
verify(certificateManager, never()).ensureHost(anyString());
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
@@ -39,7 +40,8 @@ class IotDomainConfigurationServiceTest {
private final ObjectMapper mapper = new ObjectMapper();
private final IotDomainConfigurationService service = new IotDomainConfigurationService(
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig());
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig(),
mock(TlsCertificateManager.class));
private static EmulatorConfig endpointConfig() {
EmulatorConfig config = mock(EmulatorConfig.class);
@@ -0,0 +1,147 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.TlsCertificateManager;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/**
* The contract between CreateDomainConfiguration and the TLS certificate manager: a
* customer-managed domain name is handed over once, after the configuration is stored and with
* no service lock held; an ENDPOINT configuration, the AWS-managed configurations, a rejected
* request and every later operation register nothing.
*/
class IotDomainConfigurationTlsServiceTest {
private static final String REGION = "us-east-1";
private static final String CERTIFICATE_ARN =
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
private final ObjectMapper mapper = new ObjectMapper();
private final TlsCertificateManager certificateManager = mock(TlsCertificateManager.class);
private final IotDomainConfigurationService service = new IotDomainConfigurationService(
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig(), certificateManager);
private static EmulatorConfig endpointConfig() {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
return config;
}
private ObjectNode customDomain(String domainName) {
ObjectNode request = mapper.createObjectNode().put("domainName", domainName);
request.putArray("serverCertificateArns").add(CERTIFICATE_ARN);
return request;
}
@Test
void customerManagedDomainIsHandedOverOnce() {
service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);
verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
@Test
void endpointConfigurationRegistersNothing() {
service.createDomainConfiguration("endpoint", mapper.createObjectNode(), REGION);
service.createDomainConfiguration("null-body", null, REGION);
verifyNoInteractions(certificateManager);
}
@Test
void awsManagedConfigurationsRegisterNothing() {
assertEquals("AWS_MANAGED", service.describeDomainConfiguration("iot:Data-ATS", REGION).getDomainType());
verifyNoInteractions(certificateManager);
}
@Test
void domainWithoutACertificateIsRejectedBeforeTheHook() {
AwsException failure = assertThrows(AwsException.class, () -> service.createDomainConfiguration(
"no-cert", mapper.createObjectNode().put("domainName", "iot.dev.localhost.floci.io"), REGION));
assertEquals("InvalidRequestException", failure.getErrorCode());
verifyNoInteractions(certificateManager);
}
@Test
void duplicateNameIsRejectedBeforeTheHook() {
service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);
AwsException failure = assertThrows(AwsException.class,
() -> service.createDomainConfiguration("iot", customDomain("again.dev.localhost.floci.io"), REGION));
assertEquals("ResourceAlreadyExistsException", failure.getErrorCode());
verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
@Test
void configurationIsStoredBeforeTheCertificateIsExtended() {
doAnswer(invocation -> {
assertNotNull(service.describeDomainConfiguration("iot", REGION),
"DescribeDomainConfiguration must already find the configuration while the certificate reloads");
return null;
}).when(certificateManager).ensureHost(anyString());
service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);
verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");
}
@Test
void laterOperationsOnTheConfigurationRegisterNothingAgain() {
service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);
service.updateDomainConfiguration("iot",
mapper.createObjectNode().put("domainConfigurationStatus", "DISABLED"), REGION);
service.describeDomainConfiguration("iot", REGION);
service.deleteDomainConfiguration("iot", REGION);
verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");
verifyNoMoreInteractions(certificateManager);
}
/** The reissue blocks on the HTTPS listener; a concurrent create must not queue behind it. */
@Test
void noServiceLockIsHeldWhileTheCertificateReloads() throws Exception {
AtomicBoolean nested = new AtomicBoolean();
Thread[] concurrent = new Thread[1];
doAnswer(invocation -> {
if (nested.compareAndSet(false, true)) {
concurrent[0] = new Thread(() -> service.createDomainConfiguration(
"other", customDomain("other.dev.localhost.floci.io"), REGION));
concurrent[0].start();
concurrent[0].join(5000);
assertFalse(concurrent[0].isAlive(), "a create must not wait for another create's TLS reload");
}
return null;
}).when(certificateManager).ensureHost(anyString());
service.createDomainConfiguration("iot", customDomain("iot.dev.localhost.floci.io"), REGION);
verify(certificateManager).ensureHost("iot.dev.localhost.floci.io");
verify(certificateManager).ensureHost("other.dev.localhost.floci.io");
assertNotNull(service.describeDomainConfiguration("other", REGION));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.lambda.launcher;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
@@ -84,9 +85,7 @@ class ContainerLauncherCaTrustTest {
void resolveCaCertPath_acceptsButWarnsForUserLeafCert() throws Exception {
// A leaf/server cert (issuer != subject, not a CA) is still accepted so trust injection
// proceeds; the warning is logged. Here we assert it is accepted and is NOT a self-signed CA.
Path leaf = writeCert(tempDir.resolve("leaf.crt"),
new CertificateGenerator().generateCertificate(
"floci-leaf", List.of(), KeyAlgorithm.RSA_2048).certificatePem());
Path leaf = writeLeaf("leaf.crt", "floci-leaf");
Optional<Path> resolved = ContainerLauncher.resolveFlociCaCertPath(
true, Optional.of(leaf.toString()), tempDir.toString());
@@ -127,9 +126,7 @@ class ContainerLauncherCaTrustTest {
@Test
void isSelfSignedCaCertificate_falseForLeafCert() throws Exception {
Path leaf = writeCert(tempDir.resolve("leaf2.crt"),
new CertificateGenerator().generateCertificate(
"floci-leaf2", List.of(), KeyAlgorithm.RSA_2048).certificatePem());
Path leaf = writeLeaf("leaf2.crt", "floci-leaf2");
assertFalse(ContainerLauncher.isSelfSignedCaCertificate(leaf));
}
@@ -144,4 +141,11 @@ class ContainerLauncherCaTrustTest {
private static Path writeCert(Path path, String pem) throws Exception {
return Files.writeString(path, pem);
}
/** A server leaf issued by a throwaway CA: its issuer differs from its subject and it is not a CA. */
private Path writeLeaf(String fileName, String commonName) throws Exception {
FlociCertificateAuthority throwawayCa = FlociCertificateAuthority.loadOrCreate(tempDir.resolve("throwaway-ca"));
return writeCert(tempDir.resolve(fileName),
throwawayCa.issueServerCertificate(commonName, List.of(), KeyAlgorithm.RSA_2048, null).certificatePem());
}
}