Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ public class RaftHAPlugin implements HAServerPlugin, HAReplicationStatsProvider
// Read by concurrent HTTP worker threads (e.g. the readiness probe via getReadinessSignal) while it is
// (re)assigned by the server startup/shutdown thread, so the reference must be published with volatile.
private volatile RaftHAServer raftHAServer;
// The cluster token of the Raft server this plugin stopped, kept so the node goes on recognising its peers for the
// rest of its shutdown (issue #9554): ArcadeDBServer stops HA before the HTTP listener, and a forward still reaching
// the node in between must get the retryable "not the leader" answer, not 401 "Invalid cluster token". The token
// never changes for the life of the process, so the kept value cannot go stale.
private volatile String stoppedClusterToken;

// Databases already warned about single-bucket types, so the diagnostic is logged once per
// database per plugin lifetime instead of on every (re)wrap.
Expand Down Expand Up @@ -218,6 +223,9 @@ public void startService() {
@Override
public void stopService() {
if (raftHAServer != null) {
final String clusterToken = raftHAServer.getClusterToken();
if (clusterToken != null)
stoppedClusterToken = clusterToken;
// Never issue leaveCluster() on shutdown: the K8s auto-leave (formerly in RaftHAServer.stop())
// silently shrank the committed Raft membership on every pod recreation and the node was never
// re-added (issue #5275); a duplicate leave here also caused redundant reconfig work and a
Expand Down Expand Up @@ -894,7 +902,8 @@ public String getCriticalHaltReason() {

@Override
public String getClusterToken() {
return raftHAServer != null ? raftHAServer.getClusterToken() : null;
final RaftHAServer s = raftHAServer;
return s != null ? s.getClusterToken() : stoppedClusterToken;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import com.arcadedb.serializer.json.JSONArray;
import com.arcadedb.serializer.json.JSONObject;
import com.arcadedb.server.ArcadeDBServer;
import com.arcadedb.server.HAServerPlugin;
import com.arcadedb.server.http.HttpServer;
import com.arcadedb.server.security.ServerSecurityUser;
import io.undertow.server.HttpHandler;
Expand Down Expand Up @@ -770,9 +771,10 @@ private ServerSecurityUser authenticate(final HttpServerExchange exchange) {
final HeaderValues clusterTokenHeader = exchange.getRequestHeaders().get("X-ArcadeDB-Cluster-Token");
if (clusterTokenHeader != null && !clusterTokenHeader.isEmpty()) {
final var server = httpServer.getServer();
final RaftHAPlugin haPlugin = server.getHA() instanceof RaftHAPlugin rp ? rp : null;
final RaftHAServer raftHAServer = haPlugin != null ? haPlugin.getRaftHAServer() : null;
final String expectedToken = raftHAServer != null ? raftHAServer.getClusterToken() : null;
// The helper every other cluster-token check uses (issue #9554): read through server.getHA() alone, the token was
// missing while the HA plugin was still starting - after Ratis could already be elected leader and asked for a
// snapshot - and once it had stopped, so a peer's correctly authenticated download was refused.
final String expectedToken = HAServerPlugin.effectiveClusterToken(server);
if (expectedToken != null && !expectedToken.isEmpty()
&& MessageDigest.isEqual(
expectedToken.getBytes(), clusterTokenHeader.getFirst().getBytes())) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com)
* SPDX-License-Identifier: Apache-2.0
*/
package com.arcadedb.server.ha.raft;

import com.arcadedb.server.ArcadeDBServer;
import com.arcadedb.server.HAServerPlugin;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Issue #9554: a peer's forwarded command was refused with HTTP 401 "Invalid cluster token" around leader changes.
* <p>
* The HTTP gate checks the token through {@link HAServerPlugin#effectiveClusterToken}, which read it only from
* {@code server.getHA()}. {@code RaftHAPlugin.startService()} registers itself there only once {@code raft.start()} has
* returned, but the HTTP listener is up long before, and Ratis is running - and can be elected leader, so its peers
* forward to it - inside {@code raft.start()}. In that window the gate fell back to the raw
* {@code arcadedb.ha.clusterToken} setting, which is empty on every cluster that lets the token be derived, so the
* peer's correct token was refused as invalid.
* <p>
* The window is reproduced on a running node by unregistering the HA plugin from the server, which leaves exactly
* what the starting node has: a running plugin, discovered and registered with the plugin manager, that
* {@code getHA()} does not name yet. The node's own background HA threads keep running meanwhile and may read
* {@code getHA()} as null too - the readiness probe, for instance - which is the state a starting node is in anyway;
* every test restores it in a {@code finally}.
*/
class Issue9554ClusterTokenAcrossHALifecycleIT extends BaseRaftHATest {

private static final HttpClient HTTP = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build();

@Test
@Timeout(120)
void aPeerForwardIsAcceptedBeforeTheHAPluginRegistersItselfOnTheServer() throws Exception {
final ArcadeDBServer server = getServer(0);
final String clusterToken = getRaftPlugin(0).getRaftHAServer().getClusterToken();
assertThat(clusterToken).as("the cluster declares no token, so the effective one is derived at startup").isNotBlank();

final HAServerPlugin ha = server.getHA();
assertThat(ha).isNotNull();
try {
server.setHA(null);

assertThat(HAServerPlugin.effectiveClusterToken(server))
.as("the token this node accepts must not depend on whether the HA plugin registered itself yet")
.isEqualTo(clusterToken);

final HttpResponse<String> response = forwardedCommand(0, clusterToken);
assertThat(response.statusCode())
.as("a peer's forward carrying the right cluster token must not be refused as 'Invalid cluster token', body: %s",
response.body())
.isEqualTo(200);
} finally {
server.setHA(ha);
}
}

@Test
@Timeout(120)
void aWrongClusterTokenIsStillRefusedInTheSameWindow() throws Exception {
final ArcadeDBServer server = getServer(0);
final HAServerPlugin ha = server.getHA();
try {
server.setHA(null);

final HttpResponse<String> response = forwardedCommand(0, "issue9554-not-the-cluster-token");
assertThat(response.statusCode()).isEqualTo(401);
assertThat(response.body()).contains("Invalid cluster token");
} finally {
server.setHA(ha);
}
}

/**
* The snapshot route authenticates peers on its own rather than through the shared HTTP gate, and read the token the
* same way: a follower asking a just-elected leader for a snapshot in the same window was refused 401.
*/
@Test
@Timeout(120)
void aPeerSnapshotRequestIsAuthenticatedBeforeTheHAPluginRegistersItselfOnTheServer() throws Exception {
final ArcadeDBServer server = getServer(0);
final String clusterToken = getRaftPlugin(0).getRaftHAServer().getClusterToken();
final HAServerPlugin ha = server.getHA();
try {
server.setHA(null);

final HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://127.0.0.1:" + server.getHttpServer().getPort() + "/api/v1/ha/snapshot/" + getDatabaseName()))
.timeout(Duration.ofSeconds(60))
.header("X-ArcadeDB-Cluster-Token", clusterToken)
.GET()
.build();
final HttpResponse<Void> response = HTTP.send(request, HttpResponse.BodyHandlers.discarding());
assertThat(response.statusCode())
.as("a peer's snapshot request carrying the right cluster token must be authenticated and served")
.isEqualTo(200);
} finally {
server.setHA(ha);
}
}

/** The shape {@code RaftReplicatedDatabase.forwardCommandToLeaderViaRaft} sends: the token and a forwarded user. */
private HttpResponse<String> forwardedCommand(final int serverIndex, final String clusterToken) throws Exception {
final int port = getServer(serverIndex).getHttpServer().getPort();
final HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://127.0.0.1:" + port + "/api/v1/command/" + getDatabaseName()))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", "application/json")
.header("X-ArcadeDB-Cluster-Token", clusterToken)
.header("X-ArcadeDB-Forwarded-User", "root")
.POST(HttpRequest.BodyPublishers.ofString("{\"language\":\"sql\",\"command\":\"SELECT 1\"}", StandardCharsets.UTF_8))
.build();
return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com)
* SPDX-License-Identifier: Apache-2.0
*/
package com.arcadedb.server.ha.raft;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Issue #9554: {@code ArcadeDBServer.stopInternal()} stops the HA plugin before the HTTP listener, and
* {@code RaftHAPlugin.stopService()} dropped its Raft server - the only place it read the cluster token from. For the
* rest of the shutdown every peer's forward that still reached the node, the node it believed to be the leader, was
* answered 401 "Invalid cluster token" rather than the retryable refusal a node that no longer leads gives.
*/
class Issue9554ClusterTokenRetainedAfterStopTest {

@Test
void theClusterTokenOutlivesThePluginsRaftServer() {
final RaftHAPlugin plugin = new RaftHAPlugin();
plugin.setRaftHAServer(FakeRaftHAServer.detached().clusterToken("issue9554-token"));
assertThat(plugin.getClusterToken()).isEqualTo("issue9554-token");

plugin.stopService();

assertThat(plugin.getRaftHAServer()).as("the Raft server is gone once the plugin stops").isNull();
assertThat(plugin.getClusterToken())
.as("the token peers authenticate with does not change when this node stops, so neither may the answer")
.isEqualTo("issue9554-token");

// stopService() runs twice on every HA shutdown (issue #5890): the second call must not lose it either.
plugin.stopService();
assertThat(plugin.getClusterToken()).isEqualTo("issue9554-token");
}

@Test
void aPluginThatNeverStartedHasNoToken() {
assertThat(new RaftHAPlugin().getClusterToken()).isNull();
}
}
25 changes: 24 additions & 1 deletion server/src/main/java/com/arcadedb/server/HAServerPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -436,18 +436,41 @@ default String getClusterToken() {
* receiver checked the derived token, so on a default-configured cluster the forward carried no usable
* credentials at all.
*
* <p>
* The plugin is looked up among the server's registered plugins as well when {@link ArcadeDBServer#getHA()} names
* none yet (issue #9554). An HA plugin registers itself there only at the end of its start, but the HTTP listener is
* up before it begins, and the replication layer it starts can be elected leader - so its peers forward to it - well
* before it returns. Falling back to the raw setting in that window answered every correct forward
* 401 "Invalid cluster token" on a cluster whose token is derived.
*
* @return the effective token, or null/blank when this server has none
*/
static String effectiveClusterToken(final ArcadeDBServer server) {
if (server == null)
return null;
final HAServerPlugin ha = server.getHA();
HAServerPlugin ha = server.getHA();
if (ha == null)
ha = registeredHAPlugin(server);
final String fromPlugin = ha != null ? ha.getClusterToken() : null;
if (fromPlugin != null && !fromPlugin.isBlank())
return fromPlugin;
return server.getConfiguration().getValueAsString(GlobalConfiguration.HA_CLUSTER_TOKEN);
}

/**
* The HA plugin registered with {@code server}'s plugin manager, whether or not it has registered itself as the
* server's HA implementation yet, or null when there is none.
* <p>
* A plugin found here may not have derived its token yet - discovered but not started - and then answers null:
* the caller falls back to the raw setting, which is what it read before this lookup existed. That is intended.
*/
private static HAServerPlugin registeredHAPlugin(final ArcadeDBServer server) {
for (final ServerPlugin plugin : server.getPlugins())
if (plugin instanceof final HAServerPlugin ha)
return ha;
return null;
}

/**
* Returns the HTTP address (host:port) of the current leader, or null if unknown.
*/
Expand Down