Repository navigation
fix(distributed): cap pre-auth slots, type rejections, auth DI roles - #2674
Conversation
Implementation Review SummaryIntent
Findings AddressedNo CRITICAL or HIGH findings; no fixes were needed. Remaining Items
Verification
The failing |
|
Security and performance review of head 0bd014c. No CRITICAL or HIGH findings. Fixed in 471320c:
Verified with no change needed: the pending slot is released on every exit path (RAII, dropped right after Remaining, not fixed (LOW): the per-IP key is a full IPv6 address, so one /64 can rotate past the per-IP limit (the global pool still bounds it). Also, Checks: |
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
Security review follow-ups for the #2655 transport hardening. - The identity rejection record is now sent only for a well-formed identity that names another IP (IdentityNotOwned). An identity that is not a socket address comes from no mlxcel client, so it is a protocol error closed without a reply, and the unauthenticated identity is Debug-escaped in the log message so it cannot forge log lines. The identity-not-owned wire format is unchanged (REJECT_MAGIC plus 0x01). - A client that resets (or aborts, or breaks the pipe) after the server's authenticator is classified as ClientAbortedAfterServerProof, like an orderly close, instead of a generic I/O error. - PendingHandshakeLimiter::new refuses zero bounds, and TcpTransport::bind fails with that error before binding when auth is set, instead of producing a listener that closes every socket at accept. Without auth the bounds stay unused. - docs/distributed.md and the module docs no longer claim a flood cannot affect real peers: a flood from 8 or more source IPs fills the pending pool and delays new connections from any source by up to the handshake timeout per slot; established authenticated connections and frames stay unaffected. New tests cover each change (malformed identity gets no reply, reset after proof, error-kind classifier, zero bounds at limiter and bind). distributed:: and server::startup:: lib tests, clippy -D warnings and fmt pass locally. Refs #2655
The cluster authentication section now states that a reset or abort after the server's authenticator is classified like an orderly close (probable secret mismatch), and that an advertised identity that is not a socket address is closed without a rejection record. The TcpTransportConfig field docs and module Security Notes state that zero pending-handshake bounds are refused at bind when auth is set. Validation: cargo fmt --check, clippy -D warnings (lib and tests), make verify-env-var-docs, and cargo check of the two disaggregated e2e targets all pass. Refs #2655
6e3da1d to
7de51d0
Compare
…2705) ## Summary Five hardening items from the #2674 security review on the authenticated cluster transport (`src/distributed/`) and the disaggregated router demux, in one PR with one verification pass. None changes what a party without the secret can read or inject. 1. **Per-source pending limit keyed per IPv6 /64.** `pending_source_key(ip)` canonicalizes, keeps IPv4 as is and masks IPv6 to its /64; `try_acquire` and `pending_from` use it, `PendingSlotRefusal::PerIp` carries the key and prints `.../64` for IPv6. Module doc, the `max_pending_handshakes_per_ip` field doc and `docs/distributed.md` say that nodes inside one /64 share the per-source budget. 2. **`active_conns` deleted** with its three manual decrements and the `AtomicUsize` import; no replacement counter. `cluster_auth::panicking_rpc_handler_releases_its_connection_slot` is the regression guard (see the note below on its observable). 3. **`src/distributed/handshake_warn.rs`** (`HandshakeWarnClass {Noise, Diagnostic}`, `handshake_warn_class(&anyhow::Error)`, `WarnBudget::allow_at(class, now) -> WarnDecision { warn, suppressed_in_previous_window }`, process-wide `handshake_warn_allowed(class)` with the rollover summary `N cluster handshake warnings (<class>) were logged at debug in the last 60s`). Pending refusals draw `Noise`, handshake failures `handshake_warn_class(&err)`, rejected frames `Diagnostic`; `tcp_transport.rs` and `stage_assignment.rs` call sites updated, the old limiter removed. Residual risk noted in `docs/distributed.md`. 4. **Router sender check.** `TcpTransport::is_authenticated()`; `RouterState::build` fails with `the disaggregated router requires a role transport bound with the cluster secret`; `result_senders: HashSet<SocketAddr>` (prefill ∪ decode peers, canonical IPs) and `accepts_result_from(&str)`; the demux drops other senders with the `router: dropping result frame from ...` warn through the `Diagnostic` budget. Both router test fixtures bind with auth. `docs/distributed.md`, `docs/CONTINUOUS_BATCHING.md` and the `--prefill-peers` / `--decode-peers` help now say a peer must be listed under the address it connects from (its `--serving-bind`, with an unspecified IP replaced by the source IP). `docs/distributed.md` states that the check authenticates the source IP (handshake-verified) while the port is the sender's advertised listener port, so it tells members apart by source IP plus claimed port, not by port-level proof. The demux logs drops through tracing fields without building a message string. 5. **Admission inside the handshake.** `VERDICT_AT_CAPACITY = 0x02`, `PROTOCOL_VERSION` 3 to 4 (`cluster_handshake.rs`, constant unchanged in name and place), `pub(crate) async fn server_handshake_admitting<P>(stream, auth, local_identity, suite, channel, admit: impl FnOnce() -> Option<P>) -> Result<(String, SessionKeys, P)>` calling `admit()` only after the client authenticator verified; `server_handshake` / `server_handshake_on` wrap it with `|| Some(())`. New errors `ConnectionLimitReached { peer }` (server) and `ServerAtCapacity` (client; not treated as fatal like `HandshakeRejected`: `connect_with_retry` returns it without backoff, the next pool `acquire` reconnects, and `Transport::connect` warns), the latter re-exported from `distributed/mod.rs`. `accept_loop` passes `|| conn_semaphore.try_acquire_owned().ok()` and keeps the `max connections (N) reached` warn. Wire diagram and docs updated. Pre-existing limitation found while writing the item 2 test: `TcpTransport` reads `RpcResponse` frames only on accepted connections, never on the pooled outbound connection an `rpc_call` went out on, so no RPC echo can reach a TCP client (the only in-repo RPC-over-TCP caller, `bench.rs`, ignores the result). The guard therefore keeps the panicking RPC handler as the trigger (client A's `rpc_call(b"boom")` fails) and uses client B's `send` reaching `server.recv()` within 2 s as the observable. ## Changes during review The implementation review and the security review found no CRITICAL or HIGH issues. The follow-up commit tightens wording only: the residual-risk notes now name `IdentityNotOwned` and `FrameSuiteMismatch` (decided from the hello alone) next to `ClientAbortedAfterServerProof` as refusals a party without the secret can push into the `Diagnostic` window; the `ServerAtCapacity` docs and the `connection_pool.rs` "failed handshake is terminal" comment describe the no-backoff reconnect precisely; the `startup.rs` router comment credits `RouterState::build` for enforcing `cluster_auth`; and the sender-check docs say only the source IP is verified. ## Failing-first evidence (main 84e20ce) Checked by temporarily reverting the fix hunks on this branch (key on the full address, one shared warn window, no `is_authenticated` check, no sender check), rebuilding the lib tests and running the tests by name, then restoring the files byte for byte (sha256 verified): - `ipv6_sources_in_one_64_share_the_per_source_limit`: FAILED (third acquire from `2001:db8:1:2:ffff::3` succeeded, `unwrap_err` panicked at `pending_handshakes_tests.rs:83`). - `ipv6_sources_in_different_64s_are_counted_separately`: FAILED (second address in the /64 acquired a slot, `pending_handshakes_tests.rs:110`). - `noise_flood_does_not_suppress_diagnostic_warnings`: FAILED (`left: WarnDecision { warn: false, .. }`). - `build_refuses_an_unauthenticated_transport`: FAILED (`an unauthenticated transport must be refused`). - `result_demux_drops_frames_from_unconfigured_senders`: FAILED (`unconfigured sender's frame was delivered: ... tokens: ["injected"]`). - `rollover_reports_suppressed_count` passes with a shared window too (only one class is exercised); `classifies_handshake_errors` and `accepts_result_from_only_configured_peers` call functions that do not exist on main, so they do not compile there. - `server_at_capacity_sends_capacity_verdict`, `admission_is_not_consulted_before_the_client_authenticates` and `cluster_auth::full_connection_cap_reports_capacity_to_the_client` do not compile on main (`server_handshake_admitting`, `ServerAtCapacity`, `ConnectionLimitReached` are new). - `cluster_auth::panicking_rpc_handler_releases_its_connection_slot` passes with and without the counter, by design. ## Verification (GB10 spark-102, `--profile test-fast`, builds outside `gpu-lock`, runs under `gpu-lock run --tag issue-2692`) - `cargo fmt --check`: clean. - `cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings`: clean (rerun after the review commit: clean; `server::router_front::` + `distributed::handshake_warn::` 38 passed, and the touched modules `cluster_handshake`, `pending_handshakes`, `tcp_transport` 53 passed at 699d208). - 13 new or touched tests by name (`--lib -- --test-threads=1`): 13 passed. - `--lib distributed:: -- --test-threads=1`: 1473 passed, 0 failed, 4 ignored. - `--lib server::router_front -- --test-threads=1`: 35 passed. - `--test zero_config_cluster_init`: 4 passed, 3 ignored. - `tests/disaggregated_serving_e2e.rs` (`--features cuda,test-utils -- --include-ignored --test-threads=1`): 2 passed. - `tests/disaggregated_router_e2e.rs` (same flags): 7 passed (49.7 s). - `MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`, `--features cuda,test-utils -- --ignored --test-threads=1`: `pipeline_remote_real_models` 10 passed, 1 failed; `pipeline_server_remote_real_models` 7 passed, 1 failed; `pipeline_ci_multi_stage_real_models` 2 passed. The two failures are the `glm_moe_dsa` tests panicking in `repo_model_dir` because `glm5-4bit` is absent: `mlx-community/GLM-5-4bit` is 418.6 GB and cannot be loaded on this 128 GB box, and the tests predate #2674 (added 2026-04-13), so this is a missing checkpoint, not a regression. Every llama, gemma3, gemma4, qwen3, qwen3.5 and glm-4.7 parity test passed. - Manual three-process loopback (router + prefill + decode, one shared `--cluster-secret-file` mode 0600, `qwen3-0.6b-4bit`, 127.0.0.1 ports 19801-19806, `target/test-fast/mlxcel-server` built from this branch): `POST /v1/chat/completions` returned HTTP 200 with `"2 + 2 = 4."`, and the router log contains no `dropping result frame` line. Processes killed by PID afterwards. Closes #2692
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).
authset, a socket that has not finished the handshake no longer holds amax_connectionspermit. 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 afterOk(identity). The limiter isdistributed::pending_handshakes::PendingHandshakeLimiter(pub(crate), reusable by feat(distributed): make zero-config --pp-peer bring-up work (beacons and stage push-assignment) #2658's listener). Withauthset,TcpTransport::bindrefuses a zero bound for either field before binding the listener (0 would refuse every authenticated connection). Withoutauththe accept path is byte for byte the old one and the two fields are unused.PROTOCOL_VERSIONis 2. On identity-binding failure the server writesREJECT_MAGIC(MLXCREJ\0) plusREJECT_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_helloreads the first 8 bytes first; in the client role the record becomesHandshakeRejected("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)"), soTransport::connectfails within 1 s instead of warning after the 5 s timeout. Server side: typedIdentityNotOwned { advertised, source_ip }andClientAbortedAfterServerProof("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_handshakewrites the record itself, so any caller gets the behavior.client_handshake,server_handshake,HANDSHAKE_TIMEOUTand the four error types are re-exported frommlxcel::distributedfor feat(distributed): make zero-config --pp-peer bring-up work (beacons and stage push-assignment) #2658's coordinator-to-peer channel.resolve_disaggregated_cluster_auth(sources, mode)next toresolve_pipeline_cluster_auth:HybridreturnsNonewithout reading any source;PrefillOnly,DecodeOnlyandRouterrequire a secret and otherwise fail naming the role andCLUSTER_SECRET_SOURCES_HELP. It runs instart_serverbefore the peer probe, any listener bind and the weight load, withClusterSecretSources::from_env(--cluster-secret-file, [cluster] secret_file). The auth flows throughServerConfig::cluster_authandWorkerSchedulerConfig::cluster_authinto the worker's role transport (disaggregated_role_transport_config) and the router's transport, on bothmlxcel-serverandmlxcel serve. The decode loop's intake is factored intoServingCoordinator::next_decode_metaso 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-roleand--cluster-secret-filehelp, therouter_front.rstrust comment and the tcp_transport Security Notes are updated.tests/disaggregated_router_e2e.rsandtests/disaggregated_serving_e2e.rsgive every spawned role a fresh per-test secret file (tests/common::TestClusterSecretFile); the serving e2e's in-test client transport carries the same auth. Noscripts/or.github/workflows/file launches a disaggregated role (re-checked).Breaking change
--node-role prefill,--node-role decodeand--node-role routernow 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 withthe 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, orhybrid) is unchanged.Migration:
openssl rand -hex 32 > /etc/mlxcel/cluster.secret && chmod 600 /etc/mlxcel/cluster.secret.--cluster-secret-file /etc/mlxcel/cluster.secretto every--node-role prefill|decode|routerlaunch (or setMLXCEL_CLUSTER_SECRET_FILE, orMLXCEL_CLUSTER_SECRET, or[cluster] secret_filein a cluster TOML passed with--distributed-config; same precedence as the pipeline roles).--serving-bindname the IP the peers see this node connect from (not0.0.0.0on 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.Failing-first evidence
Run from the lib test binary built before the implementation (same tests, unfixed code):
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 undergpu-lock run --tag issue-2655)cargo test -p mlxcel --lib distributed:: -- --test-threads=1on 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_workerhas 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 warningson 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.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:--cluster-secret-fileon router, prefill, decode:POST /v1/chat/completionsreturned HTTP 200 ("usage":{"prompt_tokens":16,"completion_tokens":16,"total_tokens":32}).decode handoff to 127.0.0.1:19465 failed; prefill logCluster 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 logRejecting 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.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 forrouter).pgrep -af mlxcel-serverempty afterwards.MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1, built with--no-runoutside the lock:pipeline_remote_runtime_qwen3_real_model_parity_and_cleanupok (1.34 s),pipeline_server_remote_coordinator_qwen3_matches_dense_baselineok (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
ClientAbortedAfterServerProoflike 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 indocs/distributed.mdand 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