mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(tls): a local root CA that signs Floci's server certificate (#3078)
* refactor(acm): one issuer-signing primitive in CertificateGenerator
buildCertificate always signed with the subject's own key. signCertificate now
takes the issuer DN and key explicitly; generateCaCertificate and
generateIssuedCertificate sit on top of it, with serverAuth or clientAuth EKU on
leaves. Existing public methods keep their signatures and output; metadata now
follows ACM: colon-separated hex serial and the certificate's real signature
algorithm in upper case.
* refactor(cloudhsmv2): sign emulated hardware certificates through CertificateGenerator
Deletes the private generateCert copy; the shared primitive also marks the two
CA levels of the chain as CAs, which the old code did not.
* refactor(acm): normalize imported certificate metadata and check issued key relationships
ImportCertificate now stores the serial as colon-separated hex and the
signature algorithm in upper case, the same shape generated certificates
report. generateIssuedCertificate verifies the leaf against the issuer's
certificate and refuses a supplied key pair whose halves do not match.
* refactor(acm): refuse a supplied key pair that is not of the requested algorithm
* refactor(acm): match a supplied EC key pair by named curve, not field size
* feat(tls): FlociCertificateAuthority, a persistent local root CA
Loads or creates {persistent-path}/tls/floci-root-ca.{crt,key} with an
owner-only key, signs serverAuth and clientAuth leaves through
CertificateGenerator, and regenerates with a WARN when the pair is corrupt,
expired, not a CA, or the key does not match the certificate. A CDI producer
exposes the same pair to beans, using the directory the config bootstrap used.
* feat(tls): issue the HTTPS server certificate from the local CA
The leaf is floci-server.{crt,key}, signed by floci-root-ca; a pre-CA
self-signed leaf, a leaf from a regenerated CA and an expired leaf are replaced
on boot. Published through quarkus.tls.key-store.pem.0.* so the TLS registry
owns it and can reload it. The server key is written owner-only.
* feat: serve the local CA at GET /_floci/ca.pem
TlsLocalCaIntegrationTest boots the HTTP server on the TLS registry keys and
completes a handshake trusting only the PEM this endpoint serves.
* fix(lambda): inject the local root CA into containers instead of the server leaf
The leaf will be reissued as SANs grow; pinning it would break after the first
reissue. The CA is stable.
* docs(tls): trust the local CA once instead of disabling verification
* feat(tls): create private key files owner-only and log why a CA was regenerated
* feat(tls): serve the user certificate from ca.pem in custom-cert mode, log the CA fingerprint
With floci.tls.cert-path set, GET /_floci/ca.pem returns that file, the same
file the Lambda launcher mounts, and creates no local CA. The CA's SHA-256
fingerprint is logged at startup so an out-of-band copy can be checked, and a
file system without POSIX permissions gets a WARN instead of a silent default.
* feat(tls): ca.pem is a bundle in custom-cert mode; clear the bootstrap directory on every boot
With a user-provided certificate the endpoint returns that file followed by
the local CA, so both the HTTPS endpoint and anything Floci issues validate
from one file. TlsConfigSource resets its resolved directory on construction
so a later boot in the same JVM with TLS off or a user certificate never
reuses a stale value.
* docs(lambda): drop two em-dashes from the CA trust javadoc
* test(tls): cover an expired leaf, an expired CA, a missing CA key and the producer's directory choice
* docs(tls): describe IoT device certificates as a follow-up of the local CA
This commit is contained in:
1 parent
4e05fdf582
commit
3c6c005ff1
21 files changed
+1019
-150
No files matched your search
+59
@@ -0,0 +1,59 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The producer must hand beans the directory the config bootstrap used, and only fall back to the
|
||||
* configured persistent path when the bootstrap laid nothing down.
|
||||
*/
|
||||
class FlociCertificateAuthorityProducerTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@AfterEach
|
||||
void clearBootstrap() {
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
new TlsConfigSource();
|
||||
}
|
||||
|
||||
private static EmulatorConfig configWithPersistentPath(String path) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
|
||||
when(config.storage()).thenReturn(storage);
|
||||
when(storage.persistentPath()).thenReturn(path);
|
||||
return config;
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesTheBootstrapDirectoryWhenTheBootstrapIssuedTheLeaf() {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
new TlsConfigSource();
|
||||
|
||||
Path dir = FlociCertificateAuthorityProducer.tlsDir(configWithPersistentPath("/elsewhere/from/yaml"));
|
||||
|
||||
assertEquals(tempDir.resolve("tls"), dir, "one directory for the served leaf and ca.pem, or two CAs would exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToTheConfiguredPathWhenTlsIsOff() {
|
||||
System.setProperty("floci.tls.enabled", "false");
|
||||
new TlsConfigSource();
|
||||
|
||||
Path dir = FlociCertificateAuthorityProducer.tlsDir(configWithPersistentPath(tempDir.toString()));
|
||||
|
||||
assertEquals(tempDir.resolve("tls"), dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
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.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
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;
|
||||
|
||||
class FlociCertificateAuthorityTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void createsCaFilesWithOwnerOnlyKey() throws Exception {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertTrue(Files.exists(tempDir.resolve("floci-root-ca.crt")));
|
||||
assertTrue(Files.exists(tempDir.resolve("floci-root-ca.key")));
|
||||
assertEquals(tempDir.resolve("floci-root-ca.crt"), ca.certificatePath());
|
||||
assertTrue(ca.certificate().getBasicConstraints() >= 0, "CA must be cA=true");
|
||||
assertTrue(ca.certificate().getKeyUsage()[5], "CA must assert keyCertSign");
|
||||
assertEquals(ca.certificate().getSubjectX500Principal(), ca.certificate().getIssuerX500Principal());
|
||||
assertEquals("CN=Floci Local CA", ca.certificate().getSubjectX500Principal().getName());
|
||||
assertTrue(ca.caPem().startsWith("-----BEGIN CERTIFICATE-----"));
|
||||
assertEquals(Files.readString(tempDir.resolve("floci-root-ca.crt")), ca.caPem(), "caPem is the file's bytes");
|
||||
assertTrue(ca.fingerprint().matches("([0-9A-F]{2}:){31}[0-9A-F]{2}"), ca.fingerprint());
|
||||
assertEquals(ca.fingerprint(), FlociCertificateAuthority.loadOrCreate(tempDir).fingerprint());
|
||||
|
||||
Set<PosixFilePermission> keyPerms = Files.getPosixFilePermissions(tempDir.resolve("floci-root-ca.key"));
|
||||
assertEquals(PosixFilePermissions.fromString("rw-------"), keyPerms);
|
||||
assertEquals(PosixFilePermissions.fromString("rwx------"), Files.getPosixFilePermissions(tempDir));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsTheDirectoryWhenMissing() {
|
||||
Path tlsDir = tempDir.resolve("nested").resolve("tls");
|
||||
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
|
||||
assertTrue(Files.exists(tlsDir.resolve("floci-root-ca.key")));
|
||||
assertTrue(ca.isIssuedByUs(parse(ca.issueClientCertificate("device").certificatePem())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadsTheSameCaAcrossRestarts() throws Exception {
|
||||
FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
Files.setPosixFilePermissions(tempDir.resolve("floci-root-ca.key"), PosixFilePermissions.fromString("rw-r--r--"));
|
||||
|
||||
FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertEquals(first.certificate(), second.certificate());
|
||||
assertEquals(first.key(), second.key());
|
||||
assertEquals(first.caPem(), second.caPem());
|
||||
assertEquals(PosixFilePermissions.fromString("rw-------"),
|
||||
Files.getPosixFilePermissions(tempDir.resolve("floci-root-ca.key")), "permissions are re-tightened on load");
|
||||
}
|
||||
|
||||
@Test
|
||||
void corruptCaIsRegeneratedNotSilentlyKept() throws Exception {
|
||||
FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.crt"), "-----BEGIN CERTIFICATE-----\nnope\n-----END CERTIFICATE-----\n");
|
||||
|
||||
FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertNotEquals(first.certificate(), second.certificate());
|
||||
assertTrue(second.certificate().getBasicConstraints() >= 0);
|
||||
assertEquals(second.caPem(), Files.readString(tempDir.resolve("floci-root-ca.crt")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyThatDoesNotMatchTheCertificateIsRegenerated() throws Exception {
|
||||
FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
var stranger = new CertificateGenerator().generateCaCertificate("Other CA");
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.key"), stranger.privateKeyPem());
|
||||
|
||||
FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertNotEquals(first.certificate(), second.certificate(), "a pair that cannot sign must not be kept");
|
||||
assertTrue(second.isIssuedByUs(parse(second.issueClientCertificate("device").certificatePem())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredCaIsRegenerated() throws Exception {
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
java.security.KeyPair keyPair = java.security.KeyPairGenerator.getInstance("RSA").generateKeyPair();
|
||||
var dn = new org.bouncycastle.asn1.x500.X500Name("CN=" + FlociCertificateAuthority.COMMON_NAME);
|
||||
X509Certificate expired = gen.signCertificate(dn, keyPair.getPublic(), dn, keyPair.getPrivate(), List.of(),
|
||||
true, null, -1);
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.crt"), gen.toPem(expired));
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.key"), gen.toPem(keyPair.getPrivate()));
|
||||
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertNotEquals(expired, ca.certificate(), "an expired trust anchor is useless and must be replaced");
|
||||
ca.certificate().checkValidity();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingKeyFileRegeneratesThePair() throws Exception {
|
||||
FlociCertificateAuthority first = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
Files.delete(tempDir.resolve("floci-root-ca.key"));
|
||||
|
||||
FlociCertificateAuthority second = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertNotEquals(first.certificate(), second.certificate(), "a certificate without its key cannot sign");
|
||||
assertTrue(Files.exists(tempDir.resolve("floci-root-ca.key")));
|
||||
assertEquals(second.caPem(), Files.readString(tempDir.resolve("floci-root-ca.crt")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLeafInPlaceOfTheCaIsRegenerated() throws Exception {
|
||||
var leaf = new CertificateGenerator().generateCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.crt"), leaf.certificatePem());
|
||||
Files.writeString(tempDir.resolve("floci-root-ca.key"), leaf.privateKeyPem());
|
||||
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
assertTrue(ca.certificate().getBasicConstraints() >= 0, "must be a CA again");
|
||||
assertEquals(ca.certificate().getSubjectX500Principal(), ca.certificate().getIssuerX500Principal());
|
||||
}
|
||||
|
||||
@Test
|
||||
void signsAServerLeafThatVerifiesAgainstTheCa() throws Exception {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate(
|
||||
"localhost", List.of("localhost", "*.localhost.floci.io"), KeyAlgorithm.RSA_2048, null);
|
||||
X509Certificate cert = parse(leaf.certificatePem());
|
||||
|
||||
cert.verify(ca.certificate().getPublicKey());
|
||||
assertEquals(ca.certificate().getSubjectX500Principal(), cert.getIssuerX500Principal());
|
||||
assertEquals(-1, cert.getBasicConstraints());
|
||||
assertEquals(List.of("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage());
|
||||
assertEquals(List.of("localhost", "*.localhost.floci.io"),
|
||||
cert.getSubjectAlternativeNames().stream().map(san -> san.get(1)).toList());
|
||||
assertTrue(ca.isIssuedByUs(cert));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signsAClientLeafWithClientAuthOnly() throws Exception {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
|
||||
X509Certificate cert = parse(ca.issueClientCertificate("AWS IoT Certificate").certificatePem());
|
||||
|
||||
cert.verify(ca.certificate().getPublicKey());
|
||||
assertEquals("CN=AWS IoT Certificate", cert.getSubjectX500Principal().getName());
|
||||
assertEquals(List.of("1.3.6.1.5.5.7.3.2"), cert.getExtendedKeyUsage());
|
||||
assertTrue(ca.isIssuedByUs(cert));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSelfSignedLeafIsNotOurs() {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
var stranger = new CertificateGenerator().generateSelfSignedCertificate(
|
||||
"localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
|
||||
|
||||
assertFalse(ca.isIssuedByUs(parse(stranger.certificatePem())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLeafNamingOurCaButSignedByAnotherKeyIsNotOurs() {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tempDir);
|
||||
var impostor = new CertificateGenerator().generateCaCertificate(FlociCertificateAuthority.COMMON_NAME);
|
||||
var generator = new CertificateGenerator();
|
||||
var forged = generator.generateIssuedCertificate("localhost", List.of(), KeyAlgorithm.RSA_2048, null,
|
||||
new CertificateGenerator.Issuer(parse(impostor.certificatePem()),
|
||||
generator.parsePrivateKey(impostor.privateKeyPem())),
|
||||
CertificateGenerator.LeafUsage.SERVER);
|
||||
|
||||
assertFalse(ca.isIssuedByUs(parse(forged.certificatePem())), "same issuer name, wrong signature");
|
||||
}
|
||||
|
||||
private static X509Certificate parse(String pem) {
|
||||
return new CertificateGenerator().parseCertificate(pem);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.security.Security;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.*;
|
||||
@@ -67,7 +68,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
@@ -91,7 +92,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
@@ -111,7 +112,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
@@ -132,7 +133,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
@@ -154,7 +155,7 @@ class TlsCertificateHostnameTest {
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
X509Certificate initialCert = parseCertificate(certFile);
|
||||
List<String> initialSans = extractSansFromCertificate(initialCert);
|
||||
assertTrue(initialSans.contains("host1"), "Initial certificate should contain 'host1'");
|
||||
@@ -183,9 +184,9 @@ class TlsCertificateHostnameTest {
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path keyFile = tlsDir.resolve("floci-selfsigned.key");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path certFile = tlsDir.resolve("floci-server.crt");
|
||||
Path keyFile = tlsDir.resolve("floci-server.key");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
|
||||
// Generate certificate without metadata
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
@@ -224,7 +225,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
@@ -249,7 +250,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
@@ -291,7 +292,7 @@ class TlsCertificateHostnameTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: No self-signed certificate generated
|
||||
Path selfSignedCert = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path selfSignedCert = tempDir.resolve("tls/floci-server.crt");
|
||||
assertFalse(Files.exists(selfSignedCert),
|
||||
"Self-signed certificate should not be generated when user provides certificates");
|
||||
}
|
||||
@@ -310,7 +311,7 @@ class TlsCertificateHostnameTest {
|
||||
// Assert
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
if (Files.exists(tlsDir)) {
|
||||
assertFalse(Files.exists(tlsDir.resolve("floci-selfsigned.crt")),
|
||||
assertFalse(Files.exists(tlsDir.resolve("floci-server.crt")),
|
||||
"No certificate should be created when TLS is disabled");
|
||||
}
|
||||
}
|
||||
@@ -327,9 +328,9 @@ class TlsCertificateHostnameTest {
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String initialMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));
|
||||
String initialMetadata = Files.readString(tempDir.resolve("tls/floci-server.metadata.json"));
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
@@ -338,7 +339,7 @@ class TlsCertificateHostnameTest {
|
||||
|
||||
// Assert: Certificate reused (not regenerated)
|
||||
long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String newMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));
|
||||
String newMetadata = Files.readString(tempDir.resolve("tls/floci-server.metadata.json"));
|
||||
|
||||
assertEquals(initialModifiedTime, newModifiedTime,
|
||||
"Certificate should be reused when configuration unchanged");
|
||||
@@ -346,6 +347,135 @@ class TlsCertificateHostnameTest {
|
||||
"Metadata should be unchanged");
|
||||
}
|
||||
|
||||
// ==================== Local CA Tests ====================
|
||||
|
||||
@Test
|
||||
void serverCertificateIsIssuedByTheLocalCa() throws Exception {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
TlsConfigSource source = new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
X509Certificate ca = parseCertificate(tlsDir.resolve("floci-root-ca.crt"));
|
||||
X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));
|
||||
leaf.verify(ca.getPublicKey());
|
||||
assertEquals(ca.getSubjectX500Principal(), leaf.getIssuerX500Principal());
|
||||
assertEquals(-1, leaf.getBasicConstraints(), "server leaf must not be 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());
|
||||
|
||||
assertEquals(tlsDir.resolve("floci-server.crt").toAbsolutePath().toString(),
|
||||
source.getValue("quarkus.tls.key-store.pem.0.cert"));
|
||||
assertEquals(tlsDir.resolve("floci-server.key").toAbsolutePath().toString(),
|
||||
source.getValue("quarkus.tls.key-store.pem.0.key"));
|
||||
assertNull(source.getValue("quarkus.http.ssl.certificate.files"), "legacy key no longer published");
|
||||
assertNull(source.getValue("quarkus.http.ssl.certificate.key-files"), "legacy key no longer published");
|
||||
assertEquals(PosixFilePermissions.fromString("rw-------"),
|
||||
Files.getPosixFilePermissions(tlsDir.resolve("floci-server.key")));
|
||||
assertEquals(tlsDir, TlsConfigSource.resolvedTlsDir());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvedTlsDirIsClearedByABootThatDoesNotIssueALeaf() throws Exception {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
new TlsConfigSource();
|
||||
assertEquals(tempDir.resolve("tls"), TlsConfigSource.resolvedTlsDir());
|
||||
|
||||
System.setProperty("floci.tls.enabled", "false");
|
||||
new TlsConfigSource();
|
||||
assertNull(TlsConfigSource.resolvedTlsDir(), "TLS off: nothing was laid down");
|
||||
|
||||
Path userCert = tempDir.resolve("user.crt");
|
||||
Path userKey = tempDir.resolve("user.key");
|
||||
var user = new CertificateGenerator().generateCertificate("localhost", List.of("localhost"), KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(userCert, user.certificatePem());
|
||||
Files.writeString(userKey, user.privateKeyPem());
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.cert-path", userCert.toString());
|
||||
System.setProperty("floci.tls.key-path", userKey.toString());
|
||||
new TlsConfigSource();
|
||||
assertNull(TlsConfigSource.resolvedTlsDir(), "user certificate: nothing was laid down");
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacySelfSignedLeafIsReplacedByCaIssuedOne() throws Exception {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
// The exact SAN list TlsConfigSource would compute for this configuration, so only the
|
||||
// issuer check can trigger regeneration here.
|
||||
List<String> sans = 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");
|
||||
var legacy = gen.generateSelfSignedCertificate("localhost", sans, KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(tlsDir.resolve("floci-server.crt"), legacy.certificatePem());
|
||||
Files.writeString(tlsDir.resolve("floci-server.key"), legacy.privateKeyPem());
|
||||
Files.writeString(tlsDir.resolve("floci-server.metadata.json"),
|
||||
new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(
|
||||
CertificateMetadata.create(sans, "dev")));
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
X509Certificate ca = parseCertificate(tlsDir.resolve("floci-root-ca.crt"));
|
||||
X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));
|
||||
assertEquals(ca.getSubjectX500Principal(), leaf.getIssuerX500Principal());
|
||||
assertNotEquals(legacy.certificatePem(), Files.readString(tlsDir.resolve("floci-server.crt")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredServerLeafIsReissued() throws Exception {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
List<String> sans = 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");
|
||||
java.security.KeyPair keyPair = java.security.KeyPairGenerator.getInstance("RSA").generateKeyPair();
|
||||
// Issued by the current CA with a validity that ended a day ago: only the expiry check can trigger.
|
||||
X509Certificate expired = gen.signCertificate(new org.bouncycastle.asn1.x500.X500Name("CN=localhost"),
|
||||
keyPair.getPublic(), org.bouncycastle.asn1.x500.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()));
|
||||
Files.writeString(tlsDir.resolve("floci-server.metadata.json"),
|
||||
new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));
|
||||
assertTrue(ca.isIssuedByUs(expired), "the expired leaf is ours, so only validity can reject it");
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));
|
||||
leaf.checkValidity();
|
||||
assertNotEquals(expired.getSerialNumber(), leaf.getSerialNumber());
|
||||
assertTrue(ca.isIssuedByUs(leaf));
|
||||
}
|
||||
|
||||
@Test
|
||||
void leafSignedByAPreviousCaIsReplacedWhenTheCaChanges() throws Exception {
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
new TlsConfigSource();
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
String firstLeaf = Files.readString(tlsDir.resolve("floci-server.crt"));
|
||||
Files.delete(tlsDir.resolve("floci-root-ca.key"));
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
X509Certificate ca = parseCertificate(tlsDir.resolve("floci-root-ca.crt"));
|
||||
X509Certificate leaf = parseCertificate(tlsDir.resolve("floci-server.crt"));
|
||||
assertNotEquals(firstLeaf, Files.readString(tlsDir.resolve("floci-server.crt")));
|
||||
leaf.verify(ca.getPublicKey());
|
||||
}
|
||||
|
||||
// ==================== Helper Methods ====================
|
||||
|
||||
private X509Certificate parseCertificate(Path certFile) throws Exception {
|
||||
|
||||
+7
-7
@@ -59,7 +59,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
@@ -81,7 +81,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
@@ -103,7 +103,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
@@ -124,7 +124,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
@@ -147,7 +147,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
@@ -183,7 +183,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls/floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
@@ -205,7 +205,7 @@ class TlsConfigSourceCertificateGenerationTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
assertTrue(Files.exists(metadataFile), "Metadata file should exist");
|
||||
|
||||
String json = Files.readString(metadataFile);
|
||||
|
||||
+9
-9
@@ -57,8 +57,8 @@ class TlsConfigSourceCertificateReuseTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path certFile = tlsDir.resolve("floci-server.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
@@ -107,8 +107,8 @@ class TlsConfigSourceCertificateReuseTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path certFile = tlsDir.resolve("floci-server.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
@@ -150,8 +150,8 @@ class TlsConfigSourceCertificateReuseTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path certFile = tlsDir.resolve("floci-server.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
@@ -195,7 +195,7 @@ class TlsConfigSourceCertificateReuseTest {
|
||||
|
||||
// First boot: generate the certificate.
|
||||
new TlsConfigSource();
|
||||
Path certFile = tempDir.resolve("tls").resolve("floci-selfsigned.crt");
|
||||
Path certFile = tempDir.resolve("tls").resolve("floci-server.crt");
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String initialCert = Files.readString(certFile);
|
||||
@@ -236,8 +236,8 @@ class TlsConfigSourceCertificateReuseTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path certFile = tlsDir.resolve("floci-server.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
|
||||
+3
-3
@@ -167,7 +167,7 @@ class TlsConfigSourceMetadataComparisonTest {
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create malformed metadata file
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
Files.writeString(metadataFile, "{ invalid json }");
|
||||
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1");
|
||||
@@ -186,7 +186,7 @@ class TlsConfigSourceMetadataComparisonTest {
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with null hostnames field
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
String json = "{\"generatedAt\":\"" + Instant.now().toString() + "\",\"flociVersion\":\"dev\"}";
|
||||
Files.writeString(metadataFile, json);
|
||||
|
||||
@@ -223,7 +223,7 @@ class TlsConfigSourceMetadataComparisonTest {
|
||||
* Helper method to create a metadata file with specified hostnames.
|
||||
*/
|
||||
private void createMetadataFile(Path tlsDir, List<String> hostnames) throws IOException {
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tlsDir.resolve("floci-server.metadata.json");
|
||||
CertificateMetadata metadata = CertificateMetadata.create(hostnames, "dev");
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
+9
-9
@@ -53,7 +53,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
assertTrue(Files.exists(metadataFile),
|
||||
"Metadata file should be created after certificate generation");
|
||||
}
|
||||
@@ -67,7 +67,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getHostnames(), "Hostnames should not be null");
|
||||
@@ -99,7 +99,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertTrue(metadata.getHostnames().contains("floci"),
|
||||
@@ -118,7 +118,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertTrue(metadata.getHostnames().contains("myhost"),
|
||||
@@ -138,7 +138,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertTrue(metadata.getHostnames().contains("newhost"),
|
||||
@@ -156,7 +156,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getGeneratedAt(),
|
||||
@@ -174,7 +174,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getFlociVersion(),
|
||||
@@ -196,7 +196,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getFlociVersion(),
|
||||
@@ -212,7 +212,7 @@ class TlsConfigSourceMetadataPersistenceTest {
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
Path metadataFile = tempDir.resolve("tls/floci-server.metadata.json");
|
||||
String json = Files.readString(metadataFile);
|
||||
|
||||
assertFalse(json.isBlank(), "Metadata file should not be empty");
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
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 org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLHandshakeException;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.KeyStore;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* Boots the HTTP server on the TLS registry keys {@code TlsConfigSource} publishes, with a leaf
|
||||
* issued by the local CA, and proves a client that trusts only {@code GET /_floci/ca.pem} completes
|
||||
* a handshake. A file assertion cannot show that Quarkus read the registry entry or that the served
|
||||
* chain is the CA's; only a handshake can.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(TlsLocalCaIntegrationTest.LocalCaProfile.class)
|
||||
class TlsLocalCaIntegrationTest {
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
|
||||
int testSslPort;
|
||||
|
||||
@Test
|
||||
void handshakeSucceedsTrustingOnlyTheServedCa() throws Exception {
|
||||
String caPem = given().when().get("/_floci/ca.pem").then().statusCode(200).extract().asString();
|
||||
X509Certificate ca = parse(caPem);
|
||||
|
||||
HttpsURLConnection connection = open(trustOnly(ca));
|
||||
assertEquals(200, connection.getResponseCode());
|
||||
Certificate[] served = connection.getServerCertificates();
|
||||
X509Certificate leaf = (X509Certificate) served[0];
|
||||
assertEquals(ca.getSubjectX500Principal(), leaf.getIssuerX500Principal());
|
||||
assertEquals(-1, leaf.getBasicConstraints());
|
||||
leaf.verify(ca.getPublicKey());
|
||||
connection.disconnect();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handshakeFailsTrustingAnotherCa() throws Exception {
|
||||
X509Certificate stranger = FlociCertificateAuthority.loadOrCreate(
|
||||
Files.createTempDirectory("floci-stranger-ca")).certificate();
|
||||
|
||||
HttpsURLConnection connection = open(trustOnly(stranger));
|
||||
assertThrows(SSLHandshakeException.class, connection::getResponseCode);
|
||||
}
|
||||
|
||||
private HttpsURLConnection open(SSLContext sslContext) throws IOException {
|
||||
HttpsURLConnection connection = (HttpsURLConnection) URI.create(
|
||||
"https://localhost:" + testSslPort + "/_floci/health").toURL().openConnection();
|
||||
connection.setSSLSocketFactory(sslContext.getSocketFactory());
|
||||
return connection;
|
||||
}
|
||||
|
||||
private static SSLContext trustOnly(X509Certificate ca) throws Exception {
|
||||
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
trust.load(null, null);
|
||||
trust.setCertificateEntry("floci-ca", ca);
|
||||
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||
factory.init(trust);
|
||||
SSLContext context = SSLContext.getInstance("TLS");
|
||||
context.init(null, factory.getTrustManagers(), null);
|
||||
return context;
|
||||
}
|
||||
|
||||
private static X509Certificate parse(String pem) throws Exception {
|
||||
return (X509Certificate) CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays down what {@code TlsConfigSource} would: a CA under {persistent-path}/tls and a leaf
|
||||
* issued by it, published as the registry's default key store. The persistent path is the
|
||||
* same directory, so the CDI producer behind {@code /_floci/ca.pem} loads the same CA.
|
||||
*/
|
||||
public static final class LocalCaProfile implements QuarkusTestProfile {
|
||||
|
||||
private static final Path DATA_DIR = Path.of("target", "floci-tls-local-ca-test").toAbsolutePath();
|
||||
private static final Path TLS_DIR = DATA_DIR.resolve("tls");
|
||||
private static final Path CERT_FILE = TLS_DIR.resolve("floci-server.crt");
|
||||
private static final Path KEY_FILE = TLS_DIR.resolve("floci-server.key");
|
||||
|
||||
static {
|
||||
try {
|
||||
FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);
|
||||
var leaf = ca.issueServerCertificate("localhost", List.of("localhost", "127.0.0.1"),
|
||||
KeyAlgorithm.RSA_2048, null);
|
||||
Files.writeString(CERT_FILE, leaf.certificatePem());
|
||||
Files.writeString(KEY_FILE, leaf.privateKeyPem());
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Failed to prepare the local CA test files", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.storage.persistent-path", DATA_DIR.toString(),
|
||||
"quarkus.tls.key-store.pem.0.cert", CERT_FILE.toString(),
|
||||
"quarkus.tls.key-store.pem.0.key", KEY_FILE.toString(),
|
||||
"quarkus.http.insecure-requests", "enabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,31 @@ class TlsUserCertIntegrationTest {
|
||||
.body("edition", is("community"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void caPemReturnsTheUserCertificateFollowedByTheLocalCa() throws Exception {
|
||||
String pem = given()
|
||||
.when()
|
||||
.get("/_floci/ca.pem")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(org.hamcrest.Matchers.startsWith("text/plain"))
|
||||
.extract().asString();
|
||||
|
||||
String userPem = Files.readString(UserCertProfile.CERT_FILE);
|
||||
org.junit.jupiter.api.Assertions.assertTrue(pem.startsWith(userPem),
|
||||
"the user certificate, which signs the HTTPS endpoint, comes first");
|
||||
var bundle = java.security.cert.CertificateFactory.getInstance("X.509")
|
||||
.generateCertificates(new java.io.ByteArrayInputStream(pem.getBytes(java.nio.charset.StandardCharsets.US_ASCII)))
|
||||
.stream().map(java.security.cert.X509Certificate.class::cast).toList();
|
||||
org.junit.jupiter.api.Assertions.assertEquals(2, bundle.size(), "user certificate plus the local CA");
|
||||
java.security.cert.X509Certificate localCa = bundle.get(1);
|
||||
org.junit.jupiter.api.Assertions.assertTrue(localCa.getBasicConstraints() >= 0, "the local CA is a CA");
|
||||
org.junit.jupiter.api.Assertions.assertEquals("CN=Floci Local CA", localCa.getSubjectX500Principal().getName());
|
||||
org.junit.jupiter.api.Assertions.assertEquals(Files.readString(
|
||||
Path.of("/tmp/floci-tls-usercert-test-data/tls/floci-root-ca.crt")), pem.substring(userPem.length()).stripLeading(),
|
||||
"the local CA served is the one on disk");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ssmPutParameterOverHttps() {
|
||||
given()
|
||||
@@ -74,7 +99,7 @@ class TlsUserCertIntegrationTest {
|
||||
public static final class UserCertProfile implements QuarkusTestProfile {
|
||||
|
||||
private static final Path CERT_DIR = Path.of("/tmp/floci-tls-usercert-test");
|
||||
private static final Path CERT_FILE = CERT_DIR.resolve("user-test.crt");
|
||||
static final Path CERT_FILE = CERT_DIR.resolve("user-test.crt");
|
||||
private static final Path KEY_FILE = CERT_DIR.resolve("user-test.key");
|
||||
|
||||
static {
|
||||
|
||||
+18
@@ -105,6 +105,24 @@ class EmulatorInfoControllerIntegrationTest {
|
||||
given().when().get(path).then().statusCode(200).contentType("application/json");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/_floci/ca.pem", "/_localstack/ca.pem"})
|
||||
void caPem_returnsTheLocalCaAsPlainText(String path) throws Exception {
|
||||
String pem = given()
|
||||
.when().get(path)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(startsWith("text/plain"))
|
||||
.extract().body().asString();
|
||||
|
||||
var cert = (java.security.cert.X509Certificate) java.security.cert.CertificateFactory.getInstance("X.509")
|
||||
.generateCertificate(new java.io.ByteArrayInputStream(pem.getBytes(java.nio.charset.StandardCharsets.US_ASCII)));
|
||||
assertTrue(cert.getBasicConstraints() >= 0, "must be a CA certificate");
|
||||
assertEquals(cert.getSubjectX500Principal(), cert.getIssuerX500Principal());
|
||||
assertEquals(pem, given().when().get("/_floci/ca.pem").then().extract().body().asString(),
|
||||
"the same CA on every call");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/_floci/state/reset", "/_localstack/state/reset", "/_floci/state/nuke", "/_localstack/state/nuke"})
|
||||
void stateReset_returnsOkOnAllPaths(String path) {
|
||||
|
||||
+5
-5
@@ -20,7 +20,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
/**
|
||||
* Unit tests for {@link ContainerLauncher}'s Floci CA-trust injection helpers. These are pure
|
||||
* (no Docker / Quarkus): they cover where the CA cert is resolved from and which environment
|
||||
* variables get injected so a Lambda container trusts Floci's self-signed HTTPS endpoint.
|
||||
* variables get injected so a Lambda container trusts Floci's HTTPS endpoint through the local CA.
|
||||
*/
|
||||
class ContainerLauncherCaTrustTest {
|
||||
|
||||
@@ -41,9 +41,9 @@ class ContainerLauncherCaTrustTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveCaCertPath_selfSignedUnderPersistentPath() throws Exception {
|
||||
void resolveCaCertPath_localCaUnderPersistentPath() throws Exception {
|
||||
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
|
||||
Path cert = Files.writeString(tlsDir.resolve("floci-selfsigned.crt"), "PEM");
|
||||
Path cert = Files.writeString(tlsDir.resolve("floci-root-ca.crt"), "PEM");
|
||||
|
||||
Optional<Path> resolved =
|
||||
ContainerLauncher.resolveFlociCaCertPath(true, Optional.empty(), tempDir.toString());
|
||||
@@ -64,9 +64,9 @@ class ContainerLauncherCaTrustTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveCaCertPath_blankUserCertFallsBackToSelfSigned() throws Exception {
|
||||
void resolveCaCertPath_blankUserCertFallsBackToLocalCa() throws Exception {
|
||||
Path tlsDir = Files.createDirectories(tempDir.resolve("tls"));
|
||||
Path cert = Files.writeString(tlsDir.resolve("floci-selfsigned.crt"), "PEM");
|
||||
Path cert = Files.writeString(tlsDir.resolve("floci-root-ca.crt"), "PEM");
|
||||
|
||||
Optional<Path> resolved =
|
||||
ContainerLauncher.resolveFlociCaCertPath(true, Optional.of(" "), tempDir.toString());
|
||||
|
||||
Reference in new issue
Block a user