Skip to content

fix(send): serialize the group sender-key chain per (group, sender) - #657

Merged
jlucaso1 merged 1 commit into
mainfrom
audit/serialize-group-sends
May 28, 2026
Merged

fix(send): serialize the group sender-key chain per (group, sender)#657
jlucaso1 merged 1 commit into
mainfrom
audit/serialize-group-sends

Conversation

@jlucaso1

@jlucaso1 jlucaso1 commented May 28, 2026

Copy link
Copy Markdown
Collaborator

Finding (WA Web parity audit, area: send/encrypt)

Concurrent send_message() calls to the same group raced the sender-key chain. The group send path performs two chain operations -- SKDM creation (create_sender_key_distribution_message_*, which creates the key if absent) and then the skmsg encrypt (encrypt_group_message, which advances the chain) -- over a store shared via Arc<SignalStoreCache>, with no serialization between them.

  • Two concurrent first/rotated sends could each create a different sender key (A and B): one ends up distributed in the SKDM while the skmsg is encrypted under the other, so recipients install A and cannot decrypt a B-encrypted message.
  • Two concurrent steady-state sends could read the same chain iteration and emit two skmsgs at it (one becomes undecryptable / the chain desyncs).

This is reachable on any same-group concurrency (e.g. a gateway serving two requests to one group), not just flooding.

WA Web parity

WAWebSendGroupMsgJob.encryptAndSendGroupMsg runs its whole body inside WAWebSendMsgQueueMap.sendMsgQueueMap.enqueue(groupJid, ...) -- serialized per destination group JID -- because the sender-key ratchet is inherently sequential and the SKDM must match the skmsg.

Change

Serialize both chain operations as one unit, per (group, sender), with a lock owned by the cache:

  • SenderKeyStore gains sender_key_lock(name) with a default uncontended impl, so the in-memory test/bench stores need no changes. SenderKeyAdapter delegates to SignalStoreCache, which hands out one shared Arc<Mutex<()>> per chain (keyed by the same cache_key as the sender keys).
  • The orchestrators -- prepare_group_stanza and the SignalApi group-encrypt helper -- hold that lock across SKDM creation + skmsg encrypt. The cipher building blocks (encrypt_group_message, create_sender_key_distribution_message_for_group, group_encrypt) document the contract instead of self-locking, mirroring encrypt_for_devices.

The lock is held at the orchestrator (not inside each cipher) precisely so the SKDM and the skmsg can't be split across two different keys -- locking only the encrypt would leave the preceding SKDM-create unguarded.

Performance / allocation

  • The SenderKeyName is now built once per send and threaded into both the SKDM creation and the encrypt, instead of being rebuilt 2-3x -- dropping a few small-string allocations per send.
  • Same-(group, sender) lock lookups are allocation free (HashMap::get by &str via Borrow, then Arc clone). Only the first send per chain allocates the lock entry. The lock map is coordination-only (never time-evicted) and prunes idle entries when it grows past the cache bound.
  • The lock does not cover query_info or the per-device SKDM fanout sessions; different groups and DMs are unaffected.

Testing

