Skip to content

fix(#9554): accept peers' cluster token while the HA plugin starts and stops - #9566

Merged
robfrank merged 2 commits into
mainfrom
fix/9554-ha-forwarded-commands-401-invalid-cluster-token
Oct 9, 2026
Merged

robfrank merged 2 commits into
mainfrom
fix/9554-ha-forwarded-commands-401-invalid-cluster-token

Conversation

@robfrank

@robfrank robfrank commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #9554

Summary

A peer's forwarded command got HTTP 401 "Invalid cluster token" around leader changes because the receiving node checked the token through server.getHA(). There are two windows where that returns nothing usable:

  • Start. RaftHAPlugin.startService() calls server.setHA(this) only after raft.start() returns. The HTTP listener is already up, and Ratis is already running inside raft.start(), so the node can be elected leader before then. Peers forward to it, and HAServerPlugin.effectiveClusterToken falls back to the raw arcadedb.ha.clusterToken setting. That setting is empty on any cluster whose token is derived, so the peer's correct token was refused.
  • Stop. ArcadeDBServer.stopInternal() stops HA before the HTTP listener. RaftHAPlugin.stopService() nulls raftHAServer, which was the only source of its token. For the rest of the shutdown, a forward from a peer that still saw this node as leader got the same 401 instead of the retryable "not the leader" refusal.

Changes:

  • HAServerPlugin.effectiveClusterToken looks the HA plugin up among the server's registered plugins when getHA() does not name one yet.
  • RaftHAPlugin keeps the token of the Raft server it stopped. The token never changes for the life of the process, and each server start creates a new plugin instance.
  • SnapshotHttpHandler.authenticate had its own copy of the getHA() lookup and the same defect: a follower asking a just-elected leader for a snapshot got 401. It now uses the shared helper.

Bullet 3 of the issue ("a 401 turned into a non-retryable client error"): with the cause above removed, the 401 is left non-retryable on purpose. A 401 "Invalid cluster token" now means the nodes really are configured with different tokens, and retrying cannot fix that. Making it retryable would turn a configuration error into a retry storm.

Test plan

  • Issue9554ClusterTokenRetainedAfterStopTest (unit): the token survives stopService(), called twice as in a real shutdown. Fails without the fix (expected "issue9554-token" but was null).
  • Issue9554ClusterTokenAcrossHALifecycleIT: on a live 2-node cluster, sets setHA(null) to reproduce the startup window, then:
    • a forward with the right token gets 200 (fails without the fix: effective token "");
    • a wrong token is still refused 401 "Invalid cluster token";
    • a snapshot request with the right token is not refused 401 (fails with only the gate fix applied, which is how the snapshot-route fix was confirmed to be needed).
  • Related tests, all green: Issue7516ClusterTokenHopProofTest, Issue7528LeaderProxyRemovedTest, RaftHAPluginExecutorLeakTest, ClusterTokenProviderTest, Issue6125SnapshotRouteValidationTest, Issue7837ShutdownRequestCredentialTest, Issue7516BasicAuthForwardLoopIT, ClusterAuthSessionTokenIT, Issue7603LeaderForwardHopIT, RaftReplicationWriteAgainstReplicaIT.

Coverage

Invariant: a node accepts its peers' cluster token for as long as its HTTP listener is up and it holds an HA plugin, whatever stage that plugin's lifecycle is in.

Entry point that validates an inbound cluster token Status
AbstractServerHttpHandler.isValidClusterToken (every HTTP route, including /api/v1/command forwards and /api/v1/server) fixed here, through effectiveClusterToken
SnapshotHttpHandler.authenticate (/api/v1/ha/snapshot/*) fixed here, now uses the shared helper
PostClusterAuthSessionHandler covered: it relies on the gate above
Senders (LeaderCommandForwarder, SupportPeerQuery) covered: they use the same helper, so they also send the token during the startup window
Sender RaftReplicatedDatabase.forwardCommandToLeaderViaRaft no change needed: it reads RaftHAServer.getClusterToken(), and start() initializes the provider before Ratis starts, so no leader is known before the token is

Found with grep -rn "X-ArcadeDB-Cluster-Token" server/src/main ha-raft/src/main grpcw/src/main and grep -rn "effectiveClusterToken\|getClusterToken()". grpcw, bolt and postgresw do not validate cluster tokens.

Known gaps: None.

Adversarial pass

No subagent tool was available in this run, so I did the pass myself against the diff. No further gap found. I checked:

  • a sender that forwards before its own token exists: not possible, see the coverage table;
  • every inbound validator, listed in the table.

Review cycles

Deferred items

These were skipped as optional:

  • "a one-line comment saying only one HA plugin is expected": isAutoDiscovered registers a single Raft plugin. Adding the comment would cost a review cycle for no behavior change.
  • "consider asserting that getHA() is restored": every test restores it in finally, and the cluster is torn down per class.
  • "an IT that stops HA and then forwards": the stop window is pinned at unit level. An IT that stops HA on a live node leaves the fixture's teardown checks running against a half-stopped node.

Final state: clean-approval

🤖 Generated with Claude Code

…and stops

The HTTP gate and the snapshot route read the cluster token through
server.getHA(), which RaftHAPlugin sets only once raft.start() returns and
whose Raft server it drops when it stops. Ratis can be elected leader inside
raft.start(), and HA stops before the HTTP listener, so in both windows a
peer's correct token was compared against the empty raw setting and the
forward was answered 401 "Invalid cluster token".

- HAServerPlugin.effectiveClusterToken finds the registered HA plugin when
  getHA() does not name one yet
- RaftHAPlugin keeps the token of the Raft server it stopped
- SnapshotHttpHandler uses the shared helper instead of its own lookup

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@robfrank robfrank added this to the 26.11.1 milestone Oct 9, 2026
@robfrank robfrank added bug ha High availability / replication (Raft) labels Oct 9, 2026
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 34 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bcbeecca-97dc-4a50-95a5-e599930849d8

📥 Commits

Reviewing files that changed from the base of the PR and between 169e31e and 903f4b5.


📒 Files selected for processing (5)
  • ha-raft/src/main/java/com/arcadedb/server/ha/raft/RaftHAPlugin.java
  • ha-raft/src/main/java/com/arcadedb/server/ha/raft/SnapshotHttpHandler.java
  • ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9554ClusterTokenAcrossHALifecycleIT.java
  • ha-raft/src/test/java/com/arcadedb/server/ha/raft/Issue9554ClusterTokenRetainedAfterStopTest.java
  • server/src/main/java/com/arcadedb/server/HAServerPlugin.java


  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 4 complexity

Metric Results
Complexity 4

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@claude

claude Bot commented Oct 9, 2026

Copy link
Copy Markdown

Review

The fix is sound and well scoped. The root cause is correctly identified, the snapshot handler now shares the common helper instead of keeping its own copy of the lookup, and the tests reproduce both windows. No blocking issues.

What I checked

  • PluginManager.getPlugins() copies the plugin list under the map monitor, so the new registeredHAPlugin fallback is safe against concurrent registration. There is no CME risk.
  • The fallback only runs when getHA() is null. The extra list allocation and lock therefore stay off the normal request path.
  • Keeping stoppedClusterToken is reasonable. It is volatile, null-guarded, and survives the second stopService() call. The security impact is minor: the node accepts the same token it already accepted while running.
  • The wrong-token test in the same window confirms the gate was not loosened. MessageDigest.isEqual is still used in the snapshot handler.

Minor suggestions (non-blocking)

  1. registeredHAPlugin returns the first HAServerPlugin it finds. That plugin may be discovered but not yet configured, and its getClusterToken() may return null. The code then falls back to the setting, which is the old behaviour, so this is safe. A short comment saying that is intended would help the next reader.
  2. Issue9554ClusterTokenAcrossHALifecycleIT calls server.setHA(null) on a live node while the background HA threads keep running. The try/finally restores it, but any code that reads getHA() in that gap, such as the readiness probe, could see null. This is acceptable for a test, but it could flake on a slow CI run. If it does, add a comment explaining why.
  3. The snapshot test only asserts isNotEqualTo(401). It would be stronger to assert the expected status (likely 200, or a specific non-auth status). Right now a 500 would also pass.
  4. The 401 for a mismatched token stays non-retryable. I agree with that choice and with the reasoning in the PR description.

Conventions

  • The code follows CLAUDE.md: imports are used instead of fully qualified names, final is applied, and tests use the assertThat style.
  • There are no debug System.out calls.
  • Neither new test asserts on wall-clock time.

LGTM, pending CI.

…apshot is served (200)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Oct 9, 2026

Copy link
Copy Markdown

Review

Overall this is a well-scoped, well-explained fix. No blocking issues found.

What looks good

  • effectiveClusterToken now finds the HA plugin through the plugin manager when getHA() is null. PluginManager.getPlugins() copies the list under the map monitor, so calling it from HTTP worker threads is safe.
  • The extra lookup only runs while getHA() is null (start window), so the hot path is unchanged.
  • SnapshotHttpHandler now uses the shared helper instead of its own copy. That removes the duplicate defect and keeps the MessageDigest.isEqual constant-time comparison.
  • stoppedClusterToken is volatile, and getClusterToken() reads raftHAServer once into a local, which avoids a check-then-use race. Keeping the token after stop is safe because it never changes for the process lifetime.
  • Leaving the 401 non-retryable is a reasonable call, and the PR description explains why.
  • Tests cover the three paths (forward accepted, wrong token still 401, snapshot route). The unit test also covers the double stopService() call.

Minor suggestions (non-blocking)

  1. registeredHAPlugin returns the first HAServerPlugin it finds. If several are ever registered, the choice depends on map order. That is fine today, but a one-line comment saying only one HA plugin is expected would help.
  2. In the window where the plugin is found but has not derived its token yet, the code falls back to the raw setting. When that setting is empty, the check is expectedToken.isEmpty(), which rejects. That is the safe direction, so no change is needed.
  3. The IT sets server.setHA(null) on a live node, so background HA threads may briefly see null. The finally restore and the class Javadoc address this. Consider asserting that getHA() is restored, to catch leaks between tests.
  4. The stop-window behaviour (token retained, then a forward gets the 'not the leader' answer) is tested only at unit level. An IT that stops HA and then forwards would pin the end-to-end behaviour, but this is optional.

Style and conventions match CLAUDE.md: imports are used, there are no stray System.out calls, and the tests use the AssertJ style.

🤖 Generated with Claude Code

@robfrank
robfrank merged commit 03faa57 into main Oct 9, 2026
@robfrank
robfrank deleted the fix/9554-ha-forwarded-commands-401-invalid-cluster-token branch October 9, 2026 15:12
robfrank added a commit that referenced this pull request Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug ha High availability / replication (Raft)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

HA: forwarded commands rejected with HTTP 401 'Invalid cluster token' around leader changes

1 participant