Skip to content

fix(distributed): authenticate cluster transports and correlate stage replies - #2650

Merged
inureyes merged 6 commits into
mainfrom
fix/issue-2637-cluster-transport-auth
Oct 26, 2026
Merged

inureyes merged 6 commits into
mainfrom
fix/issue-2637-cluster-transport-auth

Conversation

@inureyes

@inureyes inureyes commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

src/distributed had no authentication layer: any network peer could inject pipeline_stage_response frames that became real model output, drive or shut down a remote stage (and crash its service thread with one malformed frame), and spoof UDP discovery beacons into the generated cluster TOML. This PR adds one pre-shared per-cluster secret and uses it at three layers, in the real code flow (transport core, pipeline runtime, remote stage service, discovery, server startup and CLI).

Design as implemented

  • Secret (D1, D2). src/distributed/cluster_auth.rs: ClusterSecret (>= 16 bytes after trimming one trailing newline, redacted Debug, scrubbed on drop, unix permission warning), ClusterSecretSources with precedence --cluster-secret-file > MLXCEL_CLUSTER_SECRET_FILE > MLXCEL_CLUSTER_SECRET > [cluster] secret_file in the TOML (relative to the TOML's directory; setting both env vars is an error), and ClusterAuth (HMAC-SHA256 via ring, already compiled into every build through rustls, plus CSPRNG nonces). Fail closed: --pp-auto, --pp-peer, and any --distributed-config with pipeline_parallel_size >= 2 refuse to start without a secret, naming every source. RemotePipelineRuntimeConfig.auth and RemoteStageServiceConfig.auth are non-optional, so no pipeline role can be constructed unauthenticated. Single-node serving and the disaggregated roles do not read it.
  • Handshake (D3). src/distributed/cluster_handshake.rs: mutual challenge-response (MLXCAUTH magic, version, 32-byte nonces, length-prefixed listener identity, domain-separated HMAC(K, "mlxcel-cluster-auth-v1/{server,client}", transcript), constant-time verify, 1-byte verdict, 5 s timeout). Accept side runs it in the per-connection task before handle_connection; connect side runs it in ConnectionPool::connect_with_retry, so pooled connections authenticate once at connect. No frame from an unauthenticated connection reaches recv(), the RPC handler, or rpc_pending. On the accept side the client's advertised identity is bound to the TCP source IP (0.0.0.0 is replaced, a concrete mismatch is rejected) and becomes the from of every frame. The connecting side does not bind the server's advertised identity to the socket IP (the server MAC already authenticates it), so NAT or port-forwarded stages keep working. A handshake rejection is a typed HandshakeRejected error, so Transport::connect fails instead of warning and the coordinator exits at startup on a secret mismatch. Thunderbolt and RDMA wrappers and bind_transport carry the auth to the TCP core. Without auth the transport behaves exactly as before.
  • Correlation (D4). RemoteStageRequest carries a fresh random nonce; every RemoteStageResponse variant echoes it (the entry stage stores it in PendingEntryReply for the reverse path). exchange accepts a frame only from the stage it addressed (PeerMatcher, hostname-aware), with the matching nonce, and for RunResult the matching request_id and micro_batch_id; the timeout is an absolute deadline; rejected frames are logged (first three at warn). forward_sequence validates logits as [1, seq_len or 1, vocab_size], with vocab_size read from config.json (read_vocab_size) in PipelineServerModel::load_remote and startup.
  • Remote stage service (D5). Commands only from the configured coordinator_peer (new field, resolved from the cluster TOML's non-stage node), forward activations only from upstream, reverse only from downstream; replies go to the authenticated source, never to reply_addr. Malformed JSON, bad tensors, and unmatched reverse activations are per-frame warnings; only a closed transport channel ends the loop. The executor is injectable (spawn_with_executor) so the control plane is unit-tested without weights. The dormant install_stage_control_service RPC plane and its StageLifecycleRequest/Response types are deleted (test-only callers).
  • Discovery (D6). src/distributed/discovery_beacon.rs: beacons carry timestamp_ms, nonce, and a hex HMAC over a canonical length-prefixed encoding; broadcast_beacon_loop re-signs per tick; discover_peers (mdns) requires the auth and rejects bad MACs, timestamps outside 60 s, replayed nonces, version mismatches (the doc comment now says the check is enforced), and advertised IPs that differ from the datagram source (unspecified is substituted). Static mode unchanged. --pp-auto records secret_file in the generated TOML as an absolute path when the secret came from a file, so peers loading the TOML from another directory resolve the same file. The beacon MAC decoder accepts exactly 64 ASCII hex characters and works on bytes, so a hostile datagram cannot panic discovery before the MAC check.

Listener inventory (D7)

Covered by the handshake: pipeline coordinator control transport, remote stage service transport, Thunderbolt and RDMA wrappers (same TCP core). Out of scope with reasons: disaggregated prefill/decode (disaggregated/coordinator.rs) and the router front (router_front.rs) are a separate opt-in feature with its own role matrix and no secret plumbing today; they keep the documented trusted-segment model and docs now say so explicitly (follow-up: wire the same secret opt-in). discovery.rs and the router health probe only connect. Heartbeat and KV-cache transfer use whatever transport they are handed. bench_activation.rs is a benchmark harness.

Tests (each fails on the pre-fix code)

Baseline for every test below: cargo test --profile test-fast --features cuda -p mlxcel --lib -- --test-threads=1 distributed:: (1375 tests, 0 failed on the final head). Revert cycles were driven by a script that toggled one fix off, rebuilt, ran the test by exact name, restored the fix, rebuilt and reran; each reverted test result was FAILED (exit 101) and the restored rerun of all five was ok. 5 passed (exit 0). Reverts used, with the test that failed:

  • Finding 1, response injection: ExchangeMatch::reject_reason made to return None (no source, nonce, or request check). runtime::correlation_tests::exchange_drops_run_result_from_non_stage_source FAILED (forged logits from the attacker node became the forward output). Siblings run on the fixed code only: exchange_drops_run_result_with_wrong_nonce, exchange_drops_run_result_with_wrong_request_id, forward_rejects_logits_with_wrong_vocab_dimension, exchange_timeout_is_absolute_under_frame_flood, probe_drops_forged_state_from_non_stage_source, validate_logits_shape_accepts_model_output_and_rejects_everything_else, and runtime::tests::remote_runtime_refuses_to_start_against_stage_with_other_secret.
  • Finding 2, unauthenticated control frame: accept-side handshake skipped in tcp_transport.rs and the coordinator source check skipped in remote_service.rs. remote_service::tests::unauthenticated_control_frame_is_rejected_before_dispatch FAILED (a raw-socket Shutdown stopped the stage; the authenticated probe timed out). Siblings: commands_from_authenticated_non_coordinator_have_no_effect (CancelRequest, BeginDrain, RunEntry, Shutdown from a rogue authenticated peer: no effect, no reply, executor never called), replies_go_to_authenticated_source_not_reply_addr, activation_from_non_neighbour_is_ignored, run_entry_with_bad_tensor_answers_error_and_keeps_serving; transport-level tcp_transport::tests::cluster_auth::* (authenticated identity as from, raw connection never reaches recv, wrong secret rejected in both directions, plain client vs authenticated server and vice versa, default config unchanged); cluster_handshake::tests::*.
  • Finding 2, malformed JSON survives: the run loop's per-frame Err arm made to return Err(err) again. remote_service::tests::malformed_json_frame_does_not_end_service FAILED (service thread ended; the next ProbeState timed out).
  • Finding 3, spoofed beacon: MAC verification skipped in discovery_beacon.rs. cluster_init::tests::discover_peers_rejects_spoofed_beacon_without_valid_mac (UDP, default mlxcel-cluster name, no MAC and a MAC under another secret) and discovery_beacon::tests::verifier_rejects_spoofed_beacon_without_mac both FAILED. Siblings: discover_peers_accepts_beacon_signed_with_the_shared_secret (secret B resolves under B, A-signed and wrong-source beacons dropped), discover_peers_mdns_requires_cluster_secret, broadcast_beacon_loop_resigns_each_tick_and_resolves_against_coordinator, verifier tests for tampering, stale and future timestamps, replayed nonce, source-IP mismatch and substitution, version and cluster-name mismatch, JSON-layout independence.
  • Shared: startup_tests::pipeline_cluster_auth_fails_closed_without_a_secret (error names --cluster-secret-file, MLXCEL_CLUSTER_SECRET_FILE, MLXCEL_CLUSTER_SECRET, secret_file; a non-pipeline topology needs no secret), remote_pipeline_topology_without_auth_is_an_internal_error, remote_stage_service_config_names_the_coordinator_peer, cluster_auth::tests::* (precedence, both-env-vars error, minimum length, redaction), render_deterministic_toml_includes_secret_file_when_set, peer_identity tests, loading::tests::read_vocab_size_reads_top_level_then_text_config. make verify-env-var-docs passes.

Lint: cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings exit 0; cargo fmt --check clean.

Real-model and loopback verification

  • tests/pipeline_remote_real_models.rs::pipeline_remote_runtime_qwen3_real_model_parity_and_cleanup (qwen3-0.6b-4bit, two authenticated remote stages, under gpu-lock): ok. 1 passed (exit 0).
  • tests/pipeline_server_remote_real_models.rs::pipeline_server_remote_coordinator_qwen3_matches_dense_baseline: ok. 1 passed (exit 0), so the vocab-size logits check accepts real model output.
  • Loopback E2E with the target/test-fast binaries (--distributed-config, coordinator 127.0.0.1:19370, stages 19371 and 19372, HTTP 19380-19382): with the shared secret_file, /v1/chat/completions returned HTTP 200 with a generated completion. With stage-1 started with --cluster-secret-file pointing at a different secret: stage-0 logged Cluster handshake with peer 127.0.0.1:19372 failed: server failed the cluster handshake: its authenticator does not verify under the configured cluster secret (secret mismatch), stage-1 logged Rejecting connection from 127.0.0.1: cluster handshake failed: connection closed before the client authenticator arrived, and the coordinator logged Cluster handshake with peer 127.0.0.1:19372 failed: ... (secret mismatch) then Failed to load model: cluster authentication with peer 127.0.0.1:19372 failed; no completion was served (HTTP 501 from the no-model path, the server's existing load-failure behavior). With no secret from any source the coordinator exited 1 with distributed pipeline roles (pipeline_parallel_size = 2) require a cluster secret ... pass --cluster-secret-file <PATH>, set MLXCEL_CLUSTER_SECRET_FILE=<PATH> or MLXCEL_CLUSTER_SECRET=<VALUE>, or add secret_file .... A rerun after the two robustness changes: phase 1 again HTTP 200 with no handshake warnings from liveness probes; in phase 2 the wrong-secret stage-1 now exits at startup with Error: cluster authentication with peer 127.0.0.1:19371 failed: cluster handshake with 127.0.0.1:19371 failed: server failed the cluster handshake: its authenticator does not verify under the configured cluster secret (secret mismatch) (mutual: it detected its correct-secret upstream's rejection), stage-0 logged Rejecting connection from 127.0.0.1: cluster handshake failed: connection closed before the client authenticator arrived, and the coordinator could not reach the exited stage (HTTP 503, worker exited); phase 3 unchanged (exit 1, fail closed).
  • No benchmarks or throughput measurements were taken.

Residual risk

Documented in docs/distributed.md and the transport's Security Notes:

  • The handshake authenticates connections; it does not encrypt or MAC each frame. An on-path attacker who can hijack an established TCP stream is out of scope (TLS or a per-frame MAC is the follow-up).
  • Unauthenticated sockets share the 512-connection cap while their handshake is pending, bounded by the 5 s handshake timeout; a per-IP limit is a follow-up. Failed inbound handshakes log at warn for the first 5 per minute and at debug afterwards, so they cannot flood the log.
  • MLXCEL_CLUSTER_SECRET stays in the process environment and is inherited by child processes; the file sources are preferred.
  • Disaggregated serving keeps the trusted-segment model (see the inventory).

Deviations from the brief

  • D5 says to bind reply_addr to the authenticated source "or the configured coordinator": replies always go to the authenticated source, and reply_addr is kept in the envelope only for compatibility (a mismatch is logged at debug). The source is the coordinator by construction since only the coordinator's commands are accepted.
  • D4's vocab size is threaded as RemotePipelineRuntimeConfig.vocab_size: Option<usize>, filled from config.json in both startup.rs and PipelineServerModel::load_remote; a checkpoint without vocab_size still gets the rank, batch, and sequence-length checks.
  • D6's version check is enforced strictly (same CARGO_PKG_VERSION), and the doc comment now says so, because the stage wire protocol is unversioned JSON and a mixed-version cluster has no defined behavior.
  • PeerMatcher treats a configured 0.0.0.0:<port> as matching any authenticated identity with that port (--pp-auto emits it when the HTTP host is 0.0.0.0); the handshake has already bound the identity to the real source IP.
  • Two robustness changes found by the E2E run, not in the brief: a connect-and-close liveness probe is logged at debug rather than as a rejected handshake, and serve_remote_pipeline_stage now exits when the service thread dies (for example when a neighbour rejects the handshake) instead of parking on ctrl_c as a zombie.
  • The disaggregated roles were not wired (allowed by D7); documented as a follow-up.

Changes during review

  • Security review (9e78bf71): HIGH, the beacon mac hex decoder sliced a &str at byte offsets, so one spoofed datagram with a non-ASCII character panicked --pp-auto discovery before the MAC check; it now decodes bytes and requires exactly 64 ASCII hex characters (verifier_rejects_non_ascii_mac_without_panicking, which panics with the old decoder). MEDIUM, ClusterSecretSources derived Debug while holding the raw MLXCEL_CLUSTER_SECRET; it now redacts it (secret_debug_is_redacted extended).
  • Implementation review follow-ups (4b6bd035): --pp-auto records the secret path as absolute (pp_auto_records_secret_file_as_absolute_path_peers_resolve); the client-side identity-to-IP binding was removed (client_accepts_server_advertising_a_forwarded_address); read_vocab_size applies sanitize_config_json (read_vocab_size_tolerates_non_standard_json_tokens); the --pp-auto fail-closed branch moved into resolve_pp_auto_cluster_auth and is tested before any discovery or TOML write (pp_auto_bring_up_fails_closed_before_discovery_or_toml_write, pp_auto_secret_resolution_fails_closed_naming_every_source). Each new test failed against the old production code and passed after restoring it.
  • Finalization (bbb11737): rate-limited failed-handshake warnings and the residual-risk list in docs/distributed.md.
  • After these changes the two qwen3 real-model tests and the three-phase loopback E2E were rerun under gpu-lock with the rebuilt binary: exit 0 for both tests; E2E phase 1 HTTP 200, phase 2 rejected with secret mismatch, phase 3 exit 1 with the fail-closed message.

Closes #2637

@inureyes inureyes added status:review Under review type:security Security vulnerability or fix priority:high High priority labels Oct 26, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Authenticate the src/distributed pipeline transports with a pre-shared cluster secret (mutual connect-time HMAC handshake), correlate stage replies in the coordinator, restrict the remote stage control plane to the coordinator and neighbours, and authenticate UDP discovery beacons, failing closed for every pipeline role.

Findings Addressed

No CRITICAL or HIGH findings. The handshake runs in the accept task before handle_connection and inside ConnectionPool::connect_with_retry, which is the only outbound connect path, so pooled and reconnected streams are always authenticated and no frame (Control, TensorData, RpcRequest, RpcResponse) reaches recv(), the RPC handler, or rpc_pending without it. exchange drops frames by source, nonce, and request/micro-batch against an absolute deadline. Every production RemotePipelineRuntimeConfig, RemoteStageServiceConfig, and discover_peers call site carries the auth; disaggregated and single-node transports keep auth: None.

Remaining Items

  • --pp-auto records secret_file verbatim in the generated TOML, but ClusterConfig::from_file resolves a relative path against the TOML directory (default ./.mlxcel/). --cluster-secret-file cluster.secret is therefore recorded as cluster.secret and a peer loading that TOML looks for .mlxcel/cluster.secret (src/server/startup.rs:2699). Fails closed, but contradicts the docs; recording std::path::absolute(path) fixes it. (MEDIUM)
  • client_handshake binds the server's advertised identity to the socket peer IP after the server already accepted (src/distributed/cluster_handshake.rs:232), and the pool discards the result (src/distributed/connection_pool.rs:190). The check has no consumer and breaks NAT or port-forwarded stages whose listener is bound to a concrete inner IP. (LOW)
  • pipeline_coordinator_address picks the first non-pipeline node (src/server/startup.rs:2492); with several non-pipeline nodes the stage silently drops the real coordinator's commands unless it is listed first. (LOW)
  • read_vocab_size parses config.json without sanitize_config_json (src/loading/mod.rs:500), so a config with non-standard JSON tokens silently skips the vocab check. (LOW)
  • The --pp-auto fail-closed branch in run_zero_config_bring_up has no automated test; it is covered by the loopback E2E only. (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

Re-run at b5b43ffc: cargo test --profile test-fast --features cuda -p mlxcel --lib distributed:: -- --test-threads=1 under gpu-lock (1373 passed, exit 0), the five startup/loading/cluster_init tests by name (exit 0), cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings (exit 0), cargo fmt --check (exit 0), make verify-env-var-docs (exit 0).

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the cluster auth changes. Two commits pushed: 9e78bf7 and 4b6bd03.

Fixed:

  • HIGH: the beacon mac hex decoder sliced the unauthenticated string as str, so a non-ASCII character at an odd offset panicked discover_peers before any MAC check. One spoofed datagram with the default cluster name and the build version ended --pp-auto discovery. It now decodes bytes and accepts only a 64-character ASCII hex tag.
  • MEDIUM: ClusterSecretSources derived Debug while holding the raw MLXCEL_CLUSTER_SECRET value. It is now redacted.
  • MEDIUM: --pp-auto now writes an absolute secret_file into the generated TOML, because from_file resolves relative paths against the TOML directory.
  • LOW: the connect side no longer binds the server identity to the socket IP. The server MAC already gives mutual authentication, and the binding broke NAT and port-forwarded stages.
  • LOW: read_vocab_size now sanitizes Infinity/NaN, and the --pp-auto fail-closed branch has a direct test through run_zero_config_bring_up.

Every new test fails when its fix is reverted and passes once it is restored.

Not fixed (no regression from main):

  • MEDIUM: unauthenticated sockets share the 512-slot accept budget and can hold slots for the 5 s handshake window. Before this PR they could hold slots indefinitely. A per-IP pre-auth limit would be a follow-up.
  • LOW: each failed inbound handshake logs one warning with no rate limit.

Verification: clippy lib+tests, fmt, distributed:: lib tests (1375 passed), the named startup and loading tests, both Qwen3 real-model remote tests, and the loopback E2E script (correct secret serves HTTP 200, wrong secret is rejected, no secret fails closed). The hot path is unchanged: no per-frame MAC, one 8-byte CSPRNG read per exchange, and the handshake runs only when the pool opens a new connection.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 26, 2026
… replies

`src/distributed` had no authentication layer: any network peer could inject `pipeline_stage_response` frames that became live model output, drive or shut down a remote stage (and end its service thread with one malformed frame), and spoof UDP discovery beacons into the generated cluster TOML. One pre-shared per-cluster secret now backs three layers, wired into the real code flow rather than a standalone module.

- `cluster_auth`: `ClusterSecret` (>= 16 bytes, redacted, scrubbed on drop), `ClusterSecretSources` with precedence `--cluster-secret-file` > `MLXCEL_CLUSTER_SECRET_FILE` > `MLXCEL_CLUSTER_SECRET` > TOML `[cluster] secret_file`, and `ClusterAuth` (HMAC-SHA256 via the already-compiled `ring`). Every pipeline role fails closed without a secret; single-node serving and the disaggregated roles are unchanged.
- `cluster_handshake`: mutual nonce challenge-response run on the accept side before `handle_connection` and on the connect side inside the pool, with the advertised listener identity bound to the TCP source IP and reported as `from`. Rejection is a typed error, so `Transport::connect` fails and a secret mismatch surfaces at startup. Thunderbolt, RDMA, and `bind_transport` carry the auth to the TCP core.
- Runtime: per-exchange nonce echoed by every response variant, replies accepted only from the addressed stage with matching nonce, request id, and micro-batch, absolute exchange deadline, and logits validated as `[1, seq_len, vocab_size]`.
- Remote stage service: commands only from the configured coordinator, activations only from the adjacent stage, replies to the authenticated source, per-frame errors logged instead of ending the loop; the dormant `install_stage_control_service` RPC plane is deleted.
- Discovery: beacons carry timestamp, nonce, and HMAC over a canonical encoding; the receiver rejects bad MACs, stale or replayed beacons, version mismatches (now enforced), and source-IP mismatches.
- CLI flag on both binaries, env vars documented in `docs/environment-variables.md`, operator guide in `docs/distributed.md`, example TOMLs and the rollout script reference a `secret_file`, harnesses generate a random secret per run.

Validated with the new adversarial unit tests (forged source, wrong nonce, wrong request id, wrong shape, frame flood, unauthenticated control frame, malformed JSON, rogue authenticated peer, spoofed and replayed beacons), the distributed lib suite, clippy, the qwen3-0.6b remote-runtime and server-coordinator real-model parity tests, and a loopback coordinator plus two-stage run with a correct secret and a stage started with a wrong secret.

Closes #2637
The discovery beacon's hex `mac` field is unauthenticated, and the decoder sliced it as a `str` two bytes at a time. A multi-byte character at an odd offset split a UTF-8 boundary and panicked, so one spoofed datagram carrying the public default cluster name and the build version ended a `--pp-auto` coordinator's discovery before any MAC was checked. The decoder now works on bytes and rejects anything that is not exactly one HMAC-SHA256 tag of ASCII hex.

`ClusterSecretSources` derived `Debug` while holding the raw `MLXCEL_CLUSTER_SECRET` value; it now redacts that field like `ClusterSecret` and `ClusterAuth` do.

Both regression tests fail on the previous code (the beacon test panics with "end byte index 2 is not a char boundary") and pass now.

Refs #2637
`--pp-auto` wrote `[cluster] secret_file` into the generated TOML exactly as typed, relative to the working directory, while `ClusterConfig::from_file` resolves a relative `secret_file` against the TOML's own directory (default `./.mlxcel/`). Every reader of the TOML looked for the secret in the wrong place. The coordinator now records the absolute path it read.

The connect side of the cluster handshake no longer binds the server's advertised identity to the socket peer IP. The server's authenticator already gives mutual authentication, the pool discarded the bound value, and the check refused stages reached through NAT or a port forward after the server had accepted. The accept side still binds the client identity, which is what frames are attributed to.

`read_vocab_size` now sanitizes `Infinity`/`NaN` like the other config.json readers, so such configs keep the coordinator's logits vocab check. The `--pp-auto` fail-closed path is extracted into `resolve_pp_auto_cluster_auth` and tested through `run_zero_config_bring_up`, which must fail without a secret before discovery or any TOML write.

The secret-path, NAT, and vocab tests fail on the previous code and pass now.

Refs #2637
An unauthenticated peer could make the accept loop emit one warn line per failed inbound handshake. The first five per minute now log at warn and the rest at debug.

docs/distributed.md now states the final behavior: the pp-auto secret path is recorded as an absolute path, and the residual risks are listed (no per-frame encryption or MAC, unauthenticated handshake slots bounded by the 5 s timeout and the 512-connection cap, MLXCEL_CLUSTER_SECRET inherited by child processes, disaggregated serving out of scope).

Validation:
- cargo fmt --check, make verify-env-var-docs, cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings: exit 0
- distributed:: lib tests under gpu-lock, --test-threads=1: 1375 passed, 0 failed

Refs #2637
Bilingual report on the cluster secret, the mutual connect-time handshake, stage reply correlation, remote stage authorization, the discovery beacon MAC, the operator-facing breaking change, residual risks, and the revert, real-model and loopback evidence.

Refs #2637
@inureyes
inureyes force-pushed the fix/issue-2637-cluster-transport-auth branch from bbb1173 to 39ad716 Compare October 26, 2026 18:36
Record the orchestrator re-verification on the rebased head (clippy, 1937 lib tests, distributed_integration, zero_config_cluster_init, pipeline_e2e, fmt and env-var docs gates) in both report languages.

Refs #2637
@inureyes
inureyes marked this pull request as ready for review October 26, 2026 18:38
@inureyes
inureyes merged commit b6be7e1 into main Oct 26, 2026
29 checks passed
@inureyes
inureyes deleted the fix/issue-2637-cluster-transport-auth branch October 26, 2026 18:38
inureyes added a commit that referenced this pull request Oct 27, 2026
Three hardening residuals of the #2650 cluster handshake, all in the TCP transport and the startup paths that build it.

Pre-auth slots (item a): an authenticated listener no longer lets sockets that have not finished the handshake hold `max_connections` permits. They draw from a separate pending pool (`TcpTransportConfig::max_pending_handshakes`, default 64, and `max_pending_handshakes_per_ip`, default 8, keyed by the canonical source IP) for the handshake only; a socket beyond either bound is closed at accept with a rate-limited warning, and the main permit is taken only after `Ok(identity)`. The limiter is `distributed::pending_handshakes::PendingHandshakeLimiter`, pub(crate) so another authenticated listener can reuse it. Without `auth` the accept path is unchanged.

Typed rejections (item b): the server answers an identity it cannot bind with a 9-byte rejection record (`MLXCREJ\0` + `0x01`) instead of silently closing, still sending no nonce or authenticator, and `read_hello` turns it into a `HandshakeRejected` on the client naming the advertised identity and the NAT or advertised-address cause, so `Transport::connect` fails within 1 s instead of warning after a 5 s timeout. The server side gets typed `IdentityNotOwned` and `ClientAbortedAfterServerProof` (EOF after the server proof, reported as a probable secret mismatch), and the altered-transcript verdict message says so. `PROTOCOL_VERSION` is 2; the handshake entry points and their error types are re-exported from `distributed` for other TCP channels.

Disaggregated roles (item d, breaking): `--node-role prefill`, `decode` and `router` resolve the cluster secret through the same sources as the pipeline roles (`resolve_disaggregated_cluster_auth`, before any probe, bind or weight load) and refuse to start without one; `Hybrid` reads nothing. The secret flows through `ServerConfig::cluster_auth` and `WorkerSchedulerConfig::cluster_auth` into the worker's role transport (`disaggregated_role_transport_config`) and the router's transport, on both `mlxcel-server` and `mlxcel serve`. A raw client that skips the handshake never gets a frame to a role loop; the decode loop's intake is now `next_decode_meta`, which the test drives without a scheduler.

Docs, both CLIs' `--node-role` and `--cluster-secret-file` help, and the disaggregated e2e harnesses (fresh per-test secret file via `tests/common::TestClusterSecretFile`) follow. Verified with the `distributed::` and `server::startup::` lib suites, clippy, fmt, env-var docs, a loopback 3-node run with a shared, a wrong and a missing secret, and the qwen3 remote-pipeline real-model parity tests on GB10.

Closes #2655
inureyes added a commit that referenced this pull request Oct 27, 2026
…2674)

## Summary

Three hardening residuals of the #2650 cluster handshake, in one PR as the issue asks (items a, b, d; item c moved to #2658).

- **Item a, pre-auth slots.** With `auth` set, a socket that has not finished the handshake no longer holds a `max_connections` permit. It takes a slot from a separate pending pool (`TcpTransportConfig::max_pending_handshakes`, default 64; `max_pending_handshakes_per_ip`, default 8, keyed by the canonical source IP so IPv4-mapped IPv6 counts as IPv4) for the handshake only; a socket beyond either bound is closed at accept with a rate-limited warning, and the main permit is taken only after `Ok(identity)`. The limiter is `distributed::pending_handshakes::PendingHandshakeLimiter` (pub(crate), reusable by #2658's listener). With `auth` set, `TcpTransport::bind` refuses a zero bound for either field before binding the listener (0 would refuse every authenticated connection). Without `auth` the accept path is byte for byte the old one and the two fields are unused.
- **Item b, typed rejections.** `PROTOCOL_VERSION` is 2. On identity-binding failure the server writes `REJECT_MAGIC` (`MLXCREJ\0`) plus `REJECT_IDENTITY_NOT_OWNED` (`0x01`), flushes and closes, and still sends no nonce or authenticator. The record is 9 constant bytes and never carries the observed source IP. An advertised identity that does not parse as a socket address (no mlxcel client sends one) is a protocol error: the connection closes without a reject record, and the identity is logged with `{:?}` escaping so peer input cannot forge log lines. `read_hello` reads the first 8 bytes first; in the client role the record becomes `HandshakeRejected("server refused this node's advertised identity <id>: the advertised IP must be the address the server sees this connection come from (check the bind or advertised address and any NAT or port forward between the nodes)")`, so `Transport::connect` fails within 1 s instead of warning after the 5 s timeout. Server side: typed `IdentityNotOwned { advertised, source_ip }` and `ClientAbortedAfterServerProof` ("client closed the connection after receiving this server's authenticator; it most likely holds a different cluster secret"), which covers an orderly close as well as a reset, abort or broken pipe after the server proof; the altered-transcript verdict message now says so. `server_handshake` writes the record itself, so any caller gets the behavior. `client_handshake`, `server_handshake`, `HANDSHAKE_TIMEOUT` and the four error types are re-exported from `mlxcel::distributed` for #2658's coordinator-to-peer channel.
- **Item d, cluster auth for the disaggregated roles.** `resolve_disaggregated_cluster_auth(sources, mode)` next to `resolve_pipeline_cluster_auth`: `Hybrid` returns `None` without reading any source; `PrefillOnly`, `DecodeOnly` and `Router` require a secret and otherwise fail naming the role and `CLUSTER_SECRET_SOURCES_HELP`. It runs in `start_server` before the peer probe, any listener bind and the weight load, with `ClusterSecretSources::from_env(--cluster-secret-file, [cluster] secret_file)`. The auth flows through `ServerConfig::cluster_auth` and `WorkerSchedulerConfig::cluster_auth` into the worker's role transport (`disaggregated_role_transport_config`) and the router's transport, on both `mlxcel-server` and `mlxcel serve`. The decode loop's intake is factored into `ServingCoordinator::next_decode_meta` so the unauthenticated-frame test runs without a scheduler. The router health monitor's connect-and-close probe stays at debug.

Docs (`docs/distributed.md`, `docs/environment-variables.md`, `docs/CONTINUOUS_BATCHING.md`), both CLIs' `--node-role` and `--cluster-secret-file` help, the `router_front.rs` trust comment and the tcp_transport Security Notes are updated. `tests/disaggregated_router_e2e.rs` and `tests/disaggregated_serving_e2e.rs` give every spawned role a fresh per-test secret file (`tests/common::TestClusterSecretFile`); the serving e2e's in-test client transport carries the same auth. No `scripts/` or `.github/workflows/` file launches a disaggregated role (re-checked).

## Breaking change

`--node-role prefill`, `--node-role decode` and `--node-role router` now refuse to start without a cluster secret, as the pipeline roles have since #2650. A deployment that launched these roles without one exits at startup with `the disaggregated <role> role (--node-role <role>) requires a cluster secret ... pass --cluster-secret-file <PATH>, set MLXCEL_CLUSTER_SECRET_FILE=<PATH> or MLXCEL_CLUSTER_SECRET=<VALUE>, or add secret_file under [cluster] in the cluster TOML`. Single-node serving (no `--node-role`, or `hybrid`) is unchanged.

Migration:

1. Generate one secret: `openssl rand -hex 32 > /etc/mlxcel/cluster.secret && chmod 600 /etc/mlxcel/cluster.secret`.
2. Copy the file to every host that runs a prefill, decode or router process (same value everywhere).
3. Add `--cluster-secret-file /etc/mlxcel/cluster.secret` to every `--node-role prefill|decode|router` launch (or set `MLXCEL_CLUSTER_SECRET_FILE`, or `MLXCEL_CLUSTER_SECRET`, or `[cluster] secret_file` in a cluster TOML passed with `--distributed-config`; same precedence as the pipeline roles).
4. Make `--serving-bind` name the IP the peers see this node connect from (not `0.0.0.0` on a multi-homed host): the accepting side binds the advertised identity to the TCP source IP and refuses a mismatch with the new identity rejection.
5. Upgrade all nodes together: the handshake wire version is now 2 and a mixed-version pair fails with an explicit version message.

## Failing-first evidence

Run from the lib test binary built before the implementation (same tests, unfixed code):

```
test distributed::cluster_handshake::tests::client_reports_identity_rejection_as_typed_rejection ... FAILED
  expected HandshakeRejected, got: peer closed the connection without starting the cluster handshake
test distributed::cluster_handshake::tests::server_reports_client_abort_after_proof_as_probable_secret_mismatch ... FAILED
  cluster handshake timed out after 5s
test distributed::tcp_transport::tests::cluster_auth::pending_handshakes_do_not_consume_connection_slots ... FAILED
  called `Result::unwrap()` on an `Err` value: cluster handshake with 127.0.0.1:44591 failed
```

The remaining new tests (`per_ip_pending_limit_closes_excess_sockets`, `pending_slot_is_released_after_handshake`, `identity_rejection_sends_only_the_reject_record`, `startup_tests::disaggregated_roles_fail_closed_without_a_secret`, `coordinator_tests::networked_decode_role_rejects_unauthenticated_frame`) reference new config fields or functions and do not compile against the unfixed code.

## Verification (GB10 spark-102, `--profile test-fast --features cuda`, GPU work under `gpu-lock run --tag issue-2655`)

- `cargo test -p mlxcel --lib distributed:: -- --test-threads=1` on the post-review code (471320c): 1390 passed, 0 failed, 4 ignored. `distributed::cluster_handshake::` repeated 8 times: 15 of 15 passed each time.
- `cargo test -p mlxcel --lib server::startup:: -- --test-threads=1`: 93 passed. The 11 new or updated tests by name (handshake, tcp_transport cluster_auth, coordinator, startup): 11 passed. `server::model_worker` has no in-module unit tests; its change is covered by the startup resolver test and the e2e harness compile.
- `cargo clippy -p mlxcel --lib --tests -- -D warnings` on the final head: clean. `cargo fmt --check`: clean. `make verify-env-var-docs`: OK (15 tests).
- `cargo check -p mlxcel --test disaggregated_router_e2e --test disaggregated_serving_e2e --test pipeline_remote_real_models --test pipeline_server_remote_real_models`: compiles.
- Manual loopback, `target/test-fast/mlxcel-server`, qwen3-0.6b-4bit, 127.0.0.1 ports 19450-19473, `--parallel 2 --max-batch-size 2 --decode-storage-backend paged --no-warmup`:
  - Shared `--cluster-secret-file` on router, prefill, decode: `POST /v1/chat/completions` returned **HTTP 200** (`"usage":{"prompt_tokens":16,"completion_tokens":16,"total_tokens":32}`).
  - Different secret on the decode node: HTTP 500 `decode handoff to 127.0.0.1:19465 failed`; prefill log `Cluster handshake with peer 127.0.0.1:19465 failed: server failed the cluster handshake: its authenticator does not verify under the configured cluster secret (secret mismatch)`; decode log `Rejecting connection from 127.0.0.1: cluster handshake failed: client closed the connection after receiving this server's authenticator; it most likely holds a different cluster secret`.
  - Decode role and router role with no secret: **exit 1**, `Error: the disaggregated decode role (--node-role decode) requires a cluster secret so the router, prefill and decode role transports can authenticate each other, and none was configured: pass --cluster-secret-file <PATH>, set MLXCEL_CLUSTER_SECRET_FILE=<PATH> or MLXCEL_CLUSTER_SECRET=<VALUE>, or add secret_file = "<PATH>" under [cluster] in the cluster TOML (...)` (same for `router`).
  - All spawned servers killed by PID; `pgrep -af mlxcel-server` empty afterwards.
- `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`, built with `--no-run` outside the lock: `pipeline_remote_runtime_qwen3_real_model_parity_and_cleanup` ok (1.34 s), `pipeline_server_remote_coordinator_qwen3_matches_dense_baseline` ok (1.58 s). Re-run on the final head 6e3da1d with `--ignored --exact`: both ok again (1.31 s, 1.63 s).

Not run: the `#[ignore]` disaggregated e2e harnesses themselves (they build release binaries with Metal features in their doc; the harness change is compile-checked and the equivalent three-process flow is the manual loopback run above).

## Changes during review

The security pass (471320c) tightened three edges: zero pending-handshake bounds are refused at bind when auth is set; an unparseable advertised identity closes without a reject record (the record is reserved for the identity-not-owned case) and is logged escaped; a reset, abort or broken pipe after the server proof is classified as `ClientAbortedAfterServerProof` like an orderly close. New tests: `unparseable_identity_closes_without_a_reject_record`, `server_reports_client_reset_after_proof_as_probable_secret_mismatch`, `peer_abort_classifies_eof_reset_and_broken_pipe`, `zero_bounds_are_refused_at_construction`, `cluster_auth::bind_refuses_zero_pending_bounds_with_auth`. The docs commit (6e3da1d) documents these in `docs/distributed.md` and the tcp_transport field docs, and corrects the flood wording: a flood from 8 or more source IPs can delay new connections from any source while the pending pool is full, but cannot take slots from established authenticated connections or inject frames.

Closes #2655
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:high High priority status:done Completed type:security Security vulnerability or fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(distributed): authenticate cluster transports and correlate responses (output injection, stage takeover, discovery spoofing)

1 participant