From 0de5f7b220570ac07b9b20c5120124c22eacf995 Mon Sep 17 00:00:00 2001 From: Hermes rust-dev Date: Sat, 12 Sep 2026 15:16:38 -0400 Subject: [PATCH] fix(sdk): surface Sent/Queued on send(), and build the SDK in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Node::send()` became `Result` in the local-outbox work, which broke `crates/onionwire-sdk` (E0308 at src/lib.rs:195) — and nothing noticed, because the SDK is a separate cargo workspace that root CI never compiles and android-release.yml only builds on a v*.*.* tag. - `Wire::send()` now returns `WResult` (`Sent` | `Queued`) instead of swallowing the outcome as `()`. A queued send is local-only until the retry worker gets a circuit through, so the Kotlin boundary must be able to tell it apart from a delivered one. - `ChatMessage` gains `delivery: Option` ("sent" | "queued" | "sending" | "failed: "), populated from the message's outbox row; `None` for incoming messages. An outgoing row with no outbox row was accepted on the first attempt, so it reads "sent". - New `sdk` job in `.forgejo/workflows/ci.yml`: `cargo test --locked` + `cargo clippy --locked --all-targets -- -D warnings` in `crates/onionwire-sdk` in the same rust:1.91-bookworm container, with its own target volume (the SDK resolves the root crate with rustls, so sharing the root job's target dir would thrash feature-unified artifacts). - Drift found while un-rotting it: the SDK `Cargo.lock` was stale (missing `sha2`, added to the root crate by the zeroize work), so `--locked` failed; and the SDK README still said "no outbox, no spool in v1" and "identity keys in sqlite are plaintext", both untrue since the outbox and SQLCipher landed. Tests: crates/onionwire-sdk 4 passed (2 new unit tests over the status mapping), clippy clean; root `cargo test --locked` clean. The CI job body was smoke-run locally in the same container image before being committed. --- .forgejo/workflows/ci.yml | 46 +++++++++++ README.md | 2 +- crates/onionwire-sdk/Cargo.lock | 1 + crates/onionwire-sdk/README.md | 20 +++-- crates/onionwire-sdk/src/lib.rs | 138 +++++++++++++++++++++++++++++--- 5 files changed, 188 insertions(+), 19 deletions(-) diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 4c7b8aa..d922dfe 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -39,6 +39,11 @@ env: CARGO_REGISTRY_VOLUME: onionwire-cargo-registry CARGO_TARGET_VOLUME: onionwire-target-ci BUILD_CONTAINER: onionwire-ci-${{ github.run_id }} + # The SDK job gets its own target volume: it resolves the root crate with + # `rustls` instead of `native-tls`, so sharing a target dir would thrash both + # jobs' feature-unified artifacts. + SDK_CARGO_TARGET_VOLUME: onionwire-target-ci-sdk + SDK_BUILD_CONTAINER: onionwire-ci-sdk-${{ github.run_id }} jobs: test: @@ -73,3 +78,44 @@ jobs: tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees . \ | docker start -a -i "$BUILD_CONTAINER" docker rm -f "$BUILD_CONTAINER" > /dev/null + + # `crates/onionwire-sdk` is a SEPARATE cargo workspace: its own Cargo.lock and + # a path dependency on the root crate, resolved with `rustls` instead of + # `native-tls`. The `test` job above therefore never compiles it, so a + # root-crate signature change (`Node::send` gaining the outbox result, the + # SQLCipher passphrase entry points) breaks the Android SDK — and the tagged + # release AAR, since android-release.yml only builds on `v*.*.*` — while both + # the root suites and local `cargo test` stay green. Build it here. + sdk: + runs-on: docker + timeout-minutes: 120 + steps: + - name: Checkout + uses: https://code.forgejo.org/actions/checkout@v4 + + - name: cargo test + clippy for crates/onionwire-sdk on aarch64 + run: | + set -euo pipefail + cd "${GITHUB_WORKSPACE}" + echo "workspace: $GITHUB_WORKSPACE" + docker volume create "$CARGO_REGISTRY_VOLUME" > /dev/null + docker volume create "$SDK_CARGO_TARGET_VOLUME" > /dev/null + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null 2>&1 || true + docker create --name "$SDK_BUILD_CONTAINER" -i \ + -e CARGO_TARGET_DIR=/target \ + -e CARGO_BUILD_JOBS=2 \ + -e CARGO_TERM_COLOR=never \ + -v "$CARGO_REGISTRY_VOLUME":/usr/local/cargo/registry \ + -v "$SDK_CARGO_TARGET_VOLUME":/target \ + -w /src \ + "$RUST_IMAGE" \ + sh -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src/crates/onionwire-sdk \ + && apt-get update \ + && apt-get install -y --no-install-recommends pkg-config libssl-dev \ + && rustup component add clippy \ + && cargo test --locked \ + && cargo clippy --locked --all-targets -- -D warnings' + tar czf - --exclude=./target --exclude=./.git --exclude=./.worktrees \ + --exclude=./crates/onionwire-sdk/target . \ + | docker start -a -i "$SDK_BUILD_CONTAINER" + docker rm -f "$SDK_BUILD_CONTAINER" > /dev/null diff --git a/README.md b/README.md index 82aeb2c..c755ba9 100644 --- a/README.md +++ b/README.md @@ -289,7 +289,7 @@ FORGEJO_TOKEN= scripts/build-release-local.sh vX.Y.Z Workflows (Forgejo Actions, `.forgejo/workflows/`): -- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. Pi runner, `docker` label. +- [`.forgejo/workflows/ci.yml`](.forgejo/workflows/ci.yml) — two jobs, both on the Pi runner (`docker` label), serialized by the `onionwire-ci-pi` concurrency group. `test`: `cargo test --locked` + `cargo clippy --all-targets -- -D warnings` at the repo root. `sdk`: the same for `crates/onionwire-sdk`, which is a separate cargo workspace (own `Cargo.lock`, root crate by path, `rustls` instead of `native-tls`) and therefore never gets compiled by the root job — without it a root-crate signature change would silently break the Android SDK and the tagged release AAR. Both run on `main` and PRs when `src/`, `crates/`, `tests/`, `Cargo.toml`, `Cargo.lock`, or this workflow change (ignored Tor-live tests are not run). `workflow_dispatch` always runs the suite. - [`.forgejo/workflows/release.yml`](.forgejo/workflows/release.yml) — on core paths to `main` (`src/`, `crates/`, `Cargo.toml`, `Cargo.lock`, `scripts/release-body.md`): next tag, aarch64 (`docker`) + x86_64 (`docker-amd64`), one release. `workflow_dispatch` rebuilds a tag or `dry_run`s. Concurrency group `onionwire-ci-pi` (same as `ci.yml`, `cancel-in-progress: false`) so cargo jobs do not overlap on the Pi. Amd64 dind is serialized by runner `capacity=1`. Scripts: diff --git a/crates/onionwire-sdk/Cargo.lock b/crates/onionwire-sdk/Cargo.lock index 0422aac..c1867ab 100644 --- a/crates/onionwire-sdk/Cargo.lock +++ b/crates/onionwire-sdk/Cargo.lock @@ -2774,6 +2774,7 @@ dependencies = [ "rusqlite", "safelog", "serde_json", + "sha2", "sha3 0.10.9", "snow", "tokio", diff --git a/crates/onionwire-sdk/README.md b/crates/onionwire-sdk/README.md index 36e25a5..9072542 100644 --- a/crates/onionwire-sdk/README.md +++ b/crates/onionwire-sdk/README.md @@ -18,8 +18,8 @@ onions directly. There is no `tor` binary, no torrc, no Orbot as the pipe. | Onion | A **locator**, not an identity. It rotates. | | Invite | `onionwire:v1:k=…:o=…:spk=…:sig=…` | | Crypto | Noise IK (`Noise_IK_25519_ChaChaPoly_BLAKE2s`). `spk` is x25519. | -| Fail closed | Peer onion down → the send fails. No outbox, no spool in v1. | -| At rest | Chat bodies encrypted (Argon2id wrap + ChaCha20-Poly1305). Identity keys in sqlite are plaintext — that is honest, not an oversight. | +| Chat send | Unreachable peer onion → the message goes to the **local outbox** and is retried with backoff. `send()` returns `SendState.Sent` or `SendState.Queued`. File transfer and payments stay fail-closed. | +| At rest | The whole sqlite file is SQLCipher (key = Argon2id of the store passphrase), and chat bodies carry a second per-row ChaCha20-Poly1305 layer with row-bound AAD. Identity keys live in that same encrypted file. | ### Invite string @@ -66,8 +66,10 @@ Requirements: ## Kotlin surface -Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes, -and a send retries the peer for up to 3 minutes before failing. +Everything is a `suspend fun` — Arti bootstrap and onion publish take minutes. +A send that cannot reach the peer comes back immediately as `QUEUED` (it is not +a long retry inside the call): the message is stored locally and a background +worker in the core keeps retrying it. ```kotlin import uniffi.onionwire_sdk.* @@ -88,8 +90,16 @@ val friend: FriendInfo = wire.addFriend(pasted) // 4. Roster and chat. val roster: List = wire.friends() wire.setPetname(friend.pubkeyHex, "ada") -wire.send(friend.pubkeyHex, "hello wire") +when (wire.send(friend.pubkeyHex, "hello wire")) { + SendState.SENT -> { /* the peer's onion took the frame */ } + SendState.QUEUED -> { /* unreachable: stored in the local outbox and + retried in the background. Show it as pending — + it is local-only until a circuit takes it. */ } +} val msgs: List = wire.messages(friend.pubkeyHex) +// msgs[i].direction == "out" -> msgs[i].delivery is "sent" | "queued" | +// "sending" | "failed: "; null for incoming messages. Render the +// queued and failed states distinctly from sent. // 5. Locator rotation. Do NOT wire this to a single tap — the app that embeds // the SDK owns the typed confirmation. diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index e90c7fa..afb9ef4 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -11,7 +11,10 @@ //! the friend. //! * Transport is in-process Arti. There is no `tor` binary, no torrc, no //! Orbot pipe. If the onion service cannot publish, this fails closed. -//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not. +//! * Chat bodies are encrypted at rest, and the whole sqlite file is +//! SQLCipher on top of that (see the root crate). +//! * A chat send that cannot reach the peer's onion is queued in a local +//! outbox and retried — see [`SendState`]. Nothing leaves the device. //! //! The façade deliberately exposes only plain data (records + hex strings) so //! no TUI/ratatui type leaks into the AAR. @@ -20,6 +23,7 @@ use std::path::PathBuf; use std::sync::{Arc, OnceLock}; use onionwire::node::Node; +use onionwire::outbox::OutboxStatus; use onionwire::qr; uniffi::setup_scaffolding!(); @@ -79,11 +83,34 @@ pub struct FriendInfo { pub last_connect_ok: bool, } +/// What `send()` did with the message. +/// +/// The core has a local outbox: when a friend's onion is unreachable the +/// message is written to the local sqlite store and a background worker +/// retries it with backoff. Nothing is handed to a third party — every attempt +/// is a fresh handshake straight to that friend's onion — but until a circuit +/// takes it the message exists only on this device. A consumer must not render +/// `Queued` as delivered. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SendState { + /// The frame reached the peer's onion service during this call. + Sent, + /// The peer's onion was unreachable: the message is in the local outbox, + /// local-only until the retry worker delivers it (or it ends `Failed`). + Queued, +} + #[derive(Debug, Clone, uniffi::Record)] pub struct ChatMessage { /// "in" or "out". pub direction: String, pub body: String, + /// Outgoing messages only: `"sent"`, `"queued"`, `"sending"` or + /// `"failed: "`. `None` for incoming messages. An outgoing row with + /// no outbox row is one the peer accepted on the first attempt, so it reads + /// `"sent"` — never treat a missing value as "delivered" on the app side, + /// read this field. + pub delivery: Option, } #[derive(Debug, Clone, uniffi::Record)] @@ -188,28 +215,46 @@ impl Wire { .map_err(WireError::new) } - /// Send one message. Fail closed: if the peer's onion is down, this errors - /// after retrying. There is no outbox in v1 — no silent spooling. - pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { + /// Send one chat message. + /// + /// Returns [`SendState::Sent`] when the frame reached the peer's onion + /// service during this call, and [`SendState::Queued`] when it did not: the + /// message is then in the local outbox and a background worker retries it + /// with exponential backoff (30s doubling, capped at 30 min, 8 attempts) + /// until it lands or ends terminally failed. A queued send is local-only — + /// show it as pending, not delivered. + /// + /// A protocol error (signature mismatch, malformed or oversize frame) is + /// not retryable and still fails here; nothing is queued in that case. + pub async fn send(&self, pubkey_hex: String, body: String) -> WResult { let pk = unhex(&pubkey_hex)?; - self.inner + let status = self + .inner .send(&pk, body.as_bytes()) .await - .map_err(WireError::new) + .map_err(WireError::new)?; + Ok(send_state(status)) } /// Chat history for a friend, oldest first. Bodies are decrypted here; - /// they are stored encrypted at rest. + /// they are stored encrypted at rest. Outgoing rows carry their delivery + /// state in [`ChatMessage::delivery`]. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; let rows = self.inner.list_messages(&pk).map_err(WireError::new)?; - Ok(rows - .into_iter() - .map(|m| ChatMessage { - direction: m.dir, + let mut out = Vec::with_capacity(rows.len()); + for m in rows { + let status = self + .inner + .outbox_status_of_message(m.id) + .map_err(WireError::new)?; + out.push(ChatMessage { body: String::from_utf8_lossy(&m.plaintext).into_owned(), - }) - .collect()) + delivery: delivery_of(&m.dir, status), + direction: m.dir, + }); + } + Ok(out) } /// Delete every message body. Identity and friends survive. @@ -256,3 +301,70 @@ fn unhex(s: &str) -> WResult> { }) .collect() } + +/// `Node::send` only ever yields `Sent` or `Queued`; `Sending`/`Failed` exist +/// only on stored outbox rows. Everything that is not a completed send maps to +/// `Queued`, so a status this build does not know about is never reported as +/// delivered — the fail-safe direction for a caller that hides its retry UI. +fn send_state(status: OutboxStatus) -> SendState { + match status { + OutboxStatus::Sent => SendState::Sent, + _ => SendState::Queued, + } +} + +/// Delivery string for one stored chat row. `None` for incoming rows. An +/// outgoing row with no outbox row was accepted on the first attempt, so it is +/// reported as `"sent"` rather than left blank. +fn delivery_of(dir: &str, status: Option) -> Option { + if dir != "out" { + return None; + } + Some(match status { + None | Some(OutboxStatus::Sent) => "sent".to_string(), + Some(other) => other.to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use onionwire::outbox::OutboxStatus; + + #[test] + fn sent_is_sent_everything_else_is_queued() { + assert_eq!(send_state(OutboxStatus::Sent), SendState::Sent); + assert_eq!(send_state(OutboxStatus::Queued), SendState::Queued); + // `Node::send` never returns these today, but they exist on stored + // rows. Unknown states map to `Queued` — the safe direction: never + // report a send as delivered unless the core says `Sent`. + assert_eq!(send_state(OutboxStatus::Sending), SendState::Queued); + assert_eq!( + send_state(OutboxStatus::Failed("no route".into())), + SendState::Queued + ); + } + + #[test] + fn delivery_is_reported_for_outgoing_rows_only() { + assert_eq!(delivery_of("in", Some(OutboxStatus::Queued)), None); + // Outgoing row with no outbox row: delivered on the first attempt. + assert_eq!(delivery_of("out", None).as_deref(), Some("sent")); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Sent)).as_deref(), + Some("sent") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Queued)).as_deref(), + Some("queued") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Sending)).as_deref(), + Some("sending") + ); + assert_eq!( + delivery_of("out", Some(OutboxStatus::Failed("no route".into()))).as_deref(), + Some("failed: no route") + ); + } +}