Support TLS for cluster node transport

This commit is contained in:
admin committed 2026-10-10 23:57:38 +02:00
1 parent 1d1f329220
commit a71c4fa5f1
9 files changed
+327 -13

No files matched your search

+4 -3
View File
@@ -1,7 +1,6 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -325,7 +324,8 @@ public final class ClusterNode implements AutoCloseable {
env.get("CLUSTER_REPAIR_TOKEN"),
UUID.fromString(env.get("CLUSTER_HOST_ID")));
int port = Integer.parseInt(env.getOrDefault("NODE_PORT", "9100"));
var server = HttpServer.create(new InetSocketAddress(env.getOrDefault("NODE_BIND", "127.0.0.1"), port), 64);
var server = ClusterTls.nodeServer(
new InetSocketAddress(env.getOrDefault("NODE_BIND", "127.0.0.1"), port), env);
var executor = Executors.newVirtualThreadPerTaskExecutor();
server.setExecutor(executor);
server.createContext("/", node::handle);
@@ -336,6 +336,7 @@ public final class ClusterNode implements AutoCloseable {
catch (IOException error) { System.err.println("Node close failed: " + error); }
}));
server.start();
System.out.println("ObjectStore cluster node listening on :" + port);
System.out.println("ObjectStore cluster node listening on :" + port +
(server instanceof com.sun.net.httpserver.HttpsServer ? " (TLS)" : " (HTTP)"));
}
}
+99
View File
@@ -0,0 +1,99 @@
package cloud.lunarsky.store;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.time.Duration;
import java.util.Arrays;
import java.util.Map;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
final class ClusterTls {
private ClusterTls() { }
static HttpServer nodeServer(InetSocketAddress address, Map<String, String> env) throws IOException {
String keyStore = env.get("NODE_TLS_KEYSTORE");
String passwordFile = env.get("NODE_TLS_PASSWORD_FILE");
if (missing(keyStore) && missing(passwordFile)) return HttpServer.create(address, 64);
if (missing(keyStore) || missing(passwordFile))
throw new IOException("Node TLS requires both NODE_TLS_KEYSTORE and NODE_TLS_PASSWORD_FILE");
SSLContext context = serverContext(Path.of(keyStore), Path.of(passwordFile));
HttpsServer server = HttpsServer.create(address, 64);
server.setHttpsConfigurator(new HttpsConfigurator(context));
return server;
}
static HttpClient client(Map<String, String> env, Duration timeout) throws IOException {
String trustStore = env.get("CLUSTER_TLS_TRUSTSTORE");
String passwordFile = env.get("CLUSTER_TLS_PASSWORD_FILE");
if (missing(trustStore) != missing(passwordFile))
throw new IOException("Cluster TLS requires both CLUSTER_TLS_TRUSTSTORE and CLUSTER_TLS_PASSWORD_FILE");
HttpClient.Builder builder = HttpClient.newBuilder().connectTimeout(timeout);
if (!missing(trustStore))
builder.sslContext(clientContext(Path.of(trustStore), Path.of(passwordFile)));
return builder.build();
}
private static SSLContext serverContext(Path keyStore, Path passwordFile) throws IOException {
char[] password = password(passwordFile);
try {
KeyStore keys = load(keyStore, password);
KeyManagerFactory managers = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
managers.init(keys, password);
SSLContext context = SSLContext.getInstance("TLS");
context.init(managers.getKeyManagers(), null, null);
return context;
} catch (GeneralSecurityException error) {
throw new IOException("Could not configure node TLS", error);
} finally {
Arrays.fill(password, '\0');
}
}
private static SSLContext clientContext(Path trustStore, Path passwordFile) throws IOException {
char[] password = password(passwordFile);
try {
KeyStore trust = load(trustStore, password);
TrustManagerFactory managers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
managers.init(trust);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, managers.getTrustManagers(), null);
return context;
} catch (GeneralSecurityException error) {
throw new IOException("Could not configure cluster TLS trust", error);
} finally {
Arrays.fill(password, '\0');
}
}
private static KeyStore load(Path path, char[] password) throws IOException, GeneralSecurityException {
KeyStore store = KeyStore.getInstance("PKCS12");
try (InputStream input = Files.newInputStream(path)) {
store.load(input, password);
}
return store;
}
private static char[] password(Path file) throws IOException {
String value = Files.readString(file, StandardCharsets.UTF_8);
if (value.endsWith("\n")) value = value.substring(0, value.length() - 1);
if (value.endsWith("\r")) value = value.substring(0, value.length() - 1);
if (value.isEmpty()) throw new IOException("Cluster TLS password file is empty");
return value.toCharArray();
}
private static boolean missing(String value) {
return value == null || value.isBlank();
}
}
+35 -8
View File
@@ -21,18 +21,21 @@ final class NodeClient {
record Node(UUID id, UUID hostId, URI url) {}
record StoredSegment(UUID id, long modified) {}
private static final HttpClient IDENTITY_HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2)).build();
private static HttpClient identityHttp;
private final List<Node> nodes;
private final String token;
private final String repairToken;
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
private final HttpClient http;
private final ConcurrentHashMap<UUID, Long> unreadableUntil = new ConcurrentHashMap<>();
private final ConcurrentHashMap<UUID, Long> healthyUntil = new ConcurrentHashMap<>();
private static final long READ_RETRY_NANOS = TimeUnit.SECONDS.toNanos(5);
private static final long HEALTH_FRESH_NANOS = TimeUnit.SECONDS.toNanos(3);
NodeClient(List<Node> nodes, String token, String repairToken) {
NodeClient(List<Node> nodes, String token, String repairToken) throws IOException {
this(nodes, token, repairToken, ClusterTls.client(System.getenv(), Duration.ofSeconds(3)));
}
NodeClient(List<Node> nodes, String token, String repairToken, HttpClient http) {
if (nodes.isEmpty() || nodes.stream().map(Node::id).distinct().count() != nodes.size() ||
nodes.stream().map(Node::url).distinct().count() != nodes.size())
throw new IllegalArgumentException("Cluster node IDs and URLs must be unique");
@@ -45,6 +48,7 @@ final class NodeClient {
this.nodes = List.copyOf(nodes);
this.token = token;
this.repairToken = repairToken;
this.http = java.util.Objects.requireNonNull(http);
}
int count() { return nodes.size(); }
@@ -63,12 +67,16 @@ final class NodeClient {
}
static NodeIdentity probe(URI url, String token) throws IOException {
return probe(url, token, identityHttp());
}
static NodeIdentity probe(URI url, String token, HttpClient http) throws IOException {
validateUrl(url);
if (token == null || token.length() < 32) throw new IllegalArgumentException("Invalid cluster token");
HttpRequest request = HttpRequest.newBuilder(url.resolve("/identity"))
.timeout(Duration.ofSeconds(2)).header("X-Cluster-Token", token).GET().build();
try {
HttpResponse<InputStream> response = IDENTITY_HTTP.send(request, HttpResponse.BodyHandlers.ofInputStream());
HttpResponse<InputStream> response = http.send(request, HttpResponse.BodyHandlers.ofInputStream());
try (InputStream body = response.body()) {
if (response.statusCode() != 200) throw new IOException("Node identity request failed: " + response.statusCode());
byte[] bytes = body.readNBytes(128);
@@ -90,19 +98,38 @@ final class NodeClient {
catch (IOException offline) { return null; }
}
private static NodeIdentity probeIfAvailable(URI url, String token, HttpClient http) {
try { return probe(url, token, http); }
catch (IOException offline) { return null; }
}
private static synchronized HttpClient identityHttp() throws IOException {
if (identityHttp == null)
identityHttp = ClusterTls.client(System.getenv(), Duration.ofSeconds(2));
return identityHttp;
}
static void validateUrl(URI url) {
if (url == null || !"http".equals(url.getScheme()) || url.getHost() == null ||
String trustStore = System.getenv("CLUSTER_TLS_TRUSTSTORE");
validateUrl(url, trustStore != null && !trustStore.isBlank());
}
static void validateUrl(URI url, boolean requireHttps) {
if (url == null || !("http".equals(url.getScheme()) || "https".equals(url.getScheme())) ||
url.getHost() == null ||
url.getPort() < 1 || url.getRawUserInfo() != null ||
(url.getRawPath() != null && !url.getRawPath().isEmpty()) ||
url.getRawQuery() != null || url.getRawFragment() != null)
throw new IllegalArgumentException("Invalid private storage node URL");
if (requireHttps && !"https".equals(url.getScheme()))
throw new IllegalArgumentException("Cluster TLS truststore requires HTTPS node URLs");
}
boolean availableHostsAtLeast(int required, boolean testNodeDomains) {
Set<UUID> healthy = new HashSet<>();
for (int i = 0; i < nodes.size(); i++) {
Node node = nodes.get(i);
NodeIdentity actual = probeIfAvailable(node.url(), token);
NodeIdentity actual = probeIfAvailable(node.url(), token, http);
if (actual == null || !actual.nodeId().equals(node.id()) || !actual.hostId().equals(node.hostId())) {
markUnreadable(node);
continue;
@@ -159,7 +186,7 @@ final class NodeClient {
Node node = nodes.get(index);
if (unreadable(node)) throw new IOException("Storage node is temporarily unreachable");
if (!recentlyHealthy(node)) {
NodeIdentity actual = probeIfAvailable(node.url(), token);
NodeIdentity actual = probeIfAvailable(node.url(), token, http);
if (actual == null || !actual.nodeId().equals(node.id()) || !actual.hostId().equals(node.hostId())) {
markUnreadable(node);
throw new IOException("Storage node is temporarily unreachable");