derec-library 0.0.9

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! Unpair flow handlers — initiator side ([`start`], [`on_response`])
//! and responder side ([`accept`], [`reject`]).
//!
//! # Security: response replay is harmless by design
//!
//! The on-wire [`UnpairResponseMessage`] carries no nonce or
//! request-id binding, and the primitive's
//! [`crate::primitives::unpairing::response::extract`] only checks
//! the envelope/body timestamp equality (not freshness). A captured
//! `OK` response can therefore be re-decoded indefinitely under the
//! long-lived channel key. This flow nevertheless tolerates replay
//! safely because:
//!
//! 1. **Per-channel pending-unpair guard.** [`on_response`] requires
//!    a matching [`crate::protocol::StateItem::PendingUnpair`] row in
//!    the state store (written by [`start`] under
//!    [`crate::protocol::UnpairAck::Required`]) and consumes it via
//!    [`crate::protocol::DeRecStateStore::remove`], which returns
//!    `Ok(true)` iff a row was actually deleted. A replayed response
//!    after the entry has already been consumed sees a `false` return
//!    and yields [`DeRecEvent::NoOp`] — no state is touched.
//! 2. **Destructive-idempotent teardown.** When a pending entry is
//!    present, the response IS legitimate (or indistinguishable
//!    from one) and [`drop_channel_state`] runs. That function only
//!    deletes per-`(secret_id, channel_id)` rows whose store
//!    [`crate::protocol::DeRecChannelStore::remove`] /
//!    [`crate::protocol::DeRecShareStore::remove_channel`] /
//!    [`crate::protocol::DeRecSecretStore::remove`] contracts are
//!    explicitly idempotent — running them twice on the same key
//!    converges to the same end state as running them once.
//! 3. **Channel-id freshness across re-pair.** After teardown the
//!    `channel_id` is gone from the channel store; any future pair
//!    handshake mints a fresh cryptographically-derived id, so a
//!    stale response cannot accidentally target a newly-paired
//!    channel.
//!
//! The worst case under replay is therefore "unpair a channel that's
//! already unpaired" — the same end state the legitimate flow
//! produces. No cross-request satisfaction is possible because the
//! pending-unpair state store row is keyed by `channel_id` and the
//! response envelope is routed by channel id at the stores.transport layer.

use super::super::{
    DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecStateStore,
    DeRecTransport, PendingAction, SecretKind, SecretValue, StateItem, StateKey, events::UnpairAck,
};
use super::replicas::unpairing as replica;
use crate::derec_message::current_timestamp;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::extensions::message_body::{MessageBodyExt as _, Route};
use crate::protocol::context::{Exchange, Local, Round};
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::{ChannelQuery, ChannelRecord, ChannelStatus};
use crate::{
    Error, Result,
    primitives::unpairing::{
        request::produce as produce_unpair_request,
        response::{self as unpairing_response, process as process_unpair_response},
    },
    types::ChannelId,
};
use derec_proto::{
    DeRecResult, MessageBody, SenderKind, StatusEnum, UnpairRequestMessage, UnpairResponseMessage,
};

/// Route an inbound unpair message.
///
/// On the initiator side under [`crate::protocol::UnpairAck::Required`],
/// the [`crate::protocol::DeRecStateStore::remove`] of the
/// `PendingUnpair` row is the flow's replay guard: an `UnpairResponse`
/// is acted on only while a matching outbound `UnpairRequest` is still
/// in flight for that `channel_id`. `remove` returning `false` means no
/// row existed, so the response — legitimate, stale, or replayed, a
/// distinction the primitive alone cannot make (see the module-level
/// Security section) — falls through to [`DeRecEvent::NoOp`] without
/// mutating any state.
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
pub(in crate::protocol) async fn handle<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    inner: MessageBody,
) -> Result<Vec<DeRecEvent>> {
    match (inner.route(), inner) {
        (Route::Replica(target), inner) => replica::handle(stores, local, target, inner).await,
        (_, MessageBody::UnpairRequest(request)) => {
            stores
                .channels
                .require_role(local.secret_id, &[exchange.channel_id], SenderKind::Owner)
                .await?;
            on_request(exchange, request)
        }
        (_, MessageBody::UnpairResponse(response)) => {
            on_response(stores, local, exchange, &response).await
        }
        _ => Err(Error::Invariant(
            "unexpected MessageBody variant in unpairing handler",
        )),
    }
}

#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = round.trace_id)))]
pub(in crate::protocol) async fn start<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
    memo: Option<String>,
    unpair_ack: UnpairAck,
    now: u64,
    round: &Round<'_>,
) -> Result<Vec<DeRecEvent>> {
    let secret_id = local.secret_id;
    let memo_str = memo.unwrap_or_default();
    let mut events = vec![DeRecEvent::UnpairStarted {
        channel_id,
        trace_id: round.trace_id,
    }];

    let shared_key = match stores
        .secrets
        .load(secret_id, channel_id, SecretKind::SharedKey)
        .await?
    {
        Some(SecretValue::SharedKey(k)) => k,
        _ => {
            return Err(crate::Error::InvalidInput(
                "channel has no shared key — not yet paired",
            ));
        }
    };

    // Helper unpair: no member is named, which is what marks this the
    // owner ↔ helper path rather than a replica-group removal.
    let request = produce_unpair_request(channel_id, &memo_str, &shared_key, round.reply_to, None)?;
    let envelope = crate::derec_message::apply_trace_id(&request.envelope, round.trace_id)?;
    let endpoint = stores
        .channels
        .peer_endpoints(secret_id, channel_id)
        .await?;
    stores.transport.send(&endpoint, envelope).await?;

    match unpair_ack {
        UnpairAck::NotRequired => {
            drop_channel_state(stores, local, channel_id).await?;
            events.push(DeRecEvent::Unpaired { channel_id });
        }
        UnpairAck::Required => {
            stores
                .state
                .save(
                    secret_id,
                    StateItem::PendingUnpair {
                        channel_id,
                        started_at: now,
                    },
                )
                .await?;
            // Written after the pending row, so an `Unpairing` channel always
            // has one and the acknowledgement timeout always reaches it.
            set_status(
                stores,
                local,
                channel_id,
                ChannelStatus::Paired,
                ChannelStatus::Unpairing,
            )
            .await?;
        }
    }

    #[cfg(feature = "logging")]
    tracing::debug!(
        channel_id = channel_id.0,
        ack = ?unpair_ack,
        "unpair request sent"
    );

    Ok(events)
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
pub(in crate::protocol) async fn accept<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    request: &UnpairRequestMessage,
) -> Result<Vec<DeRecEvent>> {
    let channel_id = exchange.channel_id;
    let resp = unpairing_response::produce(channel_id, exchange.shared_key)?;
    let envelope = crate::derec_message::apply_trace_id(&resp.envelope, exchange.trace_id)?;
    let endpoint = stores
        .channels
        .resolve_response_endpoints(
            local.secret_id,
            channel_id,
            local.policy,
            &crate::extensions::advertised_endpoints::reply_to_owned(request),
        )
        .await?;
    let sent = crate::protocol::obligation::deliver(
        exchange.obligation,
        stores.transport,
        &endpoint,
        envelope,
        StatusEnum::Ok,
        "",
    )
    .await;
    if sent.is_err() && !crate::protocol::obligation::attempted(exchange.obligation) {
        return sent.map(|()| Vec::new());
    }

    // The acknowledgement is out, so the peer may already have dropped its
    // side: the local state goes too, and a failure from here on is
    // reported after `Unpaired`, never answered a second time.
    let dropped = drop_channel_state(stores, local, channel_id).await;

    #[cfg(feature = "logging")]
    tracing::info!("unpair accepted; local state dropped");

    crate::protocol::obligation::reported(
        exchange.obligation,
        vec![DeRecEvent::Unpaired { channel_id }],
        sent.and(dropped),
    )
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0, status = status as i32))
)]
pub(in crate::protocol) async fn reject<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    request: &UnpairRequestMessage,
    status: StatusEnum,
    memo: &str,
) -> Result<()> {
    crate::extensions::channel_store::send_channel_message(
        stores.channels,
        stores.transport,
        local.secret_id,
        exchange.channel_id,
        failure_response(status, memo),
        exchange.shared_key,
        exchange.trace_id,
        local.policy,
        &crate::extensions::advertised_endpoints::reply_to_owned(request),
        exchange.obligation,
        status,
        memo,
    )
    .await
}

/// The `UnpairResponse` that answers an unpair request with a non-`Ok`
/// `status`; the channel is kept.
pub(in crate::protocol) fn failure_response(status: StatusEnum, memo: &str) -> MessageBody {
    MessageBody::UnpairResponse(UnpairResponseMessage {
        result: Some(DeRecResult {
            status: status as i32,
            memo: memo.to_owned(),
        }),
        timestamp: Some(current_timestamp()),
    })
}

pub(in crate::protocol) async fn drop_channel_state<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
) -> Result<()> {
    let secret_id = local.secret_id;
    stores.shares.remove_channel(secret_id, channel_id).await?;

    let _ = stores
        .secrets
        .remove(secret_id, channel_id, SecretKind::SharedKey)
        .await;
    let _ = stores
        .secrets
        .remove(secret_id, channel_id, SecretKind::PairingSecret)
        .await;
    let _ = stores
        .secrets
        .remove(secret_id, channel_id, SecretKind::PairingContact)
        .await;

    let _ = stores
        .channels
        .remove(
            secret_id,
            crate::protocol::types::ChannelQuery::Helper { channel_id },
        )
        .await?;
    Ok(())
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
fn on_request(exchange: &Exchange<'_>, request: UnpairRequestMessage) -> Result<Vec<DeRecEvent>> {
    Ok(vec![DeRecEvent::ActionRequired {
        channel_id: exchange.channel_id,
        action: PendingAction::Unpair {
            channel_id: exchange.channel_id,
            request,
            shared_key: *exchange.shared_key,
            trace_id: exchange.trace_id,
        },
    }])
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
async fn on_response<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    response: &UnpairResponseMessage,
) -> Result<Vec<DeRecEvent>> {
    if !stores
        .state
        .remove(
            local.secret_id,
            StateKey::PendingUnpair {
                channel_id: exchange.channel_id,
            },
        )
        .await?
    {
        return Ok(vec![DeRecEvent::NoOp]);
    }

    match process_unpair_response(response) {
        Ok(_) => {
            drop_channel_state(stores, local, exchange.channel_id).await?;
            Ok(vec![DeRecEvent::Unpaired {
                channel_id: exchange.channel_id,
            }])
        }
        Err(Error::Unpairing(crate::primitives::unpairing::UnpairingError::NonOkStatus {
            status,
            memo,
        })) => {
            set_status(
                stores,
                local,
                exchange.channel_id,
                ChannelStatus::Unpairing,
                ChannelStatus::Paired,
            )
            .await?;
            Ok(vec![DeRecEvent::UnpairRejected {
                channel_id: exchange.channel_id,
                status,
                memo,
            }])
        }
        Err(e) => Err(e),
    }
}

/// Move a helper channel from `from` to `to`, leaving any other status alone.
///
/// Only a `Paired` channel becomes `Unpairing`: one still `Pending` is
/// already excluded from every flow, and a rejection must not promote it.
async fn set_status<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
    from: ChannelStatus,
    to: ChannelStatus,
) -> Result<()> {
    let Some(mut helper) = stores
        .channels
        .load(local.secret_id, ChannelQuery::Helper { channel_id })
        .await?
        .and_then(|record| record.as_helper().cloned())
        .filter(|helper| helper.status == from)
    else {
        return Ok(());
    };
    helper.status = to;
    stores
        .channels
        .save(local.secret_id, ChannelRecord::Helper(helper))
        .await?;
    Ok(())
}