Skip to content

[client] Post Quantum ML-KEM rosenpass alternative - #7098

Open
riccardomanfrin wants to merge 124 commits into
mainfrom
feat-post_quantum_ml_kem
Open

riccardomanfrin wants to merge 124 commits into
mainfrom
feat-post_quantum_ml_kem

Conversation

@riccardomanfrin

@riccardomanfrin riccardomanfrin commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes

Adds an optional post-quantum key exchange that derives the WireGuard preshared key from
an X25519MLKEM768 hybrid KEM, as an alternative to Rosenpass. It gives the tunnel key
post-quantum confidentiality (harvest-now-decrypt-later protection) while riding the
existing, already-authenticated Signal offer/answer channel, with a much smaller on-wire
footprint than Rosenpass (~2.3 KB per exchange). Off by default; opt in with
NB_ENABLE_PQ_MLKEM=true.

The KEM logic is a self-contained, consumer-agnostic library (client/internal/pqkem,
no WireGuard/NetBird types); the engine wires it to signalling and the WG interface via
an adapter. Pieces:

  1. KEM (pqkem/kem.go): X25519MLKEM768 per draft-ietf-tls-ecdhe-mlkem; PSK =
    HKDF-SHA256 over ML-KEM_ss ‖ X25519_ss, bound to the transcript and the
    canonicalised peer identities so it can't be transplanted to another pair/exchange.
  2. Manager (pqkem/manager.go, convergence.go): stateful orchestrator. The
    initiator is deterministic (higher WireGuard pubkey = the ICE controller), so a single
    unidirectional exchange yields one shared PSK — no glare / split-brain.
  3. Signalling (peer/handshaker.go, signaler.go, shared/signal/proto): the KEM
    offer/answer piggyback the existing Signal offer/answer. The controller replies to a
    responder's (KEM-less) offer with its own KEM offer instead of answering, so the single
    KEM-carrying transaction is the one that establishes the tunnel and the derived PSK is
    in hand before the first WireGuard handshake.
  4. Data-path transport (pqkem_transport.go): a dedicated UDP socket on the WG
    overlay IP (default port 51833, announced over Signal only when non-default) used for
    PSK rotation.
  5. PSK application (peer/conn.go, pqkem_adapter.go): the bootstrap PSK is pulled
    at WG peer-config time; steady-state rotations are pushed via SetPresharedKey.
  6. Rotation: clocked by WireGuard rekeys and gated on recent real-data activity, so
    idle tunnels stop rotating (keeps lazy connections able to return to idle).
  7. Strict mode (NB_PQ_MLKEM_STRICT): fail-closed — a per-conn random sentinel PSK
    blocks peer traffic until the real PSK is derived. Off = permissive (tunnel forms
    classically and upgrades to PQ when ready).
  8. Coexistence: mutually exclusive with Rosenpass (ML-KEM takes precedence); a peer
    that never presents KEM material is detected as non-PQ (no offer churn); a persistent
    rekey failure re-bootstraps over Signal.

Env vars: NB_ENABLE_PQ_MLKEM (default off), NB_PQ_MLKEM_STRICT, NB_PQ_MLKEM_LOG_LEVEL.

Issue ticket number and link

No public ticket — internal post-quantum project. New self-contained library under
client/internal/pqkem plus engine/signalling wiring; opt-in and off by default.

Stack

Checklist

  • Is it a bug fix
  • Is a typo/documentation fix
  • Is a feature enhancement
  • It is a refactor
  • Created tests that fail without the change (if possible)

By submitting this pull request, you confirm that you have read and agree to the terms of the Contributor License Agreement.

Documentation

Select exactly one:

  • I added/updated documentation for this change
  • Documentation is not needed for this change (explain why)

Experimental, off by default and gated behind NB_ENABLE_PQ_MLKEM; the env vars are not
yet a stable, documented public configuration surface. Public docs will follow once the
feature graduates from opt-in.

Docs PR URL (required if "docs added" is checked)

Paste the PR link from https://github.com/netbirdio/docs here:

N/A

Summary by CodeRabbit

  • New Features
    • Added optional post-quantum protection using ML-KEM alongside existing key exchange.
    • Added configurable enabled and strict modes through environment settings.
    • Added secure peer handshaking, key rotation, recovery, and protection status reporting.
    • Added signaling and data-path support for post-quantum handshake messages.
  • Bug Fixes
    • Improved recovery from failed handshakes and rekey attempts while preserving established connections.
    • Preserved newer security keys during endpoint updates.
  • Reliability
    • Added validation for malformed or tampered exchange messages.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The PR adds ML-KEM-based peer exchange, framed messages, UDP transport, signaling support, WireGuard PSK integration, engine lifecycle handling, and status reporting. It also adds environment controls, logging support, tests, and benchmarks.

Changes: ML-KEM integration

