mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat: optional TLS/HTTPS support with self-signed certificate generation (#754)
* feat: optional TLS/HTTPS support with self-signed certificate generation - Add TlsConfigSource (MicroProfile ConfigSource SPI) that injects Quarkus TLS properties before the HTTP server starts - Auto-generate self-signed certificates with correct SANs including custom hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL - Persist certificate metadata for change detection across restarts - Fix CertificateGenerator to encode IP addresses as iPAddress SANs (RFC 5280) - Serve HTTP + HTTPS simultaneously (LocalStack parity) - Support user-provided certificates via FLOCI_TLS_CERT_PATH/KEY_PATH - Add TLS configuration documentation - Add Node.js SDK compatibility test for HTTPS connectivity - Add comprehensive unit and integration tests (79 test cases) Closes #711 * feat(tls): add TLS proxy server and WebSocket-over-TLS tests - Add TlsProxyServer: TCP proxy on port 4566 that detects TLS ClientHello and routes to HTTPS (4511) or HTTP (4510) backend accordingly - Add apigatewayv2-websocket-tls.test.ts: WSS compatibility tests covering connect/disconnect, route selection, broadcast, authorization, @connections API, binary frames, and payload size limits - Update CI workflow to enable FLOCI_TLS_ENABLED=true for compat tests - Update sdk-test-node Dockerfile with NODE_TLS_REJECT_UNAUTHORIZED=0 - Update tls.test.ts for HTTPS SDK client tests - Update README with WebSocket-over-TLS test documentation * fix(tls): address review comments — LocalStack parity and floci.io SANs - Add USE_SSL and CUSTOM_SSL_CERT_PATH mappings to localstack-parity.sh - Add localhost.floci.io and *.localhost.floci.io to default certificate SANs - Update affected tests and documentation --------- Co-authored-by: Dixit R Jain <dixitrjain@Mac-379.lan> Co-authored-by: Dixit R Jain <dixitrjain@Mac.lan>
This commit is contained in:
28 files changed
+3932
-4
No files matched your search
@@ -0,0 +1,386 @@
|
||||
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.bouncycastle.asn1.x509.GeneralName;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
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.MethodSource;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.Security;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Integration tests for TLS certificate hostname functionality.
|
||||
*
|
||||
* Tests that the TLS certificate generation correctly:
|
||||
* - Includes custom hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL in certificate SANs
|
||||
* - Regenerates certificates when hostname configuration changes
|
||||
* - Preserves default behavior for standard configurations
|
||||
* - Handles user-provided certificates correctly
|
||||
* - Manages certificate reuse and regeneration appropriately
|
||||
*/
|
||||
class TlsCertificateHostnameTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeAll
|
||||
static void setupBouncyCastle() {
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanupSystemProperties() {
|
||||
System.clearProperty("floci.hostname");
|
||||
System.clearProperty("floci.base-url");
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.tls.cert-path");
|
||||
System.clearProperty("floci.tls.key-path");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
}
|
||||
|
||||
// ==================== Custom Hostname Tests ====================
|
||||
|
||||
@Test
|
||||
void testFlociHostnameIncludedInCertificateSans() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
assertTrue(sans.contains("floci"),
|
||||
"Certificate SANs should contain 'floci' from FLOCI_HOSTNAME. Found: " + sans);
|
||||
assertTrue(sans.contains("localhost"),
|
||||
"Certificate SANs should include default 'localhost'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBaseUrlHostnameIncludedInCertificateSans() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://myhost:4566");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
assertTrue(sans.contains("myhost"),
|
||||
"Certificate SANs should contain 'myhost' from FLOCI_BASE_URL. Found: " + sans);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBaseUrlIpAddressIncludedInCertificateSans() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://192.168.1.100:4566");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
assertTrue(sans.contains("192.168.1.100"),
|
||||
"Certificate SANs should contain IP address from FLOCI_BASE_URL. Found: " + sans);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBothHostnamesIncludedInCertificateSans() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "newhost");
|
||||
System.setProperty("floci.base-url", "http://oldhost:4566");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
assertTrue(sans.contains("newhost"),
|
||||
"Certificate SANs should contain 'newhost' from FLOCI_HOSTNAME. Found: " + sans);
|
||||
assertTrue(sans.contains("oldhost"),
|
||||
"Certificate SANs should contain 'oldhost' from FLOCI_BASE_URL. Found: " + sans);
|
||||
}
|
||||
|
||||
// ==================== Certificate Regeneration Tests ====================
|
||||
|
||||
@Test
|
||||
void testConfigurationChangeTriggersRegeneration() throws Exception {
|
||||
// Arrange: Generate initial certificate
|
||||
System.setProperty("floci.hostname", "host1");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
X509Certificate initialCert = parseCertificate(certFile);
|
||||
List<String> initialSans = extractSansFromCertificate(initialCert);
|
||||
assertTrue(initialSans.contains("host1"), "Initial certificate should contain 'host1'");
|
||||
|
||||
// Act: Change hostname and restart
|
||||
System.setProperty("floci.hostname", "host2");
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Certificate regenerated with new hostname
|
||||
X509Certificate regeneratedCert = parseCertificate(certFile);
|
||||
List<String> regeneratedSans = extractSansFromCertificate(regeneratedCert);
|
||||
|
||||
assertTrue(regeneratedSans.contains("host2"),
|
||||
"Certificate should contain 'host2' after configuration change. Found: " + regeneratedSans);
|
||||
assertFalse(regeneratedSans.contains("host1"),
|
||||
"Certificate should not contain old hostname 'host1'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMissingMetadataTriggersRegeneration() throws Exception {
|
||||
// Arrange: Create certificate without metadata (simulating old version)
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
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");
|
||||
|
||||
// Generate certificate without metadata
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(
|
||||
"localhost",
|
||||
List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "localhost.floci.io", "*.localhost.floci.io"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(certFile, generated.certificatePem());
|
||||
Files.writeString(keyFile, generated.privateKeyPem());
|
||||
|
||||
assertFalse(Files.exists(metadataFile), "Metadata should not exist initially");
|
||||
|
||||
// Act: Trigger TlsConfigSource
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Metadata created and certificate regenerated with custom hostname
|
||||
assertTrue(Files.exists(metadataFile),
|
||||
"Metadata file should exist after regeneration");
|
||||
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
assertTrue(sans.contains("floci"),
|
||||
"Regenerated certificate should contain 'floci'. Found: " + sans);
|
||||
}
|
||||
|
||||
// ==================== Default Configuration Tests ====================
|
||||
|
||||
@Test
|
||||
void testDefaultConfigurationGeneratesDefaultSans() throws Exception {
|
||||
// Arrange: Default configuration (no custom hostnames)
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
Set<String> expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
|
||||
"localhost.floci.io", "*.localhost.floci.io");
|
||||
Set<String> actualSans = new HashSet<>(sans);
|
||||
|
||||
assertEquals(expectedSans, actualSans,
|
||||
"Default configuration should generate certificate with default SANs only");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("defaultConfigurations")
|
||||
void testDefaultConfigurationsProduceDefaultSans(Map<String, String> config) throws Exception {
|
||||
// Arrange
|
||||
config.forEach(System::setProperty);
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
X509Certificate cert = parseCertificate(certFile);
|
||||
List<String> sans = extractSansFromCertificate(cert);
|
||||
|
||||
Set<String> expectedSans = Set.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
|
||||
"localhost.floci.io", "*.localhost.floci.io");
|
||||
Set<String> actualSans = new HashSet<>(sans);
|
||||
|
||||
assertEquals(expectedSans, actualSans,
|
||||
"Default configuration should produce default SANs. Config: " + config);
|
||||
|
||||
// Cleanup
|
||||
config.keySet().forEach(System::clearProperty);
|
||||
}
|
||||
|
||||
// ==================== User-Provided Certificate Tests ====================
|
||||
|
||||
@Test
|
||||
void testUserProvidedCertificatesUsedWithoutModification() throws Exception {
|
||||
// Arrange: Create user-provided certificate
|
||||
Path userCertFile = tempDir.resolve("user-cert.crt");
|
||||
Path userKeyFile = tempDir.resolve("user-key.key");
|
||||
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
CertificateGenerator.GeneratedCertificate userCert = gen.generateCertificate(
|
||||
"user-domain.com",
|
||||
List.of("user-domain.com", "*.user-domain.com"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(userCertFile, userCert.certificatePem());
|
||||
Files.writeString(userKeyFile, userCert.privateKeyPem());
|
||||
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.cert-path", userCertFile.toString());
|
||||
System.setProperty("floci.tls.key-path", userKeyFile.toString());
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: No self-signed certificate generated
|
||||
Path selfSignedCert = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertFalse(Files.exists(selfSignedCert),
|
||||
"Self-signed certificate should not be generated when user provides certificates");
|
||||
}
|
||||
|
||||
// ==================== TLS Disabled Tests ====================
|
||||
|
||||
@Test
|
||||
void testTlsDisabledSkipsCertificateGeneration() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.tls.enabled", "false");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
if (Files.exists(tlsDir)) {
|
||||
assertFalse(Files.exists(tlsDir.resolve("floci-selfsigned.crt")),
|
||||
"No certificate should be created when TLS is disabled");
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Certificate Reuse Tests ====================
|
||||
|
||||
@Test
|
||||
void testUnchangedConfigurationReusesCertificate() throws Exception {
|
||||
// Arrange: Generate initial certificate
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
new TlsConfigSource();
|
||||
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String initialMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
// Act: Restart with same configuration
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Certificate reused (not regenerated)
|
||||
long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String newMetadata = Files.readString(tempDir.resolve("tls/floci-selfsigned.metadata.json"));
|
||||
|
||||
assertEquals(initialModifiedTime, newModifiedTime,
|
||||
"Certificate should be reused when configuration unchanged");
|
||||
assertEquals(initialMetadata, newMetadata,
|
||||
"Metadata should be unchanged");
|
||||
}
|
||||
|
||||
// ==================== Helper Methods ====================
|
||||
|
||||
private X509Certificate parseCertificate(Path certFile) throws Exception {
|
||||
String certPem = Files.readString(certFile);
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
return gen.parseCertificate(certPem);
|
||||
}
|
||||
|
||||
private List<String> extractSansFromCertificate(X509Certificate cert) throws Exception {
|
||||
List<String> sans = new ArrayList<>();
|
||||
|
||||
Collection<List<?>> subjectAltNames = cert.getSubjectAlternativeNames();
|
||||
if (subjectAltNames != null) {
|
||||
for (List<?> san : subjectAltNames) {
|
||||
Integer type = (Integer) san.get(0);
|
||||
String value = (String) san.get(1);
|
||||
|
||||
if (type == GeneralName.dNSName || type == GeneralName.iPAddress) {
|
||||
sans.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sans;
|
||||
}
|
||||
|
||||
static Stream<Map<String, String>> defaultConfigurations() {
|
||||
return Stream.of(
|
||||
Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true"),
|
||||
Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",
|
||||
"floci.base-url", "http://localhost:4566"),
|
||||
Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",
|
||||
"floci.base-url", "http://127.0.0.1:4566"),
|
||||
Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",
|
||||
"floci.hostname", "localhost"),
|
||||
Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",
|
||||
"floci.base-url", "https://localhost:4566"),
|
||||
Map.of("floci.tls.enabled", "true", "floci.tls.self-signed", "true",
|
||||
"floci.base-url", "http://0.0.0.0:4566")
|
||||
);
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Integration tests for TLS certificate generation with custom hostnames.
|
||||
*
|
||||
* Tests Task 3.5: Update certificate generation to include custom hostnames
|
||||
* - Verifies that extractCustomHostnames() is called
|
||||
* - Verifies that custom hostnames are combined with default SANs
|
||||
* - Verifies that the combined list is deduplicated
|
||||
* - Verifies that the combined SANs are passed to CertificateGenerator
|
||||
* - Verifies that logging shows custom hostnames when present
|
||||
*/
|
||||
class TlsConfigSourceCertificateGenerationTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
// Enable TLS and self-signed mode
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
System.clearProperty("floci.hostname");
|
||||
System.clearProperty("floci.base-url");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate includes custom hostname from FLOCI_HOSTNAME
|
||||
*/
|
||||
@Test
|
||||
void testCertificateIncludesFlociHostname() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
assertTrue(sans.contains("floci"),
|
||||
"Certificate SANs should include 'floci' from FLOCI_HOSTNAME");
|
||||
assertTrue(sans.contains("localhost"),
|
||||
"Certificate SANs should include default 'localhost'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate includes custom hostname from FLOCI_BASE_URL
|
||||
*/
|
||||
@Test
|
||||
void testCertificateIncludesBaseUrlHostname() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://myhost:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
assertTrue(sans.contains("myhost"),
|
||||
"Certificate SANs should include 'myhost' from FLOCI_BASE_URL");
|
||||
assertTrue(sans.contains("localhost"),
|
||||
"Certificate SANs should include default 'localhost'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate includes IP address from FLOCI_BASE_URL
|
||||
*/
|
||||
@Test
|
||||
void testCertificateIncludesIpAddress() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://192.168.1.100:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
assertTrue(sans.contains("192.168.1.100"),
|
||||
"Certificate SANs should include '192.168.1.100' from FLOCI_BASE_URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate includes both FLOCI_HOSTNAME and FLOCI_BASE_URL hostnames
|
||||
*/
|
||||
@Test
|
||||
void testCertificateIncludesBothHostnames() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "newhost");
|
||||
System.setProperty("floci.base-url", "http://oldhost:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
assertTrue(sans.contains("newhost"),
|
||||
"Certificate SANs should include 'newhost' from FLOCI_HOSTNAME");
|
||||
assertTrue(sans.contains("oldhost"),
|
||||
"Certificate SANs should include 'oldhost' from FLOCI_BASE_URL");
|
||||
assertTrue(sans.contains("localhost"),
|
||||
"Certificate SANs should include default 'localhost'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate with default configuration includes only default SANs
|
||||
*/
|
||||
@Test
|
||||
void testCertificateWithDefaultConfiguration() throws Exception {
|
||||
// Arrange - no custom hostnames
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
assertTrue(sans.contains("localhost"),
|
||||
"Certificate SANs should include default 'localhost'");
|
||||
assertTrue(sans.contains("127.0.0.1"),
|
||||
"Certificate SANs should include default '127.0.0.1'");
|
||||
assertTrue(sans.contains("0.0.0.0"),
|
||||
"Certificate SANs should include default '0.0.0.0'");
|
||||
|
||||
// Should not contain any custom hostnames
|
||||
assertEquals(6, sans.size(),
|
||||
"Certificate SANs should contain exactly 6 default entries (localhost, 127.0.0.1, 0.0.0.0, *.localhost, localhost.floci.io, *.localhost.floci.io)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that duplicate hostnames are deduplicated
|
||||
*/
|
||||
@Test
|
||||
void testDeduplicationInCertificate() throws Exception {
|
||||
// Arrange - same hostname in both sources
|
||||
System.setProperty("floci.hostname", "myhost");
|
||||
System.setProperty("floci.base-url", "http://myhost:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path certFile = tempDir.resolve("tls/floci-selfsigned.crt");
|
||||
assertTrue(Files.exists(certFile), "Certificate file should exist");
|
||||
|
||||
List<String> sans = extractSansFromCertificate(certFile);
|
||||
long myhostCount = sans.stream().filter(s -> s.equals("myhost")).count();
|
||||
assertEquals(1, myhostCount,
|
||||
"Certificate SANs should contain 'myhost' exactly once (deduplicated)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata file is created with correct hostnames
|
||||
*/
|
||||
@Test
|
||||
void testMetadataIncludesCustomHostnames() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
System.setProperty("floci.base-url", "https://myhost:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
assertTrue(Files.exists(metadataFile), "Metadata file should exist");
|
||||
|
||||
String json = Files.readString(metadataFile);
|
||||
assertTrue(json.contains("floci"),
|
||||
"Metadata should include 'floci' hostname");
|
||||
assertTrue(json.contains("myhost"),
|
||||
"Metadata should include 'myhost' hostname");
|
||||
assertTrue(json.contains("localhost"),
|
||||
"Metadata should include default 'localhost' hostname");
|
||||
}
|
||||
|
||||
// ==================== Helper Methods ====================
|
||||
|
||||
/**
|
||||
* Extracts Subject Alternative Names (SANs) from a certificate file.
|
||||
*
|
||||
* @param certFile Path to the certificate file
|
||||
* @return List of SANs (DNS names and IP addresses)
|
||||
*/
|
||||
private List<String> extractSansFromCertificate(Path certFile) throws Exception {
|
||||
String certPem = Files.readString(certFile);
|
||||
|
||||
// Parse certificate
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
X509Certificate cert = (X509Certificate) cf.generateCertificate(
|
||||
new ByteArrayInputStream(certPem.getBytes())
|
||||
);
|
||||
|
||||
// Extract SANs
|
||||
Collection<List<?>> sans = cert.getSubjectAlternativeNames();
|
||||
if (sans == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
return sans.stream()
|
||||
.filter(san -> san.size() >= 2)
|
||||
.map(san -> san.get(1).toString())
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
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.Security;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Integration test for Task 3.6: Certificate reuse logic with metadata checking
|
||||
*
|
||||
* This test verifies that TlsConfigSource correctly:
|
||||
* 1. Checks metadata before reusing existing certificates
|
||||
* 2. Regenerates certificates when configuration changes
|
||||
* 3. Regenerates certificates when metadata is missing
|
||||
* 4. Reuses certificates when configuration is unchanged
|
||||
*/
|
||||
class TlsConfigSourceCertificateReuseTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeAll
|
||||
static void setupBouncyCastle() {
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanupSystemProperties() {
|
||||
System.clearProperty("floci.hostname");
|
||||
System.clearProperty("floci.base-url");
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate is regenerated when hostname configuration changes
|
||||
*/
|
||||
@Test
|
||||
void testCertificateRegeneratedWhenHostnameChanges() throws Exception {
|
||||
// Arrange: Generate initial certificate with FLOCI_HOSTNAME=host1
|
||||
System.setProperty("floci.hostname", "host1");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act: Create TlsConfigSource - this generates the initial certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");
|
||||
|
||||
// Read initial metadata
|
||||
String initialMetadata = Files.readString(metadataFile);
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
|
||||
// Wait a bit to ensure timestamp difference
|
||||
Thread.sleep(100);
|
||||
|
||||
// Change hostname configuration
|
||||
System.setProperty("floci.hostname", "host2");
|
||||
|
||||
// Act: Create new TlsConfigSource - should regenerate certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Certificate and metadata should be regenerated
|
||||
assertTrue(Files.exists(certFile), "Certificate should still exist");
|
||||
assertTrue(Files.exists(metadataFile), "Metadata should still exist");
|
||||
|
||||
String newMetadata = Files.readString(metadataFile);
|
||||
long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
|
||||
assertNotEquals(initialMetadata, newMetadata,
|
||||
"Metadata should be updated with new hostname");
|
||||
assertTrue(newModifiedTime > initialModifiedTime,
|
||||
"Certificate should be regenerated (newer timestamp)");
|
||||
assertTrue(newMetadata.contains("host2"),
|
||||
"New metadata should contain 'host2'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate is regenerated when metadata is missing
|
||||
*/
|
||||
@Test
|
||||
void testCertificateRegeneratedWhenMetadataMissing() throws Exception {
|
||||
// Arrange: Generate initial certificate
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act: Create TlsConfigSource - this generates the initial certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");
|
||||
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
|
||||
// Delete metadata file to simulate old version
|
||||
Files.delete(metadataFile);
|
||||
assertFalse(Files.exists(metadataFile), "Metadata should be deleted");
|
||||
|
||||
// Wait a bit to ensure timestamp difference
|
||||
Thread.sleep(100);
|
||||
|
||||
// Act: Create new TlsConfigSource - should regenerate certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Certificate and metadata should be regenerated
|
||||
assertTrue(Files.exists(certFile), "Certificate should still exist");
|
||||
assertTrue(Files.exists(metadataFile), "Metadata should be regenerated");
|
||||
|
||||
long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
assertTrue(newModifiedTime > initialModifiedTime,
|
||||
"Certificate should be regenerated when metadata is missing");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate is reused when configuration is unchanged
|
||||
*/
|
||||
@Test
|
||||
void testCertificateReusedWhenConfigurationUnchanged() throws Exception {
|
||||
// Arrange: Generate initial certificate
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act: Create TlsConfigSource - this generates the initial certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");
|
||||
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String initialMetadata = Files.readString(metadataFile);
|
||||
|
||||
// Wait a bit to ensure timestamp difference would be visible if regenerated
|
||||
Thread.sleep(100);
|
||||
|
||||
// Act: Create new TlsConfigSource with same configuration - should reuse certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Certificate and metadata should NOT be regenerated
|
||||
assertTrue(Files.exists(certFile), "Certificate should still exist");
|
||||
assertTrue(Files.exists(metadataFile), "Metadata should still exist");
|
||||
|
||||
long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
String newMetadata = Files.readString(metadataFile);
|
||||
|
||||
assertEquals(initialModifiedTime, newModifiedTime,
|
||||
"Certificate should be reused (same timestamp)");
|
||||
assertEquals(initialMetadata, newMetadata,
|
||||
"Metadata should be unchanged");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that certificate is regenerated when base URL hostname changes
|
||||
*/
|
||||
@Test
|
||||
void testCertificateRegeneratedWhenBaseUrlChanges() throws Exception {
|
||||
// Arrange: Generate initial certificate with FLOCI_BASE_URL=https://host1:4566
|
||||
System.setProperty("floci.base-url", "https://host1:4566");
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
|
||||
// Act: Create TlsConfigSource - this generates the initial certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Path certFile = tlsDir.resolve("floci-selfsigned.crt");
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
|
||||
// Verify initial certificate and metadata exist
|
||||
assertTrue(Files.exists(certFile), "Initial certificate should be generated");
|
||||
assertTrue(Files.exists(metadataFile), "Initial metadata should be generated");
|
||||
|
||||
String initialMetadata = Files.readString(metadataFile);
|
||||
long initialModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
|
||||
// Wait a bit to ensure timestamp difference
|
||||
Thread.sleep(100);
|
||||
|
||||
// Change base URL hostname
|
||||
System.setProperty("floci.base-url", "https://host2:4566");
|
||||
|
||||
// Act: Create new TlsConfigSource - should regenerate certificate
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert: Certificate and metadata should be regenerated
|
||||
assertTrue(Files.exists(certFile), "Certificate should still exist");
|
||||
assertTrue(Files.exists(metadataFile), "Metadata should still exist");
|
||||
|
||||
String newMetadata = Files.readString(metadataFile);
|
||||
long newModifiedTime = Files.getLastModifiedTime(certFile).toMillis();
|
||||
|
||||
assertNotEquals(initialMetadata, newMetadata,
|
||||
"Metadata should be updated with new hostname");
|
||||
assertTrue(newModifiedTime > initialModifiedTime,
|
||||
"Certificate should be regenerated (newer timestamp)");
|
||||
assertTrue(newMetadata.contains("host2"),
|
||||
"New metadata should contain 'host2'");
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Unit tests for hostname extraction logic in TlsConfigSource.
|
||||
*
|
||||
* Tests the extractCustomHostnames() method to verify:
|
||||
* - Extraction from FLOCI_HOSTNAME
|
||||
* - Extraction from FLOCI_BASE_URL (DNS names and IP addresses)
|
||||
* - Filtering of default values (localhost, 127.0.0.1, 0.0.0.0)
|
||||
* - Deduplication of hostnames
|
||||
* - Edge case handling (malformed URLs, missing host, IPv6 addresses)
|
||||
*/
|
||||
class TlsConfigSourceHostnameExtractionTest {
|
||||
|
||||
@AfterEach
|
||||
void cleanupSystemProperties() {
|
||||
System.clearProperty("floci.hostname");
|
||||
System.clearProperty("floci.base-url");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test extraction from FLOCI_HOSTNAME
|
||||
*/
|
||||
@Test
|
||||
void testExtractFromFlociHostname() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.contains("floci"),
|
||||
"Should extract 'floci' from FLOCI_HOSTNAME");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test extraction from FLOCI_BASE_URL with DNS name
|
||||
*/
|
||||
@Test
|
||||
void testExtractFromBaseUrlDnsName() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://myhost:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.contains("myhost"),
|
||||
"Should extract 'myhost' from FLOCI_BASE_URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test extraction from FLOCI_BASE_URL with IP address
|
||||
*/
|
||||
@Test
|
||||
void testExtractFromBaseUrlIpAddress() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://192.168.1.100:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.contains("192.168.1.100"),
|
||||
"Should extract '192.168.1.100' from FLOCI_BASE_URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test extraction from both FLOCI_HOSTNAME and FLOCI_BASE_URL
|
||||
*/
|
||||
@Test
|
||||
void testExtractFromBothSources() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "newhost");
|
||||
System.setProperty("floci.base-url", "http://oldhost:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.contains("newhost"),
|
||||
"Should extract 'newhost' from FLOCI_HOSTNAME");
|
||||
assertTrue(hostnames.contains("oldhost"),
|
||||
"Should extract 'oldhost' from FLOCI_BASE_URL");
|
||||
assertEquals(2, hostnames.size(),
|
||||
"Should contain exactly 2 hostnames");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test filtering of default hostname "localhost"
|
||||
*/
|
||||
@Test
|
||||
void testFilterDefaultLocalhostFromHostname() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "localhost");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should filter out 'localhost' as it's a default value");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test filtering of default IP "127.0.0.1"
|
||||
*/
|
||||
@Test
|
||||
void testFilterDefaultLoopbackIp() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "http://127.0.0.1:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should filter out '127.0.0.1' as it's a default value");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test filtering of default IP "0.0.0.0"
|
||||
*/
|
||||
@Test
|
||||
void testFilterDefaultAllInterfacesIp() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "http://0.0.0.0:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should filter out '0.0.0.0' as it's a default value");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test deduplication when same hostname appears in both sources
|
||||
*/
|
||||
@Test
|
||||
void testDeduplication() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "myhost");
|
||||
System.setProperty("floci.base-url", "http://myhost:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertEquals(1, hostnames.size(),
|
||||
"Should deduplicate 'myhost' appearing in both sources");
|
||||
assertTrue(hostnames.contains("myhost"),
|
||||
"Should contain 'myhost'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test handling of malformed URL
|
||||
*/
|
||||
@Test
|
||||
void testMalformedUrl() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "not-a-valid-url");
|
||||
|
||||
// Act & Assert - should not throw exception
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Should return empty list (malformed URL is logged but doesn't fail)
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should return empty list for malformed URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test handling of URL without host
|
||||
*/
|
||||
@Test
|
||||
void testUrlWithoutHost() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "file:///path/to/file");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should return empty list for URL without host");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test empty configuration (no custom hostnames)
|
||||
*/
|
||||
@Test
|
||||
void testEmptyConfiguration() throws Exception {
|
||||
// Arrange - no properties set
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should return empty list when no custom hostnames configured");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test blank FLOCI_HOSTNAME is ignored
|
||||
*/
|
||||
@Test
|
||||
void testBlankHostname() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", " ");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
assertTrue(hostnames.isEmpty(),
|
||||
"Should ignore blank FLOCI_HOSTNAME");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test IPv6 address extraction
|
||||
* Note: URI.getHost() returns IPv6 addresses with brackets
|
||||
*/
|
||||
@Test
|
||||
void testIpv6Address() throws Exception {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "http://[::1]:4566");
|
||||
|
||||
// Act
|
||||
List<String> hostnames = invokeExtractCustomHostnames();
|
||||
|
||||
// Assert
|
||||
// IPv6 loopback should be extracted (URI.getHost() returns it with brackets)
|
||||
assertTrue(hostnames.contains("[::1]"),
|
||||
"Should extract IPv6 address '[::1]' from FLOCI_BASE_URL");
|
||||
}
|
||||
|
||||
// ==================== Helper Methods ====================
|
||||
|
||||
/**
|
||||
* Invokes the private extractCustomHostnames() method using reflection.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private List<String> invokeExtractCustomHostnames() throws Exception {
|
||||
TlsConfigSource configSource = new TlsConfigSource();
|
||||
Method method = TlsConfigSource.class.getDeclaredMethod("extractCustomHostnames");
|
||||
method.setAccessible(true);
|
||||
return (List<String>) method.invoke(configSource);
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Unit tests for metadata loading and comparison in TlsConfigSource.
|
||||
*
|
||||
* Tests the hostnameConfigChanged() method to verify:
|
||||
* - Returns true when metadata file doesn't exist
|
||||
* - Returns true when hostnames have changed
|
||||
* - Returns false when hostnames are the same (order-independent)
|
||||
* - Handles read/parse failures gracefully (returns true)
|
||||
* - Proper logging for different scenarios
|
||||
*/
|
||||
class TlsConfigSourceMetadataComparisonTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Set up minimal TLS configuration for testing
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
// Clean up system properties
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
System.clearProperty("floci.hostname");
|
||||
System.clearProperty("floci.base-url");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMetadataFileMissing_ReturnsTrue() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertTrue(changed, "Should return true when metadata file doesn't exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostnamesChanged_ReturnsTrue() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with old hostnames
|
||||
List<String> oldHostnames = List.of("localhost", "127.0.0.1", "oldhost");
|
||||
createMetadataFile(tlsDir, oldHostnames);
|
||||
|
||||
// Current hostnames are different
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1", "newhost");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertTrue(changed, "Should return true when hostnames have changed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostnamesUnchanged_ReturnsFalse() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with hostnames
|
||||
List<String> hostnames = List.of("localhost", "127.0.0.1", "myhost");
|
||||
createMetadataFile(tlsDir, hostnames);
|
||||
|
||||
// Current hostnames are the same
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1", "myhost");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertFalse(changed, "Should return false when hostnames are unchanged");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostnamesUnchanged_DifferentOrder_ReturnsFalse() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with hostnames in one order
|
||||
List<String> hostnames = List.of("localhost", "myhost", "127.0.0.1");
|
||||
createMetadataFile(tlsDir, hostnames);
|
||||
|
||||
// Current hostnames in different order
|
||||
List<String> currentHostnames = List.of("127.0.0.1", "localhost", "myhost");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertFalse(changed, "Should return false when hostnames are the same but in different order");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostnameAdded_ReturnsTrue() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with fewer hostnames
|
||||
List<String> oldHostnames = List.of("localhost", "127.0.0.1");
|
||||
createMetadataFile(tlsDir, oldHostnames);
|
||||
|
||||
// Current hostnames include an additional hostname
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1", "newhost");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertTrue(changed, "Should return true when a hostname is added");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHostnameRemoved_ReturnsTrue() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with more hostnames
|
||||
List<String> oldHostnames = List.of("localhost", "127.0.0.1", "oldhost");
|
||||
createMetadataFile(tlsDir, oldHostnames);
|
||||
|
||||
// Current hostnames have one removed
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertTrue(changed, "Should return true when a hostname is removed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMalformedMetadataFile_ReturnsTrue() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create malformed metadata file
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
Files.writeString(metadataFile, "{ invalid json }");
|
||||
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertTrue(changed, "Should return true when metadata file is malformed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMetadataWithNullHostnames_ReturnsTrue() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with null hostnames field
|
||||
Path metadataFile = tlsDir.resolve("floci-selfsigned.metadata.json");
|
||||
String json = "{\"generatedAt\":\"" + Instant.now().toString() + "\",\"flociVersion\":\"dev\"}";
|
||||
Files.writeString(metadataFile, json);
|
||||
|
||||
List<String> currentHostnames = List.of("localhost", "127.0.0.1");
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertTrue(changed, "Should return true when metadata has no hostnames field");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEmptyHostnamesList_Unchanged_ReturnsFalse() throws Exception {
|
||||
// Arrange
|
||||
Path tlsDir = tempDir.resolve("tls");
|
||||
Files.createDirectories(tlsDir);
|
||||
|
||||
// Create metadata with empty hostnames list
|
||||
List<String> emptyHostnames = List.of();
|
||||
createMetadataFile(tlsDir, emptyHostnames);
|
||||
|
||||
// Current hostnames are also empty
|
||||
List<String> currentHostnames = List.of();
|
||||
|
||||
// Act
|
||||
boolean changed = invokeHostnameConfigChanged(tlsDir, currentHostnames);
|
||||
|
||||
// Assert
|
||||
assertFalse(changed, "Should return false when both hostname lists are empty");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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");
|
||||
CertificateMetadata metadata = CertificateMetadata.create(hostnames, "dev");
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);
|
||||
Files.writeString(metadataFile, json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to invoke the private hostnameConfigChanged() method via reflection.
|
||||
* We need to disable TLS temporarily to avoid certificate generation in the constructor.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private boolean invokeHostnameConfigChanged(Path tlsDir, List<String> currentHostnames) throws Exception {
|
||||
// Temporarily disable TLS to avoid certificate generation in constructor
|
||||
String originalTlsEnabled = System.getProperty("floci.tls.enabled");
|
||||
System.setProperty("floci.tls.enabled", "false");
|
||||
|
||||
try {
|
||||
TlsConfigSource configSource = new TlsConfigSource();
|
||||
Method method = TlsConfigSource.class.getDeclaredMethod("hostnameConfigChanged", Path.class, List.class);
|
||||
method.setAccessible(true);
|
||||
return (boolean) method.invoke(configSource, tlsDir, currentHostnames);
|
||||
} finally {
|
||||
// Restore original TLS setting
|
||||
if (originalTlsEnabled != null) {
|
||||
System.setProperty("floci.tls.enabled", originalTlsEnabled);
|
||||
} else {
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Unit tests for metadata persistence in TlsConfigSource.
|
||||
*
|
||||
* Tests that metadata is correctly persisted after certificate generation:
|
||||
* - Metadata file is created
|
||||
* - Metadata contains correct hostnames
|
||||
* - Metadata contains timestamp and version
|
||||
* - Write failures are handled gracefully
|
||||
*/
|
||||
class TlsConfigSourceMetadataPersistenceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
// Set TLS enabled and self-signed mode
|
||||
System.setProperty("floci.tls.enabled", "true");
|
||||
System.setProperty("floci.tls.self-signed", "true");
|
||||
System.setProperty("floci.storage.persistent-path", tempDir.toString());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
System.clearProperty("floci.tls.enabled");
|
||||
System.clearProperty("floci.tls.self-signed");
|
||||
System.clearProperty("floci.storage.persistent-path");
|
||||
System.clearProperty("floci.hostname");
|
||||
System.clearProperty("floci.base-url");
|
||||
System.clearProperty("FLOCI_VERSION");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata file is created after certificate generation
|
||||
*/
|
||||
@Test
|
||||
void testMetadataFileCreated() {
|
||||
// Act - trigger certificate generation by creating TlsConfigSource
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
assertTrue(Files.exists(metadataFile),
|
||||
"Metadata file should be created after certificate generation");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains default hostnames when no custom hostnames configured
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsDefaultHostnames() throws IOException {
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getHostnames(), "Hostnames should not be null");
|
||||
assertTrue(metadata.getHostnames().contains("localhost"),
|
||||
"Metadata should contain 'localhost'");
|
||||
assertTrue(metadata.getHostnames().contains("127.0.0.1"),
|
||||
"Metadata should contain '127.0.0.1'");
|
||||
assertTrue(metadata.getHostnames().contains("0.0.0.0"),
|
||||
"Metadata should contain '0.0.0.0'");
|
||||
assertTrue(metadata.getHostnames().contains("*.localhost"),
|
||||
"Metadata should contain '*.localhost'");
|
||||
assertTrue(metadata.getHostnames().contains("localhost.floci.io"),
|
||||
"Metadata should contain 'localhost.floci.io'");
|
||||
assertTrue(metadata.getHostnames().contains("*.localhost.floci.io"),
|
||||
"Metadata should contain '*.localhost.floci.io'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains custom hostname from FLOCI_HOSTNAME
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsCustomHostname() throws IOException {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "floci");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertTrue(metadata.getHostnames().contains("floci"),
|
||||
"Metadata should contain custom hostname 'floci'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains custom hostname from FLOCI_BASE_URL
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsBaseUrlHostname() throws IOException {
|
||||
// Arrange
|
||||
System.setProperty("floci.base-url", "https://myhost:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertTrue(metadata.getHostnames().contains("myhost"),
|
||||
"Metadata should contain hostname 'myhost' from base URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains both custom hostnames when both are configured
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsBothCustomHostnames() throws IOException {
|
||||
// Arrange
|
||||
System.setProperty("floci.hostname", "newhost");
|
||||
System.setProperty("floci.base-url", "http://oldhost:4566");
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertTrue(metadata.getHostnames().contains("newhost"),
|
||||
"Metadata should contain 'newhost' from FLOCI_HOSTNAME");
|
||||
assertTrue(metadata.getHostnames().contains("oldhost"),
|
||||
"Metadata should contain 'oldhost' from FLOCI_BASE_URL");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains timestamp
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsTimestamp() throws IOException {
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getGeneratedAt(),
|
||||
"Metadata should contain generatedAt timestamp");
|
||||
assertFalse(metadata.getGeneratedAt().isBlank(),
|
||||
"Timestamp should not be blank");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains version
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsVersion() throws IOException {
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getFlociVersion(),
|
||||
"Metadata should contain flociVersion");
|
||||
assertEquals("dev", metadata.getFlociVersion(),
|
||||
"Version should default to 'dev' when FLOCI_VERSION not set");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata contains custom version from FLOCI_VERSION environment variable
|
||||
*/
|
||||
@Test
|
||||
void testMetadataContainsCustomVersion() throws IOException {
|
||||
// Arrange
|
||||
// Note: We can't set environment variables in Java, so we'll test the default behavior
|
||||
// The actual environment variable handling is tested in integration tests
|
||||
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
CertificateMetadata metadata = readMetadata(metadataFile);
|
||||
|
||||
assertNotNull(metadata.getFlociVersion(),
|
||||
"Metadata should contain flociVersion");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that metadata file is valid JSON
|
||||
*/
|
||||
@Test
|
||||
void testMetadataIsValidJson() throws IOException {
|
||||
// Act
|
||||
new TlsConfigSource();
|
||||
|
||||
// Assert
|
||||
Path metadataFile = tempDir.resolve("tls/floci-selfsigned.metadata.json");
|
||||
String json = Files.readString(metadataFile);
|
||||
|
||||
assertFalse(json.isBlank(), "Metadata file should not be empty");
|
||||
assertTrue(json.contains("hostnames"), "JSON should contain 'hostnames' field");
|
||||
assertTrue(json.contains("generatedAt"), "JSON should contain 'generatedAt' field");
|
||||
assertTrue(json.contains("flociVersion"), "JSON should contain 'flociVersion' field");
|
||||
}
|
||||
|
||||
// ==================== Helper Methods ====================
|
||||
|
||||
/**
|
||||
* Reads and parses metadata from the specified file.
|
||||
*/
|
||||
private CertificateMetadata readMetadata(Path metadataFile) throws IOException {
|
||||
String json = Files.readString(metadataFile);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
return objectMapper.readValue(json, CertificateMetadata.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
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.RestAssured;
|
||||
import io.restassured.config.RestAssuredConfig;
|
||||
import io.restassured.config.SSLConfig;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.Security;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
* Integration test verifying TLS/HTTPS support when enabled via configuration.
|
||||
*
|
||||
* <p>Uses a {@link QuarkusTestProfile} to enable self-signed TLS so the Quarkus
|
||||
* HTTP server serves HTTPS alongside HTTP (dual-mode, LocalStack parity).
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(TlsIntegrationTest.TlsEnabledProfile.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class TlsIntegrationTest {
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
|
||||
int testSslPort;
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")
|
||||
int testHttpPort;
|
||||
|
||||
@BeforeAll
|
||||
void setupRestAssured() {
|
||||
// Trust self-signed certificates for all requests in this test class
|
||||
RestAssured.config = RestAssuredConfig.config()
|
||||
.sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation());
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
// ==================== HTTPS Connectivity ====================
|
||||
|
||||
@Test
|
||||
void healthEndpointOverHttps() {
|
||||
given()
|
||||
.baseUri("https://localhost:" + testSslPort)
|
||||
.when()
|
||||
.get("/_floci/health")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("edition", is("community"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthEndpointStillWorksOverHttp() {
|
||||
given()
|
||||
.baseUri("http://localhost:" + testHttpPort)
|
||||
.when()
|
||||
.get("/_floci/health")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("edition", is("community"));
|
||||
}
|
||||
|
||||
// ==================== SQS via HTTPS ====================
|
||||
|
||||
@Test
|
||||
void sqsCreateQueueOverHttps() {
|
||||
given()
|
||||
.baseUri("https://localhost:" + testSslPort)
|
||||
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("{\"QueueName\": \"tls-test-queue\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("QueueUrl", startsWith("https://"));
|
||||
}
|
||||
|
||||
// ==================== STS via HTTPS ====================
|
||||
|
||||
@Test
|
||||
void stsGetCallerIdentityOverHttps() {
|
||||
given()
|
||||
.baseUri("https://localhost:" + testSslPort)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("GetCallerIdentityResult"));
|
||||
}
|
||||
|
||||
// ==================== Test Profile ====================
|
||||
|
||||
public static final class TlsEnabledProfile implements QuarkusTestProfile {
|
||||
|
||||
private static final Path CERT_DIR = Path.of("/tmp/floci-tls-integration-test");
|
||||
private static final Path CERT_FILE = CERT_DIR.resolve("test.crt");
|
||||
private static final Path KEY_FILE = CERT_DIR.resolve("test.key");
|
||||
|
||||
static {
|
||||
generateCertIfNeeded();
|
||||
}
|
||||
|
||||
private static void generateCertIfNeeded() {
|
||||
if (Files.exists(CERT_FILE) && Files.exists(KEY_FILE)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(CERT_DIR);
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(
|
||||
"localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(CERT_FILE, cert.certificatePem());
|
||||
Files.writeString(KEY_FILE, cert.privateKeyPem());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to generate test cert", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.tls.enabled", "true",
|
||||
"floci.tls.self-signed", "false",
|
||||
"floci.tls.cert-path", CERT_FILE.toAbsolutePath().toString(),
|
||||
"floci.tls.key-path", KEY_FILE.toAbsolutePath().toString(),
|
||||
"floci.storage.persistent-path", "/tmp/floci-tls-integration-test-data",
|
||||
"quarkus.http.ssl.certificate.files", CERT_FILE.toAbsolutePath().toString(),
|
||||
"quarkus.http.ssl.certificate.key-files", KEY_FILE.toAbsolutePath().toString(),
|
||||
"quarkus.http.insecure-requests", "enabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
|
||||
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.RestAssured;
|
||||
import io.restassured.config.RestAssuredConfig;
|
||||
import io.restassured.config.SSLConfig;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.Security;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
|
||||
/**
|
||||
* Integration test verifying TLS works with user-provided certificate and key files.
|
||||
*
|
||||
* <p>Generates a cert/key pair in the static initializer (before Quarkus starts),
|
||||
* then configures the profile to use those paths for both floci config and
|
||||
* Quarkus SSL properties.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(TlsUserCertIntegrationTest.UserCertProfile.class)
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
class TlsUserCertIntegrationTest {
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
|
||||
int testSslPort;
|
||||
|
||||
@BeforeAll
|
||||
void setupRestAssured() {
|
||||
RestAssured.config = RestAssuredConfig.config()
|
||||
.sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation());
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void healthEndpointOverHttpsWithUserCert() {
|
||||
given()
|
||||
.baseUri("https://localhost:" + testSslPort)
|
||||
.when()
|
||||
.get("/_floci/health")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("edition", is("community"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ssmPutParameterOverHttps() {
|
||||
given()
|
||||
.baseUri("https://localhost:" + testSslPort)
|
||||
.header("X-Amz-Target", "AmazonSSM.PutParameter")
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.body("{\"Name\": \"/tls-user-cert-test\", \"Value\": \"test-value\", \"Type\": \"String\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
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");
|
||||
private static final Path KEY_FILE = CERT_DIR.resolve("user-test.key");
|
||||
|
||||
static {
|
||||
generateCertIfNeeded();
|
||||
}
|
||||
|
||||
private static void generateCertIfNeeded() {
|
||||
if (Files.exists(CERT_FILE) && Files.exists(KEY_FILE)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(CERT_DIR);
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
CertificateGenerator gen = new CertificateGenerator();
|
||||
CertificateGenerator.GeneratedCertificate cert = gen.generateCertificate(
|
||||
"localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048);
|
||||
Files.writeString(CERT_FILE, cert.certificatePem());
|
||||
Files.writeString(KEY_FILE, cert.privateKeyPem());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to generate test cert", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.tls.enabled", "true",
|
||||
"floci.tls.self-signed", "false",
|
||||
"floci.tls.cert-path", CERT_FILE.toAbsolutePath().toString(),
|
||||
"floci.tls.key-path", KEY_FILE.toAbsolutePath().toString(),
|
||||
"floci.storage.persistent-path", "/tmp/floci-tls-usercert-test-data",
|
||||
"quarkus.http.ssl.certificate.files", CERT_FILE.toAbsolutePath().toString(),
|
||||
"quarkus.http.ssl.certificate.key-files", KEY_FILE.toAbsolutePath().toString(),
|
||||
"quarkus.http.insecure-requests", "enabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ class EmulatorLifecycleTest {
|
||||
@Mock private PipesService pipesService;
|
||||
@Mock private Ec2MetadataServer ec2MetadataServer;
|
||||
@Mock private InitLifecycleState initLifecycleState;
|
||||
@Mock private EmulatorConfig.TlsConfig tlsConfig;
|
||||
|
||||
private EmulatorLifecycle emulatorLifecycle;
|
||||
|
||||
@@ -61,6 +62,8 @@ class EmulatorLifecycleTest {
|
||||
Mockito.lenient().when(config.services()).thenReturn(servicesConfig);
|
||||
Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig);
|
||||
Mockito.lenient().when(ec2ServiceConfig.enabled()).thenReturn(false);
|
||||
Mockito.lenient().when(config.tls()).thenReturn(tlsConfig);
|
||||
Mockito.lenient().when(tlsConfig.enabled()).thenReturn(false);
|
||||
|
||||
emulatorLifecycle = new EmulatorLifecycle(
|
||||
storageFactory, serviceRegistry, config,
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
|
||||
import org.bouncycastle.asn1.x509.GeneralName;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.security.Security;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests that CertificateGenerator encodes SANs with the correct type:
|
||||
* - DNS names use GeneralName.dNSName (type 2)
|
||||
* - IP addresses use GeneralName.iPAddress (type 7)
|
||||
*
|
||||
* This is critical for TLS validation — clients only match IP addresses
|
||||
* against iPAddress SANs, not dNSName SANs (RFC 5280 §4.2.1.6).
|
||||
*/
|
||||
class CertificateGeneratorSanTypeTest {
|
||||
|
||||
private static CertificateGenerator generator;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
}
|
||||
generator = new CertificateGenerator();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ipv4AddressEncodedAsIpAddressSanType() throws Exception {
|
||||
var cert = generator.generateCertificate(
|
||||
"localhost",
|
||||
List.of("localhost", "192.168.1.100"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
|
||||
X509Certificate x509 = generator.parseCertificate(cert.certificatePem());
|
||||
Collection<List<?>> sans = x509.getSubjectAlternativeNames();
|
||||
|
||||
// Find the 192.168.1.100 SAN and verify its type is iPAddress (7)
|
||||
boolean foundIpSan = sans.stream()
|
||||
.anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress
|
||||
&& san.get(1).toString().equals("192.168.1.100"));
|
||||
|
||||
assertTrue(foundIpSan,
|
||||
"192.168.1.100 should be encoded as iPAddress SAN (type 7). Found SANs: " + sans);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ipv6LoopbackEncodedAsIpAddressSanType() throws Exception {
|
||||
var cert = generator.generateCertificate(
|
||||
"localhost",
|
||||
List.of("localhost", "0.0.0.0", "::1"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
|
||||
X509Certificate x509 = generator.parseCertificate(cert.certificatePem());
|
||||
Collection<List<?>> sans = x509.getSubjectAlternativeNames();
|
||||
|
||||
// 0.0.0.0 should be iPAddress type
|
||||
boolean foundZeroIp = sans.stream()
|
||||
.anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress
|
||||
&& san.get(1).toString().equals("0.0.0.0"));
|
||||
assertTrue(foundZeroIp,
|
||||
"0.0.0.0 should be encoded as iPAddress SAN (type 7). Found SANs: " + sans);
|
||||
|
||||
// ::1 should be iPAddress type (rendered as 0:0:0:0:0:0:0:1 by Java)
|
||||
boolean foundIpv6 = sans.stream()
|
||||
.anyMatch(san -> (Integer) san.get(0) == GeneralName.iPAddress
|
||||
&& san.get(1).toString().contains("0:0:0:0:0:0:0:1"));
|
||||
assertTrue(foundIpv6,
|
||||
"::1 should be encoded as iPAddress SAN (type 7). Found SANs: " + sans);
|
||||
}
|
||||
|
||||
@Test
|
||||
void dnsNamesEncodedAsDnsNameSanType() throws Exception {
|
||||
var cert = generator.generateCertificate(
|
||||
"localhost",
|
||||
List.of("myhost.example.com", "floci"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
|
||||
X509Certificate x509 = generator.parseCertificate(cert.certificatePem());
|
||||
Collection<List<?>> sans = x509.getSubjectAlternativeNames();
|
||||
|
||||
// myhost.example.com should be dNSName type
|
||||
boolean foundDns = sans.stream()
|
||||
.anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName
|
||||
&& san.get(1).toString().equals("myhost.example.com"));
|
||||
assertTrue(foundDns,
|
||||
"myhost.example.com should be encoded as dNSName SAN (type 2). Found SANs: " + sans);
|
||||
|
||||
// floci should be dNSName type
|
||||
boolean foundFloci = sans.stream()
|
||||
.anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName
|
||||
&& san.get(1).toString().equals("floci"));
|
||||
assertTrue(foundFloci,
|
||||
"floci should be encoded as dNSName SAN (type 2). Found SANs: " + sans);
|
||||
}
|
||||
|
||||
@Test
|
||||
void wildcardEncodedAsDnsNameSanType() throws Exception {
|
||||
var cert = generator.generateCertificate(
|
||||
"localhost",
|
||||
List.of("localhost", "*.localhost"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
|
||||
X509Certificate x509 = generator.parseCertificate(cert.certificatePem());
|
||||
Collection<List<?>> sans = x509.getSubjectAlternativeNames();
|
||||
|
||||
boolean foundWildcard = sans.stream()
|
||||
.anyMatch(san -> (Integer) san.get(0) == GeneralName.dNSName
|
||||
&& san.get(1).toString().equals("*.localhost"));
|
||||
assertTrue(foundWildcard,
|
||||
"*.localhost should be encoded as dNSName SAN (type 2). Found SANs: " + sans);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixedIpsAndDnsNamesEncodedCorrectly() throws Exception {
|
||||
var cert = generator.generateCertificate(
|
||||
"localhost",
|
||||
List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost", "floci", "10.0.0.5"),
|
||||
KeyAlgorithm.RSA_2048);
|
||||
|
||||
X509Certificate x509 = generator.parseCertificate(cert.certificatePem());
|
||||
Collection<List<?>> sans = x509.getSubjectAlternativeNames();
|
||||
|
||||
// Count DNS vs IP SANs
|
||||
long dnsCount = sans.stream()
|
||||
.filter(san -> (Integer) san.get(0) == GeneralName.dNSName)
|
||||
.count();
|
||||
long ipCount = sans.stream()
|
||||
.filter(san -> (Integer) san.get(0) == GeneralName.iPAddress)
|
||||
.count();
|
||||
|
||||
// DNS: localhost, *.localhost, floci = 3
|
||||
assertEquals(3, dnsCount,
|
||||
"Should have 3 dNSName SANs (localhost, *.localhost, floci). Found SANs: " + sans);
|
||||
// IP: 127.0.0.1, 0.0.0.0, 10.0.0.5 = 3
|
||||
assertEquals(3, ipCount,
|
||||
"Should have 3 iPAddress SANs (127.0.0.1, 0.0.0.0, 10.0.0.5). Found SANs: " + sans);
|
||||
}
|
||||
|
||||
// ==================== isIpAddress utility tests ====================
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"192.168.1.1", "10.0.0.1", "127.0.0.1", "0.0.0.0", "255.255.255.255"})
|
||||
void isIpAddress_ipv4(String value) {
|
||||
assertTrue(CertificateGenerator.isIpAddress(value), value + " should be detected as IP");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"::1", "fe80::1", "2001:db8::1", "[::1]", "[fe80::1]"})
|
||||
void isIpAddress_ipv6(String value) {
|
||||
assertTrue(CertificateGenerator.isIpAddress(value), value + " should be detected as IP");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"localhost", "floci", "myhost.example.com", "*.localhost", "a.b.c.d.e"})
|
||||
void isIpAddress_dnsNames(String value) {
|
||||
assertFalse(CertificateGenerator.isIpAddress(value), value + " should NOT be detected as IP");
|
||||
}
|
||||
|
||||
@Test
|
||||
void isIpAddress_nullAndBlank() {
|
||||
assertFalse(CertificateGenerator.isIpAddress(null));
|
||||
assertFalse(CertificateGenerator.isIpAddress(""));
|
||||
assertFalse(CertificateGenerator.isIpAddress(" "));
|
||||
}
|
||||
}
|
||||
+9
@@ -308,6 +308,15 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
public DockerConfig docker() { return null; }
|
||||
@Override
|
||||
public EmulatorConfig.InitHooksConfig initHooks() { return null; }
|
||||
@Override
|
||||
public TlsConfig tls() {
|
||||
return new TlsConfig() {
|
||||
@Override public boolean enabled() { return false; }
|
||||
@Override public Optional<String> certPath() { return Optional.empty(); }
|
||||
@Override public Optional<String> keyPath() { return Optional.empty(); }
|
||||
@Override public boolean selfSigned() { return true; }
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user