Skip to content
5 changes: 5 additions & 0 deletions wacore/libsignal/src/protocol/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ pub enum SignalProtocolError {
#[source] Box<dyn std::error::Error + Send + Sync>,
),

/// A verified bundle changed local state, but its store could not finalize it.
/// Callers must abort the surrounding batch rather than skip this device.
#[error("prekey bundle local finalization failed")]
PreKeyBundleFinalizationFailed(#[source] Box<SignalProtocolError>),

#[error("protobuf encoding was invalid")]
InvalidProtobufEncoding,

Expand Down
14 changes: 13 additions & 1 deletion wacore/libsignal/src/protocol/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,23 @@ pub async fn process_prekey_bundle<R: Rng + CryptoRng>(
.await;

if had_session || result.is_ok() {
session.commit().await?;
// Identity writes can already be pending when checkout storage fails.
// Fan-out must discard that batch, just as for an acceptance-hook failure.
session.commit().await.map_err(|error| {
SignalProtocolError::PreKeyBundleFinalizationFailed(Box::new(error))
Comment thread
purpshell marked this conversation as resolved.
Resolved
})?;
} else {
session.discard();
}

if result.is_ok() {
session_store
.on_prekey_bundle_accepted(remote_address, their_identity_key)
.await
.map_err(|error| {
SignalProtocolError::PreKeyBundleFinalizationFailed(Box::new(error))
})?;
}
result
}

Expand Down
13 changes: 13 additions & 0 deletions wacore/libsignal/src/protocol/storage/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,19 @@ pub trait SessionStore: ThreadSafe {
/// Destructive cache checkouts belong in `load_session_for_update`.
async fn load_session(&self, address: &ProtocolAddress) -> Result<Option<SessionRecord>>;

/// Finish local state work after a verified prekey bundle is accepted.
/// Scoped stores can invalidate sibling ratchets in the same transaction.
/// The default leaves existing unscoped stores unchanged. This hook must
/// not publish ciphertext or perform network work.
async fn on_prekey_bundle_accepted(
&mut self,
address: &ProtocolAddress,
identity: &IdentityKey,
) -> Result<()> {
let _ = (address, identity);
Ok(())
}

/// Hint to fault `addresses` into the store in one backend round-trip.
///
/// A send fans out over every device, and without this each device pays its
Expand Down
109 changes: 109 additions & 0 deletions wacore/libsignal/tests/counter_lease.rs
Original file line number Diff line number Diff line change
Expand Up @@ -900,3 +900,112 @@ fn waiving_burns_the_ceiling_into_archived_states_too() {
.index;
assert_eq!(archived_index, Some(ceiling));
}

struct BundleCommitStore {
inner: InMemorySessionStore,
fail_commit: bool,
accepted: usize,
}

#[async_trait]
impl SessionStore for BundleCommitStore {
async fn load_session(
&self,
address: &ProtocolAddress,
) -> wacore_libsignal::protocol::error::Result<Option<SessionRecord>> {
self.inner.load_session(address).await
}

async fn has_session(
&self,
address: &ProtocolAddress,
) -> wacore_libsignal::protocol::error::Result<bool> {
self.inner.has_session(address).await
}

async fn store_session(
&mut self,
address: &ProtocolAddress,
record: SessionRecord,
) -> wacore_libsignal::protocol::error::Result<()> {
if self.fail_commit {
return Err(SignalProtocolError::BackendError(
"authored session commit failure",
std::io::Error::other("authored unavailable session store").into(),
));
}
self.inner.store_session(address, record).await
}

async fn on_prekey_bundle_accepted(
&mut self,
_address: &ProtocolAddress,
_identity: &IdentityKey,
) -> wacore_libsignal::protocol::error::Result<()> {
self.accepted += 1;
Ok(())
}
}

#[test]
fn bundle_commit_errors_require_the_enclosing_batch_to_abort() {
let mut initiator = Peer::new("authored-commit-initiator");
let target = Peer::new("authored-commit-target");
let bundle = BUNDLES.with(|b| b.borrow().get(&target.address).cloned().unwrap());
let mut store = BundleCommitStore {
inner: InMemorySessionStore::default(),
fail_commit: true,
accepted: 0,
};
let mut rng = rand::make_rng::<rand::rngs::StdRng>();
let error = futures::executor::block_on(process_prekey_bundle(
&target.address,
&mut store,
&mut initiator.identity_store,
&bundle,
&mut rng,
UsePQRatchet::No,
))
.unwrap_err();
// Identity storage precedes checkout commit. Fan-out must discard this
// pending identity instead of treating the device as an ordinary drop.
assert_eq!(
initiator.identity_store.identities.get(&target.address),
Some(bundle.identity_key().unwrap())
);
assert_eq!(store.accepted, 0);
assert!(store.inner.0.is_empty());
match error {
SignalProtocolError::PreKeyBundleFinalizationFailed(cause) => {
assert!(matches!(
*cause,
SignalProtocolError::BackendError("authored session commit failure", _)
));
}
other => panic!("commit failure did not require batch abort: {other}"),
}
}

#[test]
fn a_successful_bundle_commit_runs_acceptance_once() {
let mut initiator = Peer::new("authored-success-initiator");
let target = Peer::new("authored-success-target");
let bundle = BUNDLES.with(|b| b.borrow().get(&target.address).cloned().unwrap());
let mut store = BundleCommitStore {
inner: InMemorySessionStore::default(),
fail_commit: false,
accepted: 0,
};
let mut rng = rand::make_rng::<rand::rngs::StdRng>();
futures::executor::block_on(process_prekey_bundle(
&target.address,
&mut store,
&mut initiator.identity_store,
&bundle,
&mut rng,
UsePQRatchet::No,
))
.unwrap();
assert_eq!(store.accepted, 1);
assert!(store.inner.0.contains_key(&target.address));
}
69 changes: 66 additions & 3 deletions wacore/signal-ops/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,73 @@ impl OpsError {
pub fn is_fence_lost(&self) -> bool {
match self {
OpsError::Store(e) => state_is_refused(e),
OpsError::Signal(SignalProtocolError::BackendError(_, source)) => source
.downcast_ref::<StoreError>()
.is_some_and(state_is_refused),
OpsError::Signal(error) => signal_state_is_refused(error),
_ => false,
}
}
}

fn signal_state_is_refused(error: &SignalProtocolError) -> bool {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(error);
while let Some(current) = source {
if current
.downcast_ref::<StoreError>()
.is_some_and(state_is_refused)
{
return true;
}
source = current.source();
}
false
}

#[cfg(test)]
mod tests {
use super::*;

fn wrapped_backend(source: StoreError, depth: usize) -> OpsError {
let mut error = SignalProtocolError::BackendError("authored store", Box::new(source));
for _ in 0..depth {
error = SignalProtocolError::PreKeyBundleFinalizationFailed(Box::new(error));
}
OpsError::Signal(error)
}

#[test]
fn finalization_preserves_lost_fence_and_interrupted_state() {
for depth in [0, 1, 3] {
let lost = wacore_recordstore::FenceLost {
scope: "authored-fence-classification".into(),
generation: 7,
}
.into_store_error();
assert!(
wrapped_backend(lost, depth).is_fence_lost(),
"lost fence at depth {depth}"
);
let OpsError::Store(interrupted) = interrupted_operation() else {
unreachable!()
};
assert!(
wrapped_backend(interrupted, depth).is_fence_lost(),
"interrupted state at depth {depth}"
);
}
}

#[test]
fn finalization_keeps_ordinary_failures_distinct_from_state_refusal() {
for depth in [0, 1, 3] {
let io = StoreError::Io(std::io::Error::other("authored ordinary I/O error"));
assert!(!wrapped_backend(io, depth).is_fence_lost());
}
assert!(
!OpsError::Signal(SignalProtocolError::PreKeyBundleFinalizationFailed(
Box::new(SignalProtocolError::InvalidArgument(
"authored input failure".into()
),)
))
.is_fence_lost()
);
}
}
68 changes: 60 additions & 8 deletions wacore/signal-ops/src/inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ pub enum Received {
/// Delivered before; the client only needs to send its receipt again.
AlreadyDelivered {
receipt_key: String,
/// Classification retained in the delivered marker, without plaintext.
group_status_wrapper: Option<bool>,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
}

Expand All @@ -75,7 +77,7 @@ pub struct ReceivedMessage {
pub app_state_key_share: Option<wa::message::AppStateSyncKeyShare>,
}

fn receipt_key(request: &ReceiveRequest<'_>) -> String {
fn receipt_key(request: &ReceiveRequest<'_>, status_session: bool) -> String {
let mut hasher = Sha256::new();
for part in [
request.kind.as_str().as_bytes(),
Expand All @@ -85,6 +87,9 @@ fn receipt_key(request: &ReceiveRequest<'_>) -> String {
hasher.update(part);
hasher.update([0]);
}
if status_session {
hasher.update(b"status-session\0");
}
hasher.update(request.ciphertext);
hex::encode(hasher.finalize())
}
Expand Down Expand Up @@ -129,13 +134,17 @@ impl BufferEntry {
})
}

fn delivered(inserted_ms: u64) -> Self {
fn delivered(inserted_ms: u64, group_status_wrapper: Option<bool>) -> Self {
Self {
state: STATE_DELIVERED,
padding_version: 0,
identity_changed: false,
inserted_ms,
padded_plaintext: Vec::new(),
// A delivered marker never carries message content. Older readers
// ignore its trailing metadata; empty legacy markers stay unknown.
padded_plaintext: group_status_wrapper
.map(|flag| vec![u8::from(flag)])
.unwrap_or_default(),
}
}
}
Expand Down Expand Up @@ -183,7 +192,31 @@ impl<S: ServiceStore> SignalOps<S> {
/// Decrypt, buffer and classify one received payload. Sender-key
/// distributions inside it are stored in the same batch as the decrypt.
pub async fn receive(&self, request: ReceiveRequest<'_>) -> Result<Received, OpsError> {
let receipt_key = receipt_key(&request);
self.receive_scoped(request, false).await
}

/// Receive a status using a separate pairwise session when selected by
/// the caller's served configuration. Identity/prekeys and sender keys
/// remain shared. This does not enable status publishing.
pub async fn receive_status(
&self,
request: ReceiveRequest<'_>,
status_session: bool,
) -> Result<Received, OpsError> {
if status_session && request.kind == ReceiveKind::SenderKey {
return Err(OpsError::InvalidInput(
"sender keys cannot use a pairwise status session".into(),
));
}
self.receive_scoped(request, status_session).await
}

async fn receive_scoped(
&self,
request: ReceiveRequest<'_>,
status_session: bool,
) -> Result<Received, OpsError> {
let receipt_key = receipt_key(&request, status_session);
// Pairwise payloads can carry a sender-key distribution for this chat,
// so they also lock the sender's chain.
let chain = chain_key(request.chat, request.sender.as_str());
Expand All @@ -200,7 +233,14 @@ impl<S: ServiceStore> SignalOps<S> {
{
let entry = BufferEntry::decode(bytes)?;
if entry.state == STATE_DELIVERED {
return Ok(Received::AlreadyDelivered { receipt_key });
return Ok(Received::AlreadyDelivered {
receipt_key,
group_status_wrapper: match entry.padded_plaintext.as_slice() {
[0] => Some(false),
[1] => Some(true),
_ => None,
},
});
}
let content = classify(
&entry.padded_plaintext,
Expand All @@ -226,7 +266,13 @@ impl<S: ServiceStore> SignalOps<S> {
EncKind::Message
};
let decrypted = self
.decrypt_into(&staged, request.sender, kind, request.ciphertext)
.decrypt_into_scoped(
&staged,
request.sender,
kind,
request.ciphertext,
status_session,
)
.await?;
(decrypted.plaintext, decrypted.identity_changed)
}
Expand All @@ -252,7 +298,7 @@ impl<S: ServiceStore> SignalOps<S> {
.put_aux(
Namespace::DecryptBuffer,
&receipt_key,
&BufferEntry::delivered(inserted_ms).encode(),
&BufferEntry::delivered(inserted_ms, None).encode(),
)
.await?;
staged.commit().await?;
Expand Down Expand Up @@ -317,7 +363,13 @@ impl<S: ServiceStore> SignalOps<S> {
.put_aux(
Namespace::DecryptBuffer,
receipt_key,
&BufferEntry::delivered(entry.inserted_ms).encode(),
&BufferEntry::delivered(
entry.inserted_ms,
classify(&entry.padded_plaintext, entry.padding_version, true)
.ok()
.map(|content| content.message.group_status_message_v2.is_set()),
)
.encode(),
)
.await?;
}
Expand Down
Loading
Loading