Layer / File(s) Summary
Hybrid exchange and wire framing
client/internal/pqkem/kem.go, client/internal/pqkem/message.go, client/internal/pqkem/*_test.go, client/internal/pqkem/bench_test.go, client/internal/pqkem/env.go
Adds the X25519/ML-KEM-768 exchange, identity-bound PSK derivation, framed messages, validation, callbacks, logging configuration, tests, and benchmarks.
Exchange manager and transport
client/internal/pqkem/manager.go, client/internal/pqkem/convergence.go, client/internal/pqkem_transport.go, client/internal/pqkem/*_test.go
Adds UDP transport, exchange state, signaling bootstrap, retries, capability handling, PSK rotation, failure reporting, and concurrency coverage.
Peer negotiation and signaling
client/internal/peer/handshaker.go, client/internal/pqkem_adapter.go, client/internal/peer/signaler.go, shared/signal/client/client.go, shared/signal/proto/signalexchange.proto
Carries ML-KEM payloads and ports through signaling, registers peer endpoints, and adapts the PQ manager to peer negotiation.
WireGuard connection protection
client/internal/peer/conn.go, client/internal/peer/iface.go, client/internal/peer/endpoint.go, client/internal/peer/conn_pq_test.go, client/internal/peer/conn_test.go
Adds derived-PSK selection, strict-mode handling, activity reporting, datapath callbacks, endpoint-only delayed updates, and corrected Rosenpass status detection.
Engine lifecycle and status reporting
client/internal/engine.go, client/internal/peer/status.go, client/client/proto/daemon.proto, client/server/*, client/status/*, client/internal/debug/debug.go
Starts and stops ML-KEM support, gives it precedence over Rosenpass, validates signal ports, and reports ML-KEM configuration in status and debug output.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Engine
  participant PeerHandshaker
  participant SignalClient
  participant PQManager
  participant PQTransport
  participant WireGuard
  Engine->>PQManager: Start ML-KEM transport
  PeerHandshaker->>PQManager: Generate offer
  PeerHandshaker->>SignalClient: Send ML-KEM payload and port
  SignalClient-->>PeerHandshaker: Receive offer or answer
  PeerHandshaker->>PQManager: Process signaling exchange
  PQManager->>PQTransport: Exchange data-path messages
  PQManager->>WireGuard: Program derived PSK
  WireGuard-->>PQManager: Report rekey or datapath state
Loading

Suggested reviewers: lixmal

Merge Risk: Low · up to ec139

This opt-in change adds hybrid post-quantum key exchange and WireGuard PSK rotation, but its protection status can briefly be reported as active before the exchange is confirmed or remain marked active after a disconnect. The bounded risk is inaccurate security status for operators and automation, so merge is acceptable with explicit follow-up to tighten status transitions.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the feature, implementation, tests, and documentation decision. However, it does not provide the required issue ticket or approved discussion link for this behavior-changing f… Add a link to the NetBird-approved issue or validated discussion. Update the checklist to confirm local testing and the applicable ticket-first requirement.
Docstring Coverage ⚠️ Warning Docstring coverage is 49.15% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 59 functions across 22 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)

Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding ML-KEM as a post-quantum alternative to Rosenpass.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the feature, implementation, tests, and documentation decision. However, it does not provide the required issue ticket or approved discussion link for this behavior-changing feature.

Full details: Docstring Coverage

Explanation

Docstring coverage is 49.15% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 59 functions across 22 files. (1 skipped: 1 unsupported.)

Finishing Touches

Resolve merge conflicts

  • Resolve merge conflict in branch feat-post_quantum_ml_kem
🧪 Generate unit tests (beta)

  • Create PR with unit tests
  • Commit unit tests in branch feat-post_quantum_ml_kem
  • 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

ℹ️ Recent review info

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 1596cbfb-1400-4a29-97ee-6c384ed5d606

📥 Commits

Reviewing files that changed from the base of the PR and between 2eb110f and ec13988.

⛔ Files ignored due to path filters (1)

  • client/proto/daemon.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (8)

  • client/internal/debug/debug.go
  • client/internal/peer/conn.go
  • client/internal/peer/status.go
  • client/proto/daemon.proto
  • client/server/mdm.go
  • client/server/server.go
  • client/status/status.go
  • client/status/status_test.go

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 17

🧹 Nitpick comments (13)
client/internal/pqkem/kem_test.go (1)

28-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use assert for conditions under test.

require aborts the test and is for setup or preconditions. Keep require.NoError where later setup depends on the result. Use assert for equality, inequality, and expected-error conditions.

  • client/internal/pqkem/kem_test.go#L28-L29: replace the PSK result assertions with assert.
  • client/internal/pqkem/kem_framing_test.go#L25-L27: replace the tamper-result assertion with assert.
  • client/internal/pqkem/message_test.go#L20-L25: replace decoded-message assertions with assert.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/kem_test.go` around lines 28 - 29, Replace the PSK
equality and non-zero checks in client/internal/pqkem/kem_test.go:28-29 with
assert calls. Replace the tamper-result assertion in
client/internal/pqkem/kem_framing_test.go:25-27 and the decoded-message
assertions in client/internal/pqkem/message_test.go:20-25 with assert calls,
while retaining require for setup-dependent failures such as require.NoError.

Source: Coding guidelines

client/internal/pqkem_adapter_test.go (1)

29-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the discarded errors.

Lines 29, 30, 34, and 35 discard the error results of AnswerPayload, OfferPayload, and OnAnswer. A decode or state error would pass unnoticed and weaken the capability assertions. Capture each error and check it with require.NoError.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem_adapter_test.go` around lines 29 - 36, Update the test
flow around AnswerPayload, OfferPayload, and OnAnswer to capture every returned
error and assert each with require.NoError before evaluating the payload
capability assertions. Preserve the existing payload nil/non-nil expectations
while ensuring decode or state errors fail the test.
client/internal/pqkem/manager.go (2)

252-266: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Clear the remaining per-peer maps in Stop.

Stop resets exchanges and psks only. established, failures, capable, peerAddrs, and peersByAddr keep every peer entry after shutdown. The guidelines require Stop to clear maps and caches that would otherwise retain memory.

Based on learnings from the coding guidelines: "Make Stop and Close idempotent, release guarded state, and clear maps and caches that would otherwise retain memory."

♻️ Proposed fix
 	m.exchanges = make(map[RemoteID]*exchangeCtl)
 	m.psks = make(map[RemoteID]PSK)
+	m.established = make(map[RemoteID]bool)
+	m.failures = make(map[RemoteID]int)
+	m.capable = make(map[RemoteID]bool)
+	m.peerAddrs = make(map[RemoteID]netip.AddrPort)
+	m.peersByAddr = make(map[netip.AddrPort]RemoteID)
 	m.mu.Unlock()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/manager.go` around lines 252 - 266, Update Manager.Stop
to clear all remaining per-peer state while holding m.mu: reset established,
failures, capable, peerAddrs, and peersByAddr alongside exchanges and psks.
Preserve the existing cancellation, wait, transport detachment, and
transport-close behavior.

Source: Coding guidelines


48-50: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Port values use int across the transport contract. The guidelines require uint16 for ports internally, with conversion to int only at a library boundary. The int type crosses the Transport interface, the Manager accessor, and the UDP implementation, so all three sites must change together.

  • client/internal/pqkem/manager.go#L48-L50: change Transport.LocalPort to return uint16.
  • client/internal/pqkem/manager.go#L156-L164: change Manager.LocalPort to return uint16 and keep the nil transport case returning 0.
  • client/internal/pqkem_transport.go#L11-L23: rename DefaultPort to a private pqDefaultPort, type it and the pqTransport.port field as uint16, and convert to int only in the net.UDPAddr literal and from conn.LocalAddr().

Based on learnings from the coding guidelines: "Use uint16 for ports internally and convert to int only when required by a library."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/manager.go` around lines 48 - 50, Use uint16 for ports
throughout the transport contract: update Transport.LocalPort and
Manager.LocalPort in client/internal/pqkem/manager.go (lines 48-50 and 156-164),
preserving the nil transport return of 0; in client/internal/pqkem_transport.go
(lines 11-23), rename DefaultPort to private pqDefaultPort, make it and
pqTransport.port uint16, and convert to int only at net.UDPAddr construction and
when reading conn.LocalAddr().

Source: Coding guidelines

client/internal/pqkem/concurrency_test.go (1)

20-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Set the tuning fields before Start, or expose an options constructor.

The test writes retryInterval, maxRetries, and maxRekeyFailures after pair already called Start. The write is safe today only because no exchange loop exists yet. A future change that starts a loop inside Start turns this into a data race that -race reports intermittently. Add a test-only constructor or functional options to NewManager and set the values at construction.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/concurrency_test.go` around lines 20 - 24, Move the dB
tuning configuration for retryInterval, maxRetries, and maxRekeyFailures to
construction time, before Start is invoked. Add a test-only constructor or
functional options to NewManager, use it when creating dB, and remove the
post-Start field assignments so exchange loops never observe concurrent
configuration writes.
client/internal/pqkem/manager_test.go (1)

130-134: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use assert for the conditions under test.

The guidelines reserve require for setup and preconditions, and assert for the conditions under test. The PSK equality checks are the conditions under test, so use assert.Equal and assert.NotEqual there. Keep require for the bootstrap calls in bootstrap.

Based on learnings from the coding guidelines: "Use require for setup and preconditions, assert for conditions under test, and provide context for comparison, boolean, and collection assertions."

Also applies to: 149-153, 168-177

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/manager_test.go` around lines 130 - 134, In the PSK
derivation tests around wgA.psk and wgB.psk, replace require.NotEqual and
require.Equal with assert.NotEqual and assert.Equal, preserving the existing
comparison context messages. Apply the same assertion-type change to the
additional PSK checks at the referenced test cases, while keeping require for
bootstrap setup calls in bootstrap.

Source: Coding guidelines

client/internal/pqkem_transport.go (1)

56-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Confirm the receive buffer covers the largest framed message.

The buffer is 2048 bytes. A UDP read larger than the buffer is truncated silently, and the decoder then rejects the message with no size diagnostic. The X25519MLKEM768 offer carries a 1184-byte ML-KEM encapsulation key plus the X25519 share, so the current value looks sufficient. Derive the size from a framing constant in message.go instead of a literal, and log a truncated read at debug level.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem_transport.go` around lines 56 - 69, The receive buffer
in pqTransport.Run should be sized from the framing constant in message.go
rather than the literal 2048, and the read loop should detect and debug-log
truncated UDP datagrams before passing data to onInbound.
client/internal/pqkem/env.go (3)

76-100: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Enabled parses the environment variable on every log record.

slogToLogrus.Enabled calls logLevel(), which runs os.Getenv, strings.TrimSpace, and strings.ToLower for each record that slog evaluates. The ML-KEM manager emits trace records on hot paths such as data-path rekey. Resolve the level once and store it.

♻️ Proposed refactor
+var resolvedLogLevel = sync.OnceValue(logLevel)
+
 func (h slogToLogrus) Enabled(_ context.Context, level slog.Level) bool {
-	return level >= logLevel()
+	return level >= resolvedLogLevel()
 }

Add sync to the imports. If the level must stay reconfigurable at runtime, store it in an atomic.Int32 instead and update it when the daemon log level changes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/env.go` around lines 76 - 100, Resolve the configured
log level once when creating or initializing slogToLogrus, and store that
resolved slog.Level on the handler instead of calling logLevel() from Enabled
for every record. Update Enabled to compare against the stored level, preserving
the existing environment parsing and default behavior; only use an atomic value
if runtime log-level reconfiguration is required by the surrounding code.

45-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared boolean environment parsing.

Strict duplicates the logic of Enabled. It also calls os.Getenv(EnvStrict) three times and repeats strings.TrimSpace. Extract one helper and call it from both functions.

♻️ Proposed refactor
+// envBool reads name and reports its boolean value. An empty or unparsable value
+// yields false and logs a warning.
+func envBool(name string) bool {
+	raw := strings.ToLower(strings.TrimSpace(os.Getenv(name)))
+	switch raw {
+	case "", "off":
+		return false
+	case "on":
+		return true
+	}
+	enabled, err := strconv.ParseBool(raw)
+	if err != nil {
+		log.Warnf("parse %s value %q: %v", name, raw, err)
+		return false
+	}
+	return enabled
+}
+
 func Strict() bool {
-	switch strings.ToLower(strings.TrimSpace(os.Getenv(EnvStrict))) {
-	case "on":
-		return true
-	case "", "off":
-		return false
-	}
-	enabled, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(EnvStrict)))
-	if err != nil {
-		log.Warnf("failed to parse %s value %q: %v", EnvStrict, os.Getenv(EnvStrict), err)
-		return false
-	}
-	return enabled
+	return envBool(EnvStrict)
 }

The coding guidelines also ask for error context without a failed to prefix, which the helper applies.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/env.go` around lines 45 - 58, Extract the shared
boolean environment parsing from Strict and Enabled into one helper that reads
and trims the environment value once, supports on/off and ParseBool values, and
logs parse errors with the environment key and value without a “failed to”
prefix. Update both Strict and Enabled to delegate to this helper while
preserving their existing defaults and behavior.

Source: Coding guidelines


138-138: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

WithGroup discards the group name.

The handler ignores the group and returns itself. Attributes from different groups then write to the same field keys and overwrite each other. The ML-KEM manager does not use groups today, so no record is affected now. Document this limitation in a comment, or qualify subsequent attribute keys with the group prefix.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/pqkem/env.go` at line 138, Document the limitation in
slogToLogrus.WithGroup: it currently ignores the group name, so attributes from
different groups are not namespaced and may overwrite identical keys. Keep the
existing handler behavior unchanged, since current ML-KEM usage does not rely on
groups.
client/internal/peer/conn_pq_test.go (1)

65-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a case for a missing sentinel in strict mode.

The test covers strict mode only when pqStrictSentinelKey is set. NewConn can leave that field nil if key generation fails, and presharedKey then returns the ordinary key while strict mode is configured. Add a subtest that sets PQStrict = true with a nil pqStrictSentinelKey, so the fail-open behavior described in the NewConn comment is pinned by a test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/peer/conn_pq_test.go` around lines 65 - 85, Add a subtest
alongside the existing strict-mode cases that configures PQStrict true, leaves
pqStrictSentinelKey nil, and uses unavailable PQ; assert presharedKey returns
the ordinary nbPSK. This should pin the NewConn fail-open behavior when sentinel
generation fails.
client/internal/engine.go (1)

563-567: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Evaluate pqkem.Enabled() once.

pqkem.Enabled() reads and parses an environment variable on each call. Start calls it three times, and the two adjacent if statements test the same condition pair. Store the result in a local variable and use one if/else.

♻️ Proposed refactor
-	// Rosenpass and ML-KEM are mutually exclusive. ML-KEM (NB_ENABLE_PQ_MLKEM) takes precedence
-	if e.config.RosenpassEnabled && pqkem.Enabled() {
-		log.Warnf("rosenpass and ML-KEM post-quantum are mutually exclusive; ML-KEM is enabled, so rosenpass is disabled")
-	}
-	if e.config.RosenpassEnabled && !pqkem.Enabled() {
+	// Rosenpass and ML-KEM are mutually exclusive. ML-KEM (NB_ENABLE_PQ_MLKEM) takes precedence
+	pqEnabled := pqkem.Enabled()
+	if e.config.RosenpassEnabled && pqEnabled {
+		log.Warnf("rosenpass and ML-KEM post-quantum are mutually exclusive; ML-KEM is enabled, so rosenpass is disabled")
+	} else if e.config.RosenpassEnabled {

Reuse pqEnabled at line 658 as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/engine.go` around lines 563 - 567, In Start, evaluate
pqkem.Enabled() once into a local variable such as pqEnabled, then use that
variable for the adjacent Rosenpass/ML-KEM conditional as a single if/else while
preserving the existing precedence and logging behavior. Replace the later
pqkem.Enabled() call at the referenced Start logic with the same local variable.
client/internal/peer/conn.go (1)

1045-1053: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

LastActivities() builds a whole map for one lookup.

dataActivityAge runs on every successful WireGuard handshake check, for every peer. Each call allocates and copies the complete per-peer activity map, then reads a single key. The cost grows as O(peers²) per check cycle on large meshes.

Consider adding a single-peer accessor to WGIface, for example LastActivity(peerKey string) (monotime.Time, bool), and calling that instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/peer/conn.go` around lines 1045 - 1053, Replace the full-map
lookup in Conn.dataActivityAge with a single-peer activity accessor on WGIface,
such as LastActivity(peerKey string), using the existing RemoteKey. Implement
the accessor to retrieve only that peer’s timestamp while preserving the current
missing-peer behavior of returning time.Duration(math.MaxInt64) and the existing
monotime.Since calculation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@client/internal/engine.go`:
- Around line 656-678: Update the pqkem transport initialization in Start so a
newPQTransport failure is fatal when strict mode is configured: log the bind
error and terminate startup through the existing fatal/error-return mechanism
instead of continuing with a nil e.pqkemManager. Preserve the current non-fatal
logging and disabled behavior when strict mode is not enabled.

In `@client/internal/peer/conn_pq_test.go`:
- Around line 55-58: Update the strict setup block in the test to capture and
validate the error returned by wgtypes.GenerateKey using require.NoError before
assigning pqStrictSentinelKey, matching the existing checked call later in the
test and preventing use of an invalid zero key.

In `@client/internal/peer/conn.go`:
- Around line 84-93: The PQ port type must remain uint16 internally and only
widen at the protobuf boundary. In client/internal/peer/conn.go lines 84-93,
update PQHandshaker methods OfferPayload and AnswerPayload to return uint16
ports; in client/internal/engine.go lines 2900-2901, validate MlkemPort fits
uint16 before converting, pass it as uint16, and change
peer.OfferAnswer.MlkemPort to uint16.
- Around line 1095-1111: Remove manager-to-Conn lock inversions in
client/internal/peer/conn.go:1095-1111 by obtaining the PSK before conn.mu is
held or passing it into presharedKey; move OnDataPathDown outside the locked
body at client/internal/peer/conn.go:756-758; compute quantumResistant before
updateRelayStatus at client/internal/peer/conn.go:802 and before updateIceState
at client/internal/peer/conn.go:821, passing each result into the respective
method. Perform the required two-pass race analysis and run go test -race for
all touched packages.
- Around line 255-261: Update the strict-mode sentinel generation in NewConn to
return the GenerateKey error immediately instead of logging and continuing with
a nil pqStrictSentinelKey. Preserve assigning conn.pqStrictSentinelKey on
success so presharedKey remains fail-closed for PQStrict peers.

In `@client/internal/peer/handshaker.go`:
- Around line 217-224: Update Handshaker.pqRegisterEndpoint to select a usable
peer address instead of always using AllowedIps[0]. Iterate valid prefixes, only
consider IPv6 when wgIface.Address().HasIPv6() is true, treat missing or invalid
IPv6 addresses as absent, and fall back to a usable IPv4 prefix without allowing
IPv6 failures to prevent registration.
- Around line 42-50: Use uint16 for ML-KEM ports throughout the internal
handshaker and adapter path: update client/internal/peer/handshaker.go:42-50
OfferAnswer.MlkemPort, client/internal/pqkem_adapter.go:60-72 announcedPort and
payload methods, client/internal/peer/conn.go
PQHandshaker.OfferPayload/AnswerPayload, and
shared/signal/client/client.go:55-59 CredentialPayload.MlkemPort to return or
store uint16; validate protobuf GetMlkemPort() in client/internal/engine.go
before assigning it, keep the local transport port validated as a port, and
defensively convert the uint16 credential value to protobuf uint32 at
shared/signal/client/client.go:97-103.

In `@client/internal/pqkem_adapter.go`:
- Around line 67-113: Add GoDoc comments immediately above the exported methods
OfferPayload, ShouldSendBootstrapOffer, AnswerPayload, and OnAnswer. Each
comment must begin with the exact method identifier, describe its behavior in a
full sentence, and end with a period.

In `@client/internal/pqkem_transport.go`:
- Around line 29-43: Update newPQTransport to call Unmap on overlayIP before
converting it, and select the network as udp4 for IPv4 addresses or udp6 for
IPv6 addresses in both ListenUDP calls. Also update pqTransport.Send to unmap
endpoint.Addr() before constructing the destination AddrPort, preserving the
existing port and error behavior.

In `@client/internal/pqkem/bench_test.go`:
- Around line 22-23: Update the benchmark setup around GenerateKey calls in the
affected benchmark cases to capture and validate each returned error, calling
b.Fatal with the error when generation fails. Apply this consistently to all
referenced key-generation pairs, including the setup near lines 22–23, 42–43,
and 51–52, while preserving the existing successful key usage.

In `@client/internal/pqkem/convergence_test.go`:
- Line 39: Replace the runtime-behavior checks with assert variants while
retaining require for setup and preconditions: in
client/internal/pqkem/convergence_test.go lines 39-39 use assert.Eventually, and
lines 68-73 use assert.Equal and assert.Eventually; in
client/internal/pqkem/capability_test.go lines 20-23 use assert.Nil and
assert.Empty, lines 43-46 use assert.Nil and assert.Empty, and lines 62-64 use
assert.True and assert.NotEqual.

In `@client/internal/pqkem/convergence.go`:
- Around line 140-150: Update processAnswer around init.Finish so a Finish error
removes the exchange, registers the rekey failure, and raises the failure
through the existing failure-notification path. Ensure the cleanup occurs after
the state/initiator transition and before returning, preserving the successful
PSK flow and triggering OnRekeyFailed for initiator failures.
- Around line 39-56: Update startExchange around m.wait.Add and Manager.Stop so
shutdown coordination is serialized under m.mu: after rootCancel(), have Stop
acquire m.mu before calling m.wait.Wait(), and in startExchange check m.rootCtx
under m.mu, rejecting and cleaning up the newly created exchange when
cancellation indicates stopping before calling Add or launching initiatorLoop.
Ensure the check and WaitGroup increment cannot interleave.

In `@client/internal/pqkem/kem_test.go`:
- Around line 36-46: Update the binding test to reuse the existing exchange
material in answer when deriving pskWrong, changing only the Binding peer
identity instead of calling Respond again. Keep the honest pskHonest derivation
and final inequality assertion unchanged so the test isolates binding effects.

In `@client/internal/pqkem/kem.go`:
- Around line 151-153: Update derivePSK to validate that both Binding.LocalID
and Binding.RemoteID are non-empty before calling canonicalPair or constructing
HKDF input; return an error for either missing identity. Add tests covering an
empty LocalID and an empty RemoteID.

In `@client/internal/pqkem/manager.go`:
- Around line 279-302: Close the check-then-act race in SignalOffer and
OnDataPathRekeyed by serializing each peer’s idempotency check with exchange
installation. Add or reuse an internal startExchangeLocked path that inserts the
new exchange while m.mu remains held, and update both callers to use it without
unlocking between the decision and creation; preserve the existing reuse of
in-flight exchanges and avoid canceling an exchange another concurrent caller
has just installed.

In `@client/internal/pqkem/message.go`:
- Around line 43-49: Update the OfferMsg documentation to state that KEMOffer
contains the ML-KEM encapsulation key followed by the X25519 public key,
matching the byte order emitted by NewInitiator. Leave the OfferMsg fields and
serialization behavior unchanged.

---

Nitpick comments:
In `@client/internal/engine.go`:
- Around line 563-567: In Start, evaluate pqkem.Enabled() once into a local
variable such as pqEnabled, then use that variable for the adjacent
Rosenpass/ML-KEM conditional as a single if/else while preserving the existing
precedence and logging behavior. Replace the later pqkem.Enabled() call at the
referenced Start logic with the same local variable.

In `@client/internal/peer/conn_pq_test.go`:
- Around line 65-85: Add a subtest alongside the existing strict-mode cases that
configures PQStrict true, leaves pqStrictSentinelKey nil, and uses unavailable
PQ; assert presharedKey returns the ordinary nbPSK. This should pin the NewConn
fail-open behavior when sentinel generation fails.

In `@client/internal/peer/conn.go`:
- Around line 1045-1053: Replace the full-map lookup in Conn.dataActivityAge
with a single-peer activity accessor on WGIface, such as LastActivity(peerKey
string), using the existing RemoteKey. Implement the accessor to retrieve only
that peer’s timestamp while preserving the current missing-peer behavior of
returning time.Duration(math.MaxInt64) and the existing monotime.Since
calculation.

In `@client/internal/pqkem_adapter_test.go`:
- Around line 29-36: Update the test flow around AnswerPayload, OfferPayload,
and OnAnswer to capture every returned error and assert each with
require.NoError before evaluating the payload capability assertions. Preserve
the existing payload nil/non-nil expectations while ensuring decode or state
errors fail the test.

In `@client/internal/pqkem_transport.go`:
- Around line 56-69: The receive buffer in pqTransport.Run should be sized from
the framing constant in message.go rather than the literal 2048, and the read
loop should detect and debug-log truncated UDP datagrams before passing data to
onInbound.

In `@client/internal/pqkem/concurrency_test.go`:
- Around line 20-24: Move the dB tuning configuration for retryInterval,
maxRetries, and maxRekeyFailures to construction time, before Start is invoked.
Add a test-only constructor or functional options to NewManager, use it when
creating dB, and remove the post-Start field assignments so exchange loops never
observe concurrent configuration writes.

In `@client/internal/pqkem/env.go`:
- Around line 76-100: Resolve the configured log level once when creating or
initializing slogToLogrus, and store that resolved slog.Level on the handler
instead of calling logLevel() from Enabled for every record. Update Enabled to
compare against the stored level, preserving the existing environment parsing
and default behavior; only use an atomic value if runtime log-level
reconfiguration is required by the surrounding code.
- Around line 45-58: Extract the shared boolean environment parsing from Strict
and Enabled into one helper that reads and trims the environment value once,
supports on/off and ParseBool values, and logs parse errors with the environment
key and value without a “failed to” prefix. Update both Strict and Enabled to
delegate to this helper while preserving their existing defaults and behavior.
- Line 138: Document the limitation in slogToLogrus.WithGroup: it currently
ignores the group name, so attributes from different groups are not namespaced
and may overwrite identical keys. Keep the existing handler behavior unchanged,
since current ML-KEM usage does not rely on groups.

In `@client/internal/pqkem/kem_test.go`:
- Around line 28-29: Replace the PSK equality and non-zero checks in
client/internal/pqkem/kem_test.go:28-29 with assert calls. Replace the
tamper-result assertion in client/internal/pqkem/kem_framing_test.go:25-27 and
the decoded-message assertions in client/internal/pqkem/message_test.go:20-25
with assert calls, while retaining require for setup-dependent failures such as
require.NoError.

In `@client/internal/pqkem/manager_test.go`:
- Around line 130-134: In the PSK derivation tests around wgA.psk and wgB.psk,
replace require.NotEqual and require.Equal with assert.NotEqual and
assert.Equal, preserving the existing comparison context messages. Apply the
same assertion-type change to the additional PSK checks at the referenced test
cases, while keeping require for bootstrap setup calls in bootstrap.

In `@client/internal/pqkem/manager.go`:
- Around line 252-266: Update Manager.Stop to clear all remaining per-peer state
while holding m.mu: reset established, failures, capable, peerAddrs, and
peersByAddr alongside exchanges and psks. Preserve the existing cancellation,
wait, transport detachment, and transport-close behavior.
- Around line 48-50: Use uint16 for ports throughout the transport contract:
update Transport.LocalPort and Manager.LocalPort in
client/internal/pqkem/manager.go (lines 48-50 and 156-164), preserving the nil
transport return of 0; in client/internal/pqkem_transport.go (lines 11-23),
rename DefaultPort to private pqDefaultPort, make it and pqTransport.port
uint16, and convert to int only at net.UDPAddr construction and when reading
conn.LocalAddr().
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: b096d132-4a55-4fa5-8dc2-82b2b965c7c2

📥 Commits

Reviewing files that changed from the base of the PR and between 524b8b9 and 887ecf8.

⛔ Files ignored due to path filters (1)
  • shared/signal/proto/signalexchange.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (25)
  • client/internal/engine.go
  • client/internal/peer/conn.go
  • client/internal/peer/conn_pq_test.go
  • client/internal/peer/handshaker.go
  • client/internal/peer/iface.go
  • client/internal/peer/signaler.go
  • client/internal/pqkem/bench_test.go
  • client/internal/pqkem/callbacks.go
  • client/internal/pqkem/capability_test.go
  • client/internal/pqkem/concurrency_test.go
  • client/internal/pqkem/convergence.go
  • client/internal/pqkem/convergence_test.go
  • client/internal/pqkem/env.go
  • client/internal/pqkem/kem.go
  • client/internal/pqkem/kem_framing_test.go
  • client/internal/pqkem/kem_test.go
  • client/internal/pqkem/manager.go
  • client/internal/pqkem/manager_test.go
  • client/internal/pqkem/message.go
  • client/internal/pqkem/message_test.go
  • client/internal/pqkem_adapter.go
  • client/internal/pqkem_adapter_test.go
  • client/internal/pqkem_transport.go
  • shared/signal/client/client.go
  • shared/signal/proto/signalexchange.proto

Comment thread client/internal/engine.go Resolved
Comment thread client/internal/peer/conn_pq_test.go Resolved
Comment thread client/internal/peer/conn.go Resolved
Comment thread client/internal/peer/conn.go Resolved
Comment thread client/internal/peer/conn.go Resolved
Comment thread client/internal/pqkem/convergence.go Resolved
Comment thread client/internal/pqkem/kem_test.go Resolved
Comment thread client/internal/pqkem/kem.go Resolved
Comment thread client/internal/pqkem/manager.go Resolved
Comment thread client/internal/pqkem/message.go Resolved
@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

@riccardomanfrin

Copy link
Copy Markdown
Contributor Author

@coderabbitai, we always have IPv4 100.x.. in the overlay, IPv6 is additive so we can use udp4

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@riccardomanfrin Understood. Every NetBird overlay has an IPv4 100.x.x.x address, and IPv6 is optional. Using udp4 for the PQ KEM transport is correct. I withdraw the IPv6 concern.


✏️ Learnings added
Learnt from: riccardomanfrin
URL: https://github.com/netbirdio/netbird/pull/7098

Timestamp: 2026-08-07T15:15:55.040Z
Learning: In the NetBird overlay, every peer has an IPv4 address in the `100.x.x.x` range. IPv6 is additive. Network transports such as the PQ KEM UDP data path can use `udp4` when they bind to an overlay address.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
client/internal/peer/conn.go (1)

466-467: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Correct the lock-order description.

pqPSK completes the manager call before the caller acquires conn.mu. It does not establish a conn.mu -> manager lock order. Document the actual invariant: do not call PQHandshaker while holding conn.mu, because manager callbacks can re-enter Conn.

  • client/internal/peer/conn.go#L466-L467: replace the stated lock order with the no-manager-call-under-conn.mu rule.
  • client/internal/peer/conn.go#L550-L551: use the same corrected rule.
  • client/internal/peer/conn.go#L617-L618: use the same corrected rule.
  • client/internal/peer/conn.go#L1110-L1113: correct the helper contract to describe non-overlapping lock acquisition.

As per coding guidelines, comments should explain why, not what.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@client/internal/peer/conn.go` around lines 466 - 467, The comments around
conn.pqPSK at client/internal/peer/conn.go lines 466-467, 550-551, and 617-618
incorrectly describe a conn.mu -> manager lock order; replace each with the
invariant that PQHandshaker must not be called while holding conn.mu because
manager callbacks may re-enter Conn. Update the helper contract at lines
1110-1113 to describe non-overlapping lock acquisition and explain the
re-entrancy reason rather than restating lock operations.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@client/internal/peer/conn_test.go`:
- Around line 297-304: Update the assertions in the presharedKey test to use
assert.Nil for the Rosenpass-managed case and assert.NotNil for the initial-key
case, replacing the corresponding t.Fatalf checks while preserving their
existing failure messages or context.

In `@client/internal/pqkem_adapter.go`:
- Around line 84-86: Update the AnswerPayload documentation to describe
empty-offer handling by role: treat an empty offer as a capability signal when
this peer is the responder, while noting that an empty offer is expected when
this peer is the initiator. Keep the existing description of the returned KEM
answer and data-path port.

---

Nitpick comments:
In `@client/internal/peer/conn.go`:
- Around line 466-467: The comments around conn.pqPSK at
client/internal/peer/conn.go lines 466-467, 550-551, and 617-618 incorrectly
describe a conn.mu -> manager lock order; replace each with the invariant that
PQHandshaker must not be called while holding conn.mu because manager callbacks
may re-enter Conn. Update the helper contract at lines 1110-1113 to describe
non-overlapping lock acquisition and explain the re-entrancy reason rather than
restating lock operations.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 041cb6b6-006c-45ae-8368-539680d2cbac

📥 Commits

Reviewing files that changed from the base of the PR and between a7d2f80 and 3355911.

📒 Files selected for processing (18)
  • client/internal/engine.go
  • client/internal/peer/conn.go
  • client/internal/peer/conn_pq_test.go
  • client/internal/peer/conn_test.go
  • client/internal/peer/handshaker.go
  • client/internal/peer/signaler.go
  • client/internal/pqkem/bench_test.go
  • client/internal/pqkem/capability_test.go
  • client/internal/pqkem/concurrency_test.go
  • client/internal/pqkem/convergence.go
  • client/internal/pqkem/convergence_test.go
  • client/internal/pqkem/kem.go
  • client/internal/pqkem/kem_test.go
  • client/internal/pqkem/manager.go
  • client/internal/pqkem/manager_test.go
  • client/internal/pqkem/message.go
  • client/internal/pqkem_adapter.go
  • client/internal/pqkem_transport.go
🚧 Files skipped from review as they are similar to previous changes (12)
  • client/internal/peer/signaler.go
  • client/internal/pqkem/concurrency_test.go
  • client/internal/pqkem/bench_test.go
  • client/internal/pqkem/convergence.go
  • client/internal/pqkem/capability_test.go
  • client/internal/pqkem_transport.go
  • client/internal/engine.go
  • client/internal/pqkem/kem.go
  • client/internal/pqkem/message.go
  • client/internal/pqkem/manager.go
  • client/internal/pqkem/convergence_test.go
  • client/internal/peer/handshaker.go

Comment thread client/internal/peer/conn_test.go Resolved
Comment thread client/internal/pqkem_adapter.go Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 36 files

Tip: instead of fixing issues one by one fix them all with cubic
Tip: cubic can generate docs of your entire codebase and keep them up to date. Try it here.

Re-trigger cubic

Comment thread client/internal/pqkem/callbacks.go Resolved
Comment thread client/internal/pqkem/convergence.go Resolved
Comment thread client/internal/pqkem/manager.go Resolved
Comment thread client/internal/pqkem/manager.go Resolved
Comment thread client/internal/engine.go Resolved
Comment thread client/internal/pqkem/convergence.go Resolved
Comment thread client/internal/pqkem/callbacks.go Resolved
Comment thread client/internal/pqkem/callbacks.go Resolved
Comment thread client/internal/pqkem/manager.go Resolved
Comment thread client/status/status.go Resolved
@riccardomanfrin
riccardomanfrin force-pushed the feat-post_quantum_ml_kem branch from ec13988 to 2a9c8dd Compare August 27, 2026 11:06

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 5 files (changes from recent commits).

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

Fix all with cubic | Re-trigger cubic

Comment thread client/internal/pqkem/convergence.go Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread client/internal/pqkem/manager.go Resolved
CGO_ENABLED=1 go test ./client/internal/pqkem/ -run '^$' -bench . -benchmem 2>&1 | grep -E "Benchmark|ns/op|PASS|ok" | head -20

BenchmarkX25519Keygen-14    	   33795	     34966 ns/op	     224 B/op	       5 allocs/op
BenchmarkX25519ECDH-14      	   33855	     33973 ns/op	      32 B/op	       1 allocs/op
BenchmarkMLKEMKeygen-14     	   21817	     67778 ns/op	    8200 B/op	       2 allocs/op
BenchmarkMLKEMEncaps-14     	   29918	     43235 ns/op	    1216 B/op	       2 allocs/op
BenchmarkMLKEMDecaps-14     	   26048	     56291 ns/op	      64 B/op	       2 allocs/op
PASS
ok  	github.com/netbirdio/netbird/client/internal/pqkem	9.751s
Shell cwd was reset to /home/riccardo/Desktop/Personal/netbirdio/netbird
 - Have just one manager => one lock
 - Session state is needed in driver to => we have it available now.
 - Isomorphically align to rosenpass components and functionality

File	Role	                                  rosenpass equivalent
kem.go	primitive pure X25519MLKEM768	          crypto.go/handshake
message.go	Offer/Answer/Confirm + Encode/Decode  messages.go
manager.go	Manager stateful, single lock	      server logic
callbacks.go	WGCallbackHandler (seam output)	  Handler
Transport (interfaccia)	seam trasporto pluggable  Conn
…path established yet) + data path one

Define OnDataPathRekeyed event to transition from control plane path to data plane path over the WG tunnel.

Keep confirm ALWAYS on NEW established WG tunnel (posthandshake with rekeying). We keep an active method
irrelevant of the WG handshake (we might decide that the indirect wg handshake is sufficient in the future).

Optimistic commit on responder(when sending answer), while on initiator we set it on getting the answer
…ous round

We clock the next Offer initiation to the OnDataPathRekeyed, so we have 2 minutes
ahead of us to do our attempts and stuff before to give up.
On failure, we will know because we will not receive a new answer.. but more importantly
the wg handshake will fail :D
…cted

A failed KEM exchange makes the manager ask for a fresh signalling offer.
For a peer that is registered but offline that offer can never be answered,
so with lazy connections off (the default) each such peer drew a new offer
at every exchange timeout, about every 22 seconds, forever. That runs on top
of the reconnect guard, which already retries the peer with exponential
backoff, and every guard offer starts a fresh KEM exchange anyway. With many
offline peers it is a steady stream of useless Signal traffic.

Send the recovery offer only while the peer is connected. That is where it
is needed: the transport is up but the KEM did not converge (strict mode
stuck before its first PSK, or a broken rotation). An unreachable peer is
left to the guard's backoff.
When every offer of a data-path rotation was lost, the initiator dropped
the exchange and logged that it would retry next cycle. It never did: a
rekey only chains a new rotation from an exchange awaiting it, and none was
left. Rotation stopped until the next Signal re-bootstrap (a lazy wake, or
never on a long-lived connection), and because no further attempt ran, the
consecutive-failure count could not reach the threshold that hands recovery
to the host either (reported in the security review of #7098).

On a rotation timeout, hand the chain back to the exchange the rotation
acknowledged. The next rekey then starts a fresh rotation from it: if the
offer was simply lost both peers still hold that PSK and the rotation
converges, and if the responder had already moved on, the attempts keep
failing until the threshold triggers a re-bootstrap. A timed-out bootstrap
is still dropped, as it has nothing to fall back to.
Two derivations for the same peer can overlap, for example a rotation and
a Signal re-bootstrap. The generation guard checked and recorded the
generation under a lock but called SetPresharedKey after releasing it, so an
older apply already inside SetPresharedKey could finish after a newer one
and leave WireGuard on the stale key, splitting the peers until the next
exchange (reported in the security review of #7098).

Hold the lock across the generation check and the SetPresharedKey call. The
lock only serialises PSK applies, which are quick local calls, so this does
not reach into the manager's own locking.
The recovery that re-runs the ML-KEM bootstrap after a failed exchange was
called RequestReoffer (and "reoffer" along the callback chain). The name
only says that another offer goes out, so it reads like routine
renegotiation or key rotation, while it fires only when the exchange has
failed: the initial exchange, or rotations failing repeatedly. Normal
rotation never takes this path; it runs over the data path.

Rename it RecoverPQKeyOverSignal, and the callback field, engine wiring, log
line, comments and test with it. The controller re-offer in the handshaker
is a different mechanism and keeps its name. Pure rename, no behaviour
change; only the debug log wording follows the new name.
Only the controller's offer carries KEM material, so when the responder
starts a negotiation the controller is meant to reply with its own KEM
offer. It only did so before the very first exchange: once it held a
converged PSK it answered the responder's offer normally and kept that PSK,
on the assumption that a stale key would heal through the WireGuard watcher
reconnecting over Signal.

That assumption fails when the reconnect comes from the responder. If every
answer of a data-path rotation is lost, the responder commits the new PSK
and the controller does not, so WireGuard cannot handshake and no further
rotation runs to escalate. The watcher closes the connection after ~3.5
minutes and ICE reconnects in seconds, but the reconnect offer came from the
responder, the controller kept its stale key, and the tunnel stayed down.
In the lab it took 201 s and a lazy-connection idle/wake cycle to heal; with
lazy connections off, the default, nothing would heal it.

Treat a converged exchange as not in flight: a responder offer then always
gets a fresh bootstrap, so any responder-started renegotiation re-aligns
both PSKs. While the controller's own exchange is still in flight a
crossing offer is answered normally as before, so offers cannot multiply.
The cost is one extra Signal KEM round per responder-started reconnect.
The recovery test could time out its own bootstraps under CI load, the
non-capable test passed with the cancellation removed, and the decoder
rejection test only exercised the encoder. The timing spike ran on every
go test; it is a benchmark now.
…atus flag

These branches decide whether ML-KEM runs, which port a peer is reached
on, and what the status reports, and none of them had a test.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 30 files (changes from recent commits).

Tip: Review your code locally with the cubic CLI to iterate faster.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread client/internal/pqkem/split_test.go Resolved
Comment thread client/internal/peer/status.go Resolved
Comment thread client/internal/pqkem_adapter.go Resolved
Comment thread client/internal/pqkem/manager.go Resolved
…istant

The PSK usually lands after the connection came up, so the flag flips with
no other state change. Without a notification, UI and CLI subscribers kept
showing the peer as unprotected until something unrelated changed.
They are WireGuard key material like the current ones, which Stop already
clears, and nothing reads them after shutdown.
The split-key test only checked the manager's decision, so a broken
handshaker branch would still pass. The capability test asserted while
holding the manager lock, which hangs instead of failing.
The post-quantum exchange adds about 270 KB to the wasm client, pushing
it past 60 MB. ML-KEM runs in the browser too, so the code stays in.
An empty answer tells the initiator the peer does not run the KEM, and it
stops offering for good. A decode or version error is not that: a newer
client talking to an older one would silently stay classical.
…igure

The conn reads the PSK before configuring WireGuard. A rotation committed
in between pushes its key first, and the configure then overwrites it with
the old one, splitting the keys until the next reconnect.
When the controller's KEM offer and the responder's offer cross, the
controller used to answer the responder's offer without KEM. If the
responder read that answer before the KEM offer, it could bring WireGuard
up on no PSK and open a classical session. The responder's details still
reach the controller in its answer to the KEM offer.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 10 files (changes from recent commits).

Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread client/internal/peer/handshaker.go Resolved
The offer exchange is installed before the Signal send, so a failed send
leaves it in flight with nothing delivered. Ignoring the responder's offer
then stalled the connection until the exchange timed out. Resending the
same offer delivers it; the responder answers a duplicate from its cache.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread client/internal/peer/handshaker.go Resolved
# Conflicts:
#	.github/workflows/wasm-build-validation.yml
Main now imports the wireguard-go fork directly instead of through a
replace directive, so the upstream netstack path resolves to the original
module, which no longer builds against the bumped gvisor.
The handshaker test only saw that an offer went out, so a fresh or empty
KEM offer would have passed. The manager test pins the part the resend
relies on: the same bytes while in flight, and a duplicate answered from
the responder's cache.
@0siriz 0siriz mentioned this pull request Oct 30, 2026
6 of 10 tasks
if prev, ok := m.capable[remoteID]; ok && !prev {
return // already known non-capable, nothing to do
}
m.capable[remoteID] = false

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A peer marked non-capable stays that way until RemovePeer: SignalOffer and ShouldSendBootstrapOffer refuse to offer to it, and the responder's offer carries no KEM marker that could reset it. If the peer enables ML-KEM later, this side stays classical (blocked in strict mode) until its own restart. Clear the flag on a new signalling round.

Comment thread client/internal/engine.go
e.pqkemManager = pqkem.NewManager(pqkem.LocalID(publicKey.String()), cbHandler, pqkem.NewLogger(), opts...)
// Shares the apply lock with the rotation push, so a reapply and a push are ordered.
e.pqPSKReapplier = &pqPSKReapplier{psks: e.pqkemManager, wg: e.wgInterface, applied: applied}
e.pqkemManager.Start(tr)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rosenpass gets an inbound UDP accept rule in initFirewall, guarded by e.rpManager != nil. ML-KEM disables Rosenpass, so nothing opens this port and rotation offers can be dropped by the peer ACLs. Needs a check under a restrictive policy, then the same accept rule for the PQ port.

return nil, nil
}
// Reserve the slot so a concurrent duplicate offer bails.
m.exchanges[remoteID] = &exchangeCtl{id: o.ExchangeID, state: stateReserved, gen: m.nextGenLocked(remoteID)}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A zero-AckID offer from signalling is accepted whenever its exchange ID differs from the current one. A replayed old offer after a newer bootstrap makes the responder apply a PSK the initiator never sees, until the failed rotation re-bootstraps. Low severity, needs Signal access. Reject exchange IDs older than the last committed one, or bind the offer to the ICE session.

Comment thread client/internal/pqkem/manager.go Outdated
m.mu.Lock()
defer m.mu.Unlock()
if m.established[remoteID] {
return

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An established peer is never moved back to classical. If the peer restarts without ML-KEM (rollback or disabled), this early return keeps the old PSK programmed on this side and the handshake never completes. On two containers the tunnel was still down after 4 minutes, and status kept reporting quantum resistant. An empty offer or answer from the authenticated peer is not stray, so treat it as a downgrade: drop the PSK and fall back to classical in permissive mode, stay blocked in strict mode.

A peer that disabled ML-KEM left us on its dropped PSK with the tunnel down, and one that enabled it stayed classical until our restart.
… peer

With lazy connections off, every reconnect offer to an offline peer ended in two warnings.
…all setup

The ML-KEM transport needs the same rule for its own port.
Peer ACLs that do not open the port drop every rotation offer, so rotation never succeeds.
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants