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:
authored and GitHub committed 2026-05-10 10:21:03 -05:00
1 parent f62969a5b1
commit 5befe8b619
28 files changed
+3932 -4

No files matched your search

@@ -0,0 +1,122 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
/**
* Metadata for self-signed TLS certificates generated by Floci.
*
* <p>
* This metadata is persisted alongside certificate files to track which hostnames
* were used during generation. It enables detection of configuration changes on
* restart, allowing the system to regenerate certificates when hostname configuration
* changes.
*
* <p>
* The metadata file is stored as JSON at {@code {persistent-path}/tls/floci-selfsigned.metadata.json}.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@RegisterForReflection
public class CertificateMetadata {
/**
* List of hostnames that were included in the certificate's Subject Alternative Names (SANs).
* This includes both default hostnames (localhost, 127.0.0.1, etc.) and custom hostnames
* from FLOCI_HOSTNAME and FLOCI_BASE_URL configuration.
*/
private List<String> hostnames;
/**
* ISO-8601 timestamp when the certificate was generated.
* Used for debugging and auditing purposes.
*/
private String generatedAt;
/**
* Floci version that generated the certificate.
* Used for debugging and potential future migration scenarios.
*/
private String flociVersion;
/**
* Default constructor for Jackson deserialization.
*/
public CertificateMetadata() {
}
/**
* Creates certificate metadata with the specified hostnames.
*
* @param hostnames List of hostnames included in the certificate SANs
* @param generatedAt ISO-8601 timestamp when the certificate was generated
* @param flociVersion Floci version that generated the certificate
*/
public CertificateMetadata(List<String> hostnames, String generatedAt, String flociVersion) {
this.hostnames = hostnames;
this.generatedAt = generatedAt;
this.flociVersion = flociVersion;
}
/**
* Creates certificate metadata with the specified hostnames and current timestamp.
*
* @param hostnames List of hostnames included in the certificate SANs
* @param flociVersion Floci version that generated the certificate
* @return New CertificateMetadata instance with current timestamp
*/
public static CertificateMetadata create(List<String> hostnames, String flociVersion) {
return new CertificateMetadata(hostnames, Instant.now().toString(), flociVersion);
}
public List<String> getHostnames() {
return hostnames;
}
public void setHostnames(List<String> hostnames) {
this.hostnames = hostnames;
}
public String getGeneratedAt() {
return generatedAt;
}
public void setGeneratedAt(String generatedAt) {
this.generatedAt = generatedAt;
}
public String getFlociVersion() {
return flociVersion;
}
public void setFlociVersion(String flociVersion) {
this.flociVersion = flociVersion;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CertificateMetadata that = (CertificateMetadata) o;
return Objects.equals(hostnames, that.hostnames) &&
Objects.equals(generatedAt, that.generatedAt) &&
Objects.equals(flociVersion, that.flociVersion);
}
@Override
public int hashCode() {
return Objects.hash(hostnames, generatedAt, flociVersion);
}
@Override
public String toString() {
return "CertificateMetadata{" +
"hostnames=" + hostnames +
", generatedAt='" + generatedAt + '\'' +
", flociVersion='" + flociVersion + '\'' +
'}';
}
}
@@ -27,13 +27,18 @@ public interface EmulatorConfig {
Optional<String> hostname();
/**
* Returns the effective base URL, taking hostname into account.
* Returns the effective base URL, taking hostname and TLS into account.
* If hostname is set, replaces the host in baseUrl with it.
* If TLS is enabled, switches the scheme from http:// to https://.
*/
default String effectiveBaseUrl() {
return hostname()
String url = hostname()
.map(h -> baseUrl().replaceFirst("://[^:/]+(:\\d+)?", "://" + h + "$1"))
.orElse(baseUrl());
if (tls().enabled() && url.startsWith("http://")) {
url = "https://" + url.substring(7);
}
return url;
}
@WithDefault("us-east-1")
@@ -63,6 +68,8 @@ public interface EmulatorConfig {
InitHooksConfig initHooks();
TlsConfig tls();
interface DnsConfig {
/**
* Additional hostname suffixes the embedded DNS server will resolve to Floci's
@@ -838,6 +845,33 @@ public interface EmulatorConfig {
long timeoutSeconds();
}
/**
* Optional TLS configuration for enabling HTTPS on the Floci server.
* When enabled, all endpoints are reachable via {@code https://} and
* WebSocket connections work via {@code wss://}.
*
* <p>Both HTTP and HTTPS are served simultaneously (LocalStack parity).
*/
interface TlsConfig {
/** Enable TLS/HTTPS on the server. Env: FLOCI_TLS_ENABLED */
@WithDefault("false")
boolean enabled();
/** Path to PEM certificate file. Env: FLOCI_TLS_CERT_PATH */
Optional<String> certPath();
/** Path to PEM private key file. Env: FLOCI_TLS_KEY_PATH */
Optional<String> keyPath();
/**
* Auto-generate a self-signed certificate when no cert-path/key-path provided.
* The generated files are persisted to {@code {storage.persistent-path}/tls/}
* and reused across restarts. Env: FLOCI_TLS_SELF_SIGNED
*/
@WithDefault("true")
boolean selfSigned();
}
/**
* Configuration for Docker container management shared across all services
* that spawn Docker containers (Lambda, RDS, ElastiCache, ECS, ECR, MSK).
@@ -0,0 +1,334 @@
package io.github.hectorvent.floci.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.eclipse.microprofile.config.spi.ConfigSource;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.security.Security;
/**
* A MicroProfile {@link ConfigSource} that dynamically provides Quarkus TLS/SSL
* configuration when {@code floci.tls.enabled=true}.
*
* <p>
* This runs <em>before</em> the Quarkus HTTP server starts, which is critical
* because Quarkus reads {@code quarkus.http.ssl.*} properties during server
* initialization. A CDI {@code @Startup} bean or {@code StartupEvent} observer
* would be too late.
*
* <p>
* When TLS is enabled with self-signed mode, the certificate is generated
* using the ACM {@link CertificateGenerator} and persisted under
* {@code {persistent-path}/tls/} for reuse across restarts.
*
* <p>
* Both HTTP and HTTPS are served simultaneously (LocalStack parity).
*/
public class TlsConfigSource implements ConfigSource {
private static final Logger LOG = Logger.getLogger(TlsConfigSource.class);
private static final String SELF_SIGNED_CERT_NAME = "floci-selfsigned.crt";
private static final String SELF_SIGNED_KEY_NAME = "floci-selfsigned.key";
private static final String SELF_SIGNED_METADATA_NAME = "floci-selfsigned.metadata.json";
private static final String TLS_DIR = "tls";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final Map<String, String> properties = new HashMap<>();
public TlsConfigSource() {
String enabled = resolveProperty("floci.tls.enabled", "false");
if (!"true".equalsIgnoreCase(enabled)) {
LOG.debug("TLS disabled — TlsConfigSource inactive");
return;
}
String certPath = resolveProperty("floci.tls.cert-path", "");
String keyPath = resolveProperty("floci.tls.key-path", "");
String selfSigned = resolveProperty("floci.tls.self-signed", "true");
String persistentPath = resolveProperty("floci.storage.persistent-path", "./data");
if (!certPath.isBlank() && !keyPath.isBlank()) {
validateFileExists(certPath, "TLS certificate");
validateFileExists(keyPath, "TLS private key");
LOG.infov("TLS: using user-provided certificate: {0}", certPath);
} else if ("true".equalsIgnoreCase(selfSigned)) {
Path tlsDir = Path.of(persistentPath, TLS_DIR);
Path certFile = tlsDir.resolve(SELF_SIGNED_CERT_NAME);
Path keyFile = tlsDir.resolve(SELF_SIGNED_KEY_NAME);
// Check if certificate files exist and configuration hasn't changed
if (Files.exists(certFile) && Files.exists(keyFile)) {
// Extract current hostname configuration
List<String> customHostnames = extractCustomHostnames();
List<String> currentHostnames = new ArrayList<>();
currentHostnames.addAll(List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
"localhost.floci.io", "*.localhost.floci.io"));
currentHostnames.addAll(customHostnames);
// Check if hostname configuration has changed
if (hostnameConfigChanged(tlsDir, currentHostnames)) {
// Configuration changed or metadata missing - regenerate certificate
generateSelfSignedCert(tlsDir, certFile, keyFile);
} else {
// Configuration unchanged - reuse existing certificate
LOG.infov("TLS: reusing existing self-signed certificate: {0}", certFile);
}
} else {
// Certificate files don't exist - generate new certificate
generateSelfSignedCert(tlsDir, certFile, keyFile);
}
certPath = certFile.toAbsolutePath().toString();
keyPath = keyFile.toAbsolutePath().toString();
} else {
throw new IllegalStateException(
"TLS enabled but no certificate provided and self-signed generation disabled. "
+ "Set FLOCI_TLS_CERT_PATH + FLOCI_TLS_KEY_PATH, or enable FLOCI_TLS_SELF_SIGNED.");
}
properties.put("quarkus.http.ssl.certificate.files", certPath);
properties.put("quarkus.http.ssl.certificate.key-files", keyPath);
// When TLS is enabled, Quarkus HTTP and HTTPS run on internal ports.
// A TlsProxyServer (NetServer) listens on the public Floci port (4566)
// and does protocol detection to route HTTP and HTTPS to the correct backend.
properties.put("quarkus.http.insecure-requests", "enabled");
properties.put("quarkus.http.host", "127.0.0.1");
properties.put("quarkus.http.port", "4510");
properties.put("quarkus.http.ssl-port", "4511");
LOG.infov("TLS: HTTPS enabled — proxy will listen on port {0} (HTTP+HTTPS), cert={1}",
resolveProperty("floci.port", "4566"), certPath);
}
@Override
public int getOrdinal() {
// Higher than application.yml (250) so TLS properties take precedence
return 300;
}
@Override
public Set<String> getPropertyNames() {
return properties.keySet();
}
@Override
public String getValue(String propertyName) {
return properties.get(propertyName);
}
@Override
public String getName() {
return "FlociTlsConfigSource";
}
/**
* Resolves a property from system properties or environment variables.
* Environment variable names follow the MicroProfile convention:
* {@code floci.tls.enabled} → {@code FLOCI_TLS_ENABLED}.
*/
private static String resolveProperty(String key, String defaultValue) {
// 1. System property (highest priority)
String value = System.getProperty(key);
if (value != null && !value.isBlank())
return value;
// 2. Environment variable (underscore + uppercase)
String envKey = key.replace('.', '_').replace('-', '_').toUpperCase();
value = System.getenv(envKey);
if (value != null && !value.isBlank())
return value;
return defaultValue;
}
private void generateSelfSignedCert(Path tlsDir, Path certFile, Path keyFile) {
try {
Files.createDirectories(tlsDir);
// BouncyCastle may not be registered yet — ConfigSource runs before CDI
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
// Extract custom hostnames and combine with defaults
List<String> customHostnames = extractCustomHostnames();
List<String> allSans = new ArrayList<>();
allSans.addAll(List.of("localhost", "127.0.0.1", "0.0.0.0", "*.localhost",
"localhost.floci.io", "*.localhost.floci.io"));
allSans.addAll(customHostnames);
CertificateGenerator gen = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate generated = gen.generateCertificate(
"localhost",
allSans,
KeyAlgorithm.RSA_2048);
Files.writeString(certFile, generated.certificatePem());
Files.writeString(keyFile, generated.privateKeyPem());
LOG.infov("TLS: generated self-signed certificate: {0}", certFile);
// Persist metadata for change detection on restart
persistMetadata(tlsDir, allSans);
} catch (IOException e) {
throw new IllegalStateException("Failed to write self-signed TLS certificate", e);
}
}
private static void validateFileExists(String path, String description) {
if (!Files.isReadable(Path.of(path))) {
throw new IllegalStateException(
description + " file not found or not readable: " + path);
}
}
/**
* Extracts custom hostnames from FLOCI_HOSTNAME and FLOCI_BASE_URL configuration.
* Filters out default values like "localhost" and "127.0.0.1".
* Returns a deduplicated list of custom hostnames.
*
* @return List of custom hostnames (may be empty if no custom hostnames configured)
*/
private List<String> extractCustomHostnames() {
Set<String> hostnames = new LinkedHashSet<>();
// Extract from FLOCI_HOSTNAME
String hostname = resolveProperty("floci.hostname", "");
if (!hostname.isBlank() && !isDefaultHostname(hostname)) {
hostnames.add(hostname);
LOG.debugv("TLS: extracted hostname from floci.hostname: {0}", hostname);
}
// Extract from FLOCI_BASE_URL
String baseUrl = resolveProperty("floci.base-url", "http://localhost:4566");
try {
URI uri = new URI(baseUrl);
String host = uri.getHost();
if (host != null && !isDefaultHostname(host)) {
hostnames.add(host);
LOG.debugv("TLS: extracted hostname from floci.base-url: {0}", host);
}
} catch (URISyntaxException e) {
LOG.warnv("TLS: failed to parse base URL for hostname extraction: {0}", baseUrl);
}
List<String> result = new ArrayList<>(hostnames);
if (!result.isEmpty()) {
LOG.infov("TLS: detected custom hostnames: {0}", result);
}
return result;
}
/**
* Checks if a hostname is a default value that should be filtered out.
*
* @param hostname The hostname to check
* @return true if the hostname is a default value (localhost, 127.0.0.1, 0.0.0.0)
*/
private boolean isDefaultHostname(String hostname) {
return hostname.equals("localhost")
|| hostname.equals("127.0.0.1")
|| hostname.equals("0.0.0.0");
}
/**
* Persists certificate metadata to enable change detection on restart.
* Writes metadata to {tls-dir}/floci-selfsigned.metadata.json.
*
* @param tlsDir The TLS directory where metadata should be written
* @param hostnames List of hostnames included in the certificate SANs
*/
private void persistMetadata(Path tlsDir, List<String> hostnames) {
Path metadataFile = tlsDir.resolve(SELF_SIGNED_METADATA_NAME);
try {
String version = resolveFlociVersion();
CertificateMetadata metadata = CertificateMetadata.create(hostnames, version);
String json = OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(metadata);
Files.writeString(metadataFile, json);
LOG.debugv("TLS: persisted certificate metadata: {0}", metadataFile);
} catch (IOException e) {
// Log warning but don't fail startup - metadata is for optimization, not critical
LOG.warnv("TLS: failed to write certificate metadata (will regenerate on next restart): {0}", e.getMessage());
}
}
/**
* Resolves the Floci version from environment variable or defaults to "dev".
*
* @return Floci version string
*/
private static String resolveFlociVersion() {
String env = System.getenv("FLOCI_VERSION");
if (env != null && !env.isBlank()) {
return env;
}
return "dev";
}
/**
* Checks if the hostname configuration has changed since the last certificate generation.
* Loads the metadata file and compares the hostnames with the current configuration.
*
* @param tlsDir The TLS directory where metadata file is stored
* @param currentHostnames List of hostnames from current configuration
* @return true if configuration changed or metadata missing, false if same
*/
private boolean hostnameConfigChanged(Path tlsDir, List<String> currentHostnames) {
Path metadataFile = tlsDir.resolve(SELF_SIGNED_METADATA_NAME);
// If metadata doesn't exist, trigger regeneration
if (!Files.exists(metadataFile)) {
LOG.infov("TLS: metadata file missing, regenerating certificate to ensure correctness");
return true;
}
try {
// Load and parse metadata file
String json = Files.readString(metadataFile);
CertificateMetadata metadata = OBJECT_MAPPER.readValue(json, CertificateMetadata.class);
List<String> previousHostnames = metadata.getHostnames();
if (previousHostnames == null) {
LOG.warnv("TLS: metadata file has no hostnames field, regenerating certificate");
return true;
}
// Compare hostnames (order-independent)
Set<String> previousSet = new LinkedHashSet<>(previousHostnames);
Set<String> currentSet = new LinkedHashSet<>(currentHostnames);
if (!previousSet.equals(currentSet)) {
LOG.infov("TLS: hostname configuration changed, regenerating certificate");
LOG.debugv("TLS: previous hostnames: {0}", previousHostnames);
LOG.debugv("TLS: current hostnames: {0}", currentHostnames);
return true;
}
// Configuration unchanged
LOG.debugv("TLS: hostname configuration unchanged, reusing certificate");
return false;
} catch (IOException e) {
// Handle read/parse failures gracefully - trigger regeneration
LOG.warnv("TLS: failed to read metadata file (will regenerate certificate): {0}", e.getMessage());
return true;
}
}
}
@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.config;
import io.quarkus.runtime.Startup;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
/**
* A TCP proxy server that enables HTTP and HTTPS on the same port (LocalStack parity).
*
* <p>When TLS is enabled, Quarkus serves HTTP on an internal port (4510) and HTTPS on
* another internal port (4511). This proxy listens on the public Floci port (4566) and
* inspects the first byte of each incoming connection:
* <ul>
* <li>{@code 0x16} (TLS ClientHello) → proxy to HTTPS backend (port 4511)</li>
* <li>Anything else → proxy to HTTP backend (port 4510)</li>
* </ul>
*
* <p>This achieves true dual-protocol support on a single port, matching LocalStack's
* behavior where both {@code http://localhost:4566} and {@code https://localhost:4566}
* work simultaneously.
*
* <p>This bean is only active when {@code floci.tls.enabled=true}. When TLS is disabled,
* Quarkus serves HTTP directly on port 4566 and this proxy is not started.
*/
@ApplicationScoped
@Startup
public class TlsProxyServer {
private static final Logger LOG = Logger.getLogger(TlsProxyServer.class);
/** TLS record content type for Handshake (ClientHello). */
private static final byte TLS_HANDSHAKE = 0x16;
private static final int HTTP_BACKEND_PORT = 4510;
private static final int HTTPS_BACKEND_PORT = 4511;
private final Vertx vertx;
private final EmulatorConfig config;
private NetServer proxyServer;
private NetClient client;
@Inject
public TlsProxyServer(Vertx vertx, EmulatorConfig config) {
this.vertx = vertx;
this.config = config;
startIfTlsEnabled();
}
private void startIfTlsEnabled() {
if (!config.tls().enabled()) {
return;
}
int publicPort = config.port();
NetServerOptions options = new NetServerOptions()
.setHost("0.0.0.0")
.setPort(publicPort);
proxyServer = vertx.createNetServer(options);
client = vertx.createNetClient();
proxyServer.connectHandler(frontSocket -> {
// Pause incoming data until we've peeked at the first byte
frontSocket.pause();
frontSocket.handler(buffer -> {
// Remove handler and keep socket paused to prevent data loss
// while we establish the backend connection.
frontSocket.handler(null);
frontSocket.pause();
// Inspect first byte to determine protocol
int backendPort;
if (buffer.length() > 0 && buffer.getByte(0) == TLS_HANDSHAKE) {
backendPort = HTTPS_BACKEND_PORT;
} else {
backendPort = HTTP_BACKEND_PORT;
}
// Connect to the appropriate backend
client.connect(backendPort, "127.0.0.1").onComplete(ar -> {
if (ar.succeeded()) {
NetSocket backSocket = ar.result();
// Send the initial buffer that we already read
backSocket.write(buffer);
// Bi-directional pipe — pipeTo handles end-of-stream
// propagation and will resume the paused frontSocket.
frontSocket.pipeTo(backSocket).onFailure(err ->
LOG.debugv("TLS proxy: pipe front→back failed: {0}", err.getMessage()));
backSocket.pipeTo(frontSocket).onFailure(err ->
LOG.debugv("TLS proxy: pipe back→front failed: {0}", err.getMessage()));
} else {
LOG.warnv("TLS proxy: failed to connect to backend port {0}: {1}",
backendPort, ar.cause().getMessage());
frontSocket.close();
}
});
});
// Resume to receive the first buffer
frontSocket.resume();
});
proxyServer.listen().onComplete(ar -> {
if (ar.succeeded()) {
LOG.infov("TLS proxy: listening on port {0} (HTTP→{1}, HTTPS→{2})",
publicPort, HTTP_BACKEND_PORT, HTTPS_BACKEND_PORT);
} else {
LOG.errorv("TLS proxy: failed to start on port {0}: {1}",
publicPort, ar.cause().getMessage());
}
});
}
@PreDestroy
void stop() {
if (proxyServer != null) {
proxyServer.close();
}
if (client != null) {
client.close();
}
LOG.info("TLS proxy: stopped");
}
}
@@ -82,6 +82,7 @@ public class EmulatorLifecycle {
LOG.info("=== AWS Local Emulator Starting ===");
LOG.infov("Storage mode: {0}", config.storage().mode());
LOG.infov("Persistent path: {0}", config.storage().persistentPath());
LOG.infov("TLS: {0}", config.tls().enabled() ? "enabled (HTTPS + HTTP dual mode)" : "disabled (HTTP only)");
// BOOT hooks run before service initialization — scripts cannot use AWS APIs yet.
try {
@@ -30,6 +30,7 @@ import org.jboss.logging.Logger;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigInteger;
import java.net.InetAddress;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
@@ -43,6 +44,7 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
@ApplicationScoped
public class CertificateGenerator {
@@ -51,6 +53,14 @@ public class CertificateGenerator {
private static final String ISSUER_DN = "CN=Amazon,OU=Server CA 1B,O=Amazon,C=US";
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
/**
* Pattern matching IPv4 addresses (e.g. 192.168.1.100) and IPv6 addresses
* (bracketed like [::1] or raw like ::1, fe80::1).
*/
private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile(
"^\\[?([0-9a-fA-F:]+)]?$|^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$"
);
public record GeneratedCertificate(
String certificatePem,
String privateKeyPem,
@@ -98,11 +108,11 @@ public class CertificateGenerator {
// Add Subject Alternative Names
List<GeneralName> sanList = new ArrayList<>();
sanList.add(new GeneralName(GeneralName.dNSName, domainName));
sanList.add(toGeneralName(domainName));
if (sans != null) {
for (String san : sans) {
if (!san.equals(domainName)) {
sanList.add(new GeneralName(GeneralName.dNSName, san));
sanList.add(toGeneralName(san));
}
}
}
@@ -166,6 +176,41 @@ public class CertificateGenerator {
return keyGen.generateKeyPair();
}
/**
* Creates the appropriate {@link GeneralName} for a SAN entry.
* IP addresses (IPv4 and IPv6) use {@code GeneralName.iPAddress},
* all other values use {@code GeneralName.dNSName}.
*/
private static GeneralName toGeneralName(String san) {
if (isIpAddress(san)) {
try {
// Strip brackets from IPv6 if present (e.g. [::1] → ::1)
String raw = san.startsWith("[") && san.endsWith("]")
? san.substring(1, san.length() - 1)
: san;
byte[] addr = InetAddress.getByName(raw).getAddress();
return new GeneralName(GeneralName.iPAddress,
new org.bouncycastle.asn1.DEROctetString(addr));
} catch (Exception e) {
// Fallback to DNS name if IP parsing fails
LOG.debugv("Could not parse '{0}' as IP address, treating as DNS name", san);
return new GeneralName(GeneralName.dNSName, san);
}
}
return new GeneralName(GeneralName.dNSName, san);
}
/**
* Checks whether a SAN value looks like an IP address (IPv4 or IPv6).
* Wildcard entries (e.g. *.localhost) are never IP addresses.
*/
static boolean isIpAddress(String value) {
if (value == null || value.isBlank() || value.startsWith("*")) {
return false;
}
return IP_ADDRESS_PATTERN.matcher(value).matches();
}
private String toPem(Object obj) throws Exception {
StringWriter sw = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(sw)) {