cargo fmt, cargo clippy --all-targets -- -D warnings, cargo test -p wacore (799), cargo test -p wacore-libsignal (108) pass. Added cache tests: same name returns one shared lock (distinct names don't), and a held lock blocks a second acquire.

Known separate follow-up (not in this PR)

The SKDM fan-out calls encrypt_for_devices without the per-device session locks its contract requires; two sends to different groups sharing a recipient device can still race that pairwise session during distribution. Pre-existing, cross-group, needs sorted per-device locks with its own deadlock analysis -- tracked separately.

Draft -- from a WA Web parity audit; review independently.

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 80d858e4-0405-4eb3-b17e-296a617983be

📥 Commits

Reviewing files that changed from the base of the PR and between 2956711 and d78984b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • src/features/signal.rs
  • src/send.rs
  • src/store/signal_adapter.rs
  • wacore/libsignal/Cargo.toml
  • wacore/libsignal/src/protocol/group_cipher.rs
  • wacore/libsignal/src/protocol/storage/traits.rs
  • wacore/src/send.rs
  • wacore/src/store/signal_cache.rs

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Improved synchronization for group message sending to prevent race conditions when the same sender sends multiple messages concurrently, ensuring consistent group encryption and delivery.
  • Documentation
    • Clarified concurrency expectations around group encryption to reflect the new serialized sender-key handling.

Walkthrough

Adds per-SenderKeyName async mutexes in the cache and a SenderKeyStore::sender_key_lock trait method; callers (wacore/libsignal/features) acquire the per-sender-key lock and hold it across SKDM creation + group-message encryption to serialize sender-key chain advancement.

Changes

Sender-key chain serialization

Layer / File(s) Summary
SignalStoreCache lock map and accessor
wacore/src/store/signal_cache.rs
Adds sender_key_locks: Mutex<HashMap<Arc<str>, Arc<Mutex<()>>>>, initializes it, and exposes pub async fn sender_key_lock(&self, name: &SenderKeyName) -> Arc<Mutex<()>> that creates/returns a shared lock and prunes idle entries; includes tokio tests.
SenderKeyStore trait and workspace dep
wacore/libsignal/src/protocol/storage/traits.rs, wacore/libsignal/Cargo.toml
Adds SenderKeyStore::sender_key_lock(&self, sender_key_name: &SenderKeyName) -> Arc<async_lock::Mutex<()>> with a default unlocked mutex; adds async-lock workspace dependency.
Adapter implementation
src/store/signal_adapter.rs
SenderKeyAdapter implements sender_key_lock by delegating to SignalStoreCache::sender_key_lock.
libsignal group_encrypt doc
wacore/libsignal/src/protocol/group_cipher.rs
Documents that callers must hold sender_key_lock(sender_key_name) across group_encrypt (and any paired SKDM creation) to serialize sender-key load/advance/store.
wacore send path refactor
wacore/src/send.rs
Thread SenderKeyName through SKDM and skmsg paths, refactor encrypt_group_message/create_sender_key_distribution_message_for_group to accept &SenderKeyName, and acquire/hold the per-sender-key lock across SKDM creation + encryption.
features/signal usage
src/features/signal.rs
Acquire per-sender-key chain lock in encrypt_group_message and pass &sender_key_name into SKDM creation and encryption call sites.
Client comment
src/send.rs
Clarifies there is no send-level/client lock for group sends; sender-key-chain advancement is serialized per (group, sender) at the cipher layer.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Prepare as prepare_group_stanza
  participant Encrypt as encrypt_group_message
  participant SenderKeyStore
  participant SignalCache as SignalStoreCache

  Client->>Prepare: request group send
  Prepare->>SenderKeyStore: sender_key_lock(sender_key_name) (await)
  SenderKeyStore->>SignalCache: lookup/create Arc<async_lock::Mutex<()>>
  SignalCache-->>SenderKeyStore: Arc<async_lock::Mutex<()>>
  SenderKeyStore-->>Prepare: Arc<async_lock::Mutex<()>>
  Prepare->>Prepare: guard.lock().await (hold)
  Prepare->>Encrypt: encrypt_group_message(..., &sender_key_name, ...)
  Encrypt->>SenderKeyStore: load/advance/store sender-key (under guard)
  Encrypt-->>Client: encrypted group message(s)
  Prepare->>Prepare: guard dropped (release)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

breaking-change

Suggested reviewers

  • Ari4ka
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: serializing the group sender-key chain per (group, sender) to fix the race condition.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing the race condition found, the fix implemented, and performance implications.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch audit/serialize-group-sends

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

❤️ Share

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

@github-actions

github-actions Bot commented May 28, 2026

Copy link
Copy Markdown

Benchmark Results

67 unchanged benchmark(s)
Benchmark Current Baseline Change
reporting_token_benchmark::content_extraction_group::bench_content_extraction simple:setup_simple_message() 3,933 3,933 +0.0%
reporting_token_benchmark::content_extraction_group::bench_content_extraction extended:setup_extended_message() 12,038 12,038 +0.0%
reporting_token_benchmark::key_derivation_group::bench_key_derivation 43,514 43,514 +0.0%
reporting_token_benchmark::token_calculation_group::bench_token_calculation 19,365 19,365 +0.0%
reporting_token_benchmark::full_generation_group::bench_full_token_generation simple:setup_full_gen_simple() 68,579 68,579 +0.0%
reporting_token_benchmark::full_generation_group::bench_full_token_generation extended:setup_full_gen_extended() 76,679 76,679 +0.0%
reporting_token_benchmark::message_encoding_group::bench_message_encoding simple:setup_simple_message() 2,230 2,230 +0.0%
reporting_token_benchmark::message_encoding_group::bench_message_encoding extended:setup_extended_message() 5,988 5,988 +0.0%
send_receive_benchmark::dm_send::bench_dm_send text:setup_dm_send() 181,455 181,405 +0.0%
send_receive_benchmark::dm_recv::bench_dm_recv text:setup_dm_recv() 2,204,889 2,205,397 -0.0%
send_receive_benchmark::group_send::bench_group_send group_10:setup_group_send_10() 888,701 888,032 +0.1%
send_receive_benchmark::group_send::bench_group_send group_50:setup_group_send_50() 1,027,949 1,027,291 +0.1%
send_receive_benchmark::group_send::bench_group_send group_256:setup_group_send_256() 1,761,076 1,759,515 +0.1%
send_receive_benchmark::group_send_skdm::bench_group_send_skdm skdm_10:setup_group_skdm_10() 1,126,510 1,125,997 +0.0%
send_receive_benchmark::group_send_skdm::bench_group_send_skdm skdm_50:setup_group_skdm_50() 2,112,479 2,103,142 +0.4%
send_receive_benchmark::group_send_skdm::bench_group_send_skdm skdm_256:setup_group_skdm_256() 7,174,621 7,173,804 +0.0%
send_receive_benchmark::group_recv::bench_group_recv text:setup_group_recv() 12,679,628 12,645,806 +0.3%
binary_benchmark::marshal_group::bench_marshal_allocating 71,326 71,326 +0.0%
binary_benchmark::marshal_group::bench_marshal_auto_allocating 71,379 71,379 +0.0%
binary_benchmark::marshal_group::bench_marshal_exact_allocating 98,446 98,446 +0.0%
binary_benchmark::marshal_group::bench_marshal_reusing_buffer 78,826 78,826 +0.0%
binary_benchmark::marshal_group::bench_marshal_reusing_buffer_vec_writer 71,426 71,426 +0.0%
binary_benchmark::marshal_group::bench_marshal_long_string 7,593 7,593 +0.0%
binary_benchmark::marshal_group::bench_marshal_auto_long_string 7,636 7,636 +0.0%
binary_benchmark::marshal_group::bench_marshal_exact_long_string 9,348 9,348 +0.0%
binary_benchmark::marshal_group::bench_marshal_huge_bytes_allocating 530,583 530,583 +0.0%
binary_benchmark::marshal_group::bench_marshal_auto_huge_bytes_allocating 530,151 530,151 +0.0%
binary_benchmark::marshal_group::bench_marshal_exact_huge_bytes_allocating 531,506 531,506 +0.0%
binary_benchmark::marshal_group::bench_marshal_many_children_allocating 8,506,239 8,506,239 +0.0%
binary_benchmark::marshal_group::bench_marshal_auto_many_children_allocating 8,450,491 8,450,491 +0.0%
binary_benchmark::marshal_group::bench_marshal_exact_many_children_allocating 19,678,026 19,678,026 +0.0%
binary_benchmark::unmarshal_group::bench_unmarshal small:setup_small_marshaled() 2,468 2,468 +0.0%
binary_benchmark::unmarshal_group::bench_unmarshal large:setup_large_marshaled() 33,558 33,558 +0.0%
binary_benchmark::unpack_group::bench_unpack_uncompressed 787 787 +0.0%
binary_benchmark::unpack_group::bench_unpack_compressed 526,732 526,732 +0.0%
binary_benchmark::attr_parser_group::bench_attr_parser attr_lookup:setup_attr_marshaled() 4,986 4,986 +0.0%
binary_benchmark::roundtrip_group::bench_roundtrip small:setup_small_marshaled() 5,315 5,315 +0.0%
binary_benchmark::roundtrip_group::bench_roundtrip large:setup_large_marshaled() 61,874 61,874 +0.0%
binary_benchmark::roundtrip_group::bench_roundtrip_auto small:setup_small_marshaled() 5,347 5,347 +0.0%
binary_benchmark::roundtrip_group::bench_roundtrip_auto large:setup_large_marshaled() 61,942 61,942 +0.0%
binary_benchmark::roundtrip_group::bench_roundtrip_exact small:setup_small_marshaled() 6,734 6,734 +0.0%
binary_benchmark::roundtrip_group::bench_roundtrip_exact large:setup_large_marshaled() 85,585 85,585 +0.0%
binary_benchmark::child_iteration_group::bench_get_children_by_tag 477,570 477,570 +0.0%
binary_benchmark::jid_optimization_group::bench_jid_to_owned_access jid_access:setup_jid_heavy_marshaled() 11,563 11,563 +0.0%
numeric_attr_benchmark::bench_group::bench_baseline_u32 396 396 +0.0%
numeric_attr_benchmark::bench_group::bench_proposed_u32 120 120 +0.0%
numeric_attr_benchmark::bench_group::bench_baseline_u64 439 439 +0.0%
numeric_attr_benchmark::bench_group::bench_proposed_u64 153 153 +0.0%
numeric_attr_benchmark::bench_group::bench_baseline_i64 499 499 +0.0%
numeric_attr_benchmark::bench_group::bench_proposed_i64 162 162 +0.0%
numeric_attr_benchmark::bench_group::bench_baseline_loop_100_u64 44,624 44,624 +0.0%
numeric_attr_benchmark::bench_group::bench_proposed_loop_100_u64 16,424 16,424 +0.0%
libsignal_benchmark::dm_group::bench_dm_session_establishment setup:setup_dm_users() 17,334,726 17,218,227 +0.7%
libsignal_benchmark::dm_group::bench_dm_encrypt_first_message first_msg:setup_dm_session() 157,179 157,179 +0.0%
libsignal_benchmark::dm_group::bench_dm_decrypt_first_message decrypt_prekey:setup_dm_with_first_message() 5,513,975 5,513,975 +0.0%
libsignal_benchmark::dm_group::bench_dm_encrypt_subsequent_message subsequent:setup_established_dm_session() 157,539 157,539 +0.0%
libsignal_benchmark::group_messaging_group::bench_group_create_distribution_message create:setup_group_sender() 296,767 296,767 +0.0%
libsignal_benchmark::group_messaging_group::bench_group_encrypt_message encrypt:setup_group_with_distribution() 706,282 706,282 +0.0%
libsignal_benchmark::group_messaging_group::bench_group_decrypt_message decrypt:setup_group_with_encrypted_message() 12,648,675 12,724,427 -0.6%
libsignal_benchmark::conversation_group::bench_full_dm_conversation full:setup_conversation_data() 27,297,279 27,571,993 -1.0%
libsignal_benchmark::signature_group::bench_signature_creation sign:setup_keypair_with_message() 3,467,011 3,467,011 +0.0%
libsignal_benchmark::signature_group::bench_signature_verification verify:setup_keypair_with_message() 126,558,603 127,625,493 -0.8%
libsignal_benchmark::signature_group::bench_key_generation keygen 2,830,452 2,830,452 +0.0%
libsignal_benchmark::session_optimization_group::bench_decrypt_with_previous_session previous_session:setup_with_archived_sessions() 46,566 46,566 +0.0%
libsignal_benchmark::session_optimization_group::bench_out_of_order_decryption out_of_order:setup_out_of_order_messages() 5,197,012 5,197,012 +0.0%
libsignal_benchmark::session_optimization_group::bench_promote_matching_session promote:setup_promote_matching_session() 360,648 360,648 +0.0%
libsignal_benchmark::session_optimization_group::bench_message_key_eviction eviction:setup_message_key_eviction() 14,255,917 14,255,917 +0.0%
No significant changes detected.

@jlucaso1
jlucaso1 marked this pull request as ready for review May 28, 2026 22:18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 50e727728f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/send.rs Outdated
// JID keys ("...@g.us") can't collide with the per-device protocol
// addresses or bare user JIDs also stored in session_locks.
let group_send_mutex = self.session_lock_for(&to.to_string()).await;
let _group_send_guard = group_send_mutex.lock().await;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Hold the group send lock until the send completes

The guard acquired here is scoped only to the to.is_group() branch that builds stanza_to_send, so it is dropped before the common send_node(...) and update_sender_key_devices(...) code below runs. When the first send to a group has to distribute an SKDM, a second same-group send can acquire this lock after the first stanza is built but before the first is sent/marked, build a newer SKDM from the already-advanced sender-key iteration, and even reach the socket first; recipients that learn the chain at iteration N+1 then treat the earlier iteration N message as a duplicate/too old. To actually mirror the per-group send queue described in the comment, the same-group serialization needs to cover the network send and SKDM bookkeeping, not just encryption/stanza construction.

Useful? React with 👍 / 👎.

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown

Actionable comments posted: 0

@jlucaso1
jlucaso1 force-pushed the audit/serialize-group-sends branch 3 times, most recently from a7f965d to 2956711 Compare May 28, 2026 23:28
@jlucaso1 jlucaso1 changed the title fix(send): serialize concurrent sends to the same group fix(send): serialize the group sender-key chain advance at the cipher May 28, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2956711b5f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread wacore/libsignal/src/protocol/group_cipher.rs Outdated
Concurrent send_message() calls to the same group raced the sender-key
chain. The send path is two chain operations - SKDM creation (creates the
key if absent) then skmsg encrypt (advances the chain) - over a store
shared via Arc<SignalStoreCache>, with no lock between them. Two concurrent
first/rotated sends could create different keys (A and B), distribute one in
the SKDM and encrypt the skmsg under the other, so recipients install A and
cannot decrypt a B-encrypted message; steady-state sends could likewise
reuse a chain iteration.

Serialize both chain operations as one unit, per (group, sender), with a
lock owned by the cache:

- SenderKeyStore gains sender_key_lock (default uncontended, so the
  in-memory test/bench stores are unchanged); SenderKeyAdapter delegates to
  SignalStoreCache, which hands out one shared lock per chain keyed by the
  same cache_key as the sender keys.
- The orchestrators (prepare_group_stanza and the SignalApi group-encrypt
  helper) hold that lock across SKDM creation + skmsg encrypt. The cipher
  building blocks (encrypt_group_message, create_sender_key_distribution_*,
  group_encrypt) document the contract instead of self-locking, mirroring
  encrypt_for_devices.

The SenderKeyName is now built once per send and threaded into both the
SKDM creation and the encrypt instead of being rebuilt 2-3x, dropping a few
per-send small-string allocations. Same-name lock lookups are allocation
free (HashMap::get by &str + Arc clone); only the first send per chain
allocates the lock entry. The lock does not cover query_info or the
SKDM per-device fanout sessions (the latter is a separate, pre-existing
per-device-session concern tracked separately).
@jlucaso1
jlucaso1 force-pushed the audit/serialize-group-sends branch from 2956711 to d78984b Compare May 28, 2026 23:42
@jlucaso1 jlucaso1 changed the title fix(send): serialize the group sender-key chain advance at the cipher fix(send): serialize the group sender-key chain per (group, sender) May 28, 2026
@jlucaso1
jlucaso1 merged commit 57ce9a9 into main May 28, 2026
9 checks passed
@jlucaso1
jlucaso1 deleted the audit/serialize-group-sends branch May 28, 2026 23:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant