Compare commits

...
Author SHA1 Message Date
Sirius DevOps
d6d157765a
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 4m8s
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

- src/outbox.rs: Outbox + Deliverer + ArtiDeliverer, pure backoff_secs(),
  is_permanent_send_error(), background worker (15s scan).
- store: `outbox` table (no body column — the body is read from the joined
  messages row, under that row's existing AEAD + AAD), append_message_id(),
  queue/due/pending/mark_* helpers, reset_sending_outbox(), wipe.
- Node::send() returns Result<OutboxStatus, String> (Sent/Queued) instead of
  Err on transport failure; protocol errors still fail immediately and are
  never queued.
- Retry triggers: timer, unlock/foreground (spawn_flush_all), and "that peer
  was just seen" (handshake or connect_onion -> spawn_flush_friend).
- File transfer and payment/rcp frames stay fail-closed.
- docs/PROTOCOL.md + docs/THREAT_MODEL.md: replace the no-queue statements;
  add the seizure/cadence delta to the threat model.

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 14:39:14 -04:00
acb6c7dd65 Merge pull request 'feat(android): wrap the store passphrase in the Android Keystore' (#44) from feat/android-keystore-store-passphrase into main
Reviewed-on: #44
2026-09-12 18:29:19 +00:00
bf9900f9dc Merge branch 'main' into feat/android-keystore-store-passphrase 2026-09-12 18:29:10 +00:00
1582f7d450 Merge pull request 'feat(store): encrypt the whole sqlite store with SQLCipher' (#43) from feat/sqlcipher-store into main
All checks were successful
ci / test (push) Successful in 3m28s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 5m41s
release / aarch64 (push) Successful in 7m34s
release / publish (push) Successful in 12s
Reviewed-on: #43
2026-09-12 18:28:44 +00:00
70e70cfe8d Merge branch 'main' into feat/sqlcipher-store
All checks were successful
ci / test (pull_request) Successful in 3m31s
2026-09-12 18:28:09 +00:00
27e49b4ea6 Merge pull request 'ci: watch upstream Arti/tor-* releases daily and file an upgrade issue' (#42) from wt/t_731235d4 into main
Reviewed-on: #42
2026-09-12 18:27:21 +00:00
4338e8aeb6 Merge pull request 'ci(android): publish APK/AAR from the Pi runner' (#38) from wt/t_0bbaca1b into main
Reviewed-on: #38
2026-09-12 18:06:58 +00:00
Sirius DevOps
2fd640e230
feat(android): wrap the store passphrase in the Android Keystore
Typing the passphrase on every launch was the v1 posture. It stays the
fallback, but it is no longer required: on first unlock the passphrase can be
remembered (checkbox, on by default) and is stored as an AES-256-GCM blob
wrapped by a key that never leaves the Android Keystore.

- crypto/StoreSecret.kt: the OWSEAL1 envelope (magic + IV + ciphertext + GCM
  tag) and the wipe helpers. No android.* imports, so the code that runs on a
  device is the code the unit tests exercise, with a JVM AES key standing in
  for the Keystore key.
- crypto/KeystorePassphraseCipher.kt: AES-256-GCM key under alias
  `onionwire.store`, StrongBox requested first (API 28+) with a graceful
  fallback on ProviderException (StrongBoxUnavailableException is one), and an
  honest KeyInfo-backed report of where the key actually lives.
  setUserAuthenticationRequired(false) stays the default on purpose.
- crypto/StoredPassphraseStore.kt: ciphertext only, at
  filesDir/secrets/store-passphrase.bin, written tmp+rename. A failed decrypt
  reports Unavailable and does NOT delete the blob.
- WireViewModel: unlock(passphrase, remember), unlockStored(),
  forgetStoredPassphrase(); the secret CharArray is zeroed in `finally`; the
  Keystore probe runs off the main thread at ViewModel construction.
- UnlockScreen: one-tap when a stored blob exists, the typed passphrase is
  dropped from Compose state as soon as it is handed over and is never put in
  saved instance state; "Forget stored passphrase" deletes blob and key.
- androidTest: the device-only half (AndroidKeyStore, StrongBox, KeyInfo),
  which cannot run in the unit-test JVM.

Verified: ./gradlew :app:assembleDebug and :app:testDebugUnitTest green,
25 tests / 0 failures (11 new StoreSecretTest, 9 new StoredPassphraseStoreTest).
2026-09-12 13:55:07 -04:00
Sirius DevOps
e7b37ccb40
feat(store): encrypt the whole sqlite store with SQLCipher
All checks were successful
ci / test (pull_request) Successful in 3m35s
The db held the ed25519 identity secret, friend pubkeys, locators, profiles
and payment rows in the clear; only chat bodies were encrypted. Switch
rusqlite to `bundled-sqlcipher-vendored-openssl` and open every store with
`PRAGMA key = "x'<64 hex>'"` as the first statement after open, using the
existing Argon2id output as a raw key (no second KDF pass).

The per-install KDF salt moves out of the db into `store_salt` (0600) — a key
cannot be derived from a salt that lives inside the file it opens. The
per-message ChaCha20-Poly1305 + row-AAD layer is unchanged: whole-db
encryption does not defend against ciphertext swapped between rows, the AAD
does.

v0.2.1 installs are plaintext. The first open with the right passphrase
upgrades in place (WAL checkpoint, ATTACH ... KEY, sqlcipher_export) and only
swaps the file after the new one opens, passes integrity_check and unwraps
store_meta. A wrong passphrase leaves the plaintext file untouched; a
missing `store_salt` next to an encrypted db refuses to open rather than
guessing.

SQLCipher's internal "hmac check failed" ERROR on a rejected key is
suppressed (cipher_log_level = NONE) so a typo'd passphrase is not an error
dump.

docs/THREAT_MODEL.md: the store is now encrypted at rest; sqlcipher leaves
the "Out of v1" list.
2026-09-12 13:55:07 -04:00
Sirius DevOps
6f96d19901
ci: watch upstream Arti/tor-* releases daily and file an upgrade issue
.forgejo/workflows/arti-watch.yml runs daily (06:17 UTC) and via
workflow_dispatch: scripts/arti-watch.py compares each tor-*/arti-* pin in
Cargo.toml against crates.io and files one Forgejo issue per distinct
major.minor bump, deduped on the title so a repeat run is a no-op. It changes
no dependency.

docs/ARTI_UPGRADE.md records the pinned set (arti-client, tor-cell,
tor-hsservice, tor-rtcompat at 0.46), the lockstep rule, the rustc 1.91
floor, and the tests a bump must pass (tests/tor_hs.rs live publish +
probe-connect + byte pipe, the 360s fail-closed wait and the src/hs.rs
circuit-timeout workarounds in tests/hs.rs, the Android rustls build).

Both artefacts state what this does not cover: Tor Project security
announcements, a yanked crate, and a vulnerability with no version bump.
2026-09-12 13:55:07 -04:00
Sirius DevOps
601eb35c4b
ci(android): publish APK/AAR from the Pi runner
Build stays on docker-amd64. Attach artifacts on the Pi so POST /releases
does not 422 from amd64 dind. Join v0.1.0 when that release is missing
the APK instead of minting patch+1.
2026-09-12 13:55:07 -04:00
30 changed files with 3412 additions and 145 deletions

View file

@ -7,6 +7,10 @@ name: android-release
# toolchain runs in a sibling debian:bookworm container,
# the same stdin-tar + docker cp pattern as .forgejo/workflows/ci.yml.
#
# Publish is a separate job on the Pi runner (`docker`). POST /releases from
# the amd64 dind egress returns 422 with an empty body (core run 116);
# core's publish job on the Pi (run 135) is the proven path.
#
# First automated version with zero tags: v0.1.0. Afterwards, patch+1 from the
# latest v*.*.* tag UNLESS that tag's release is missing the Android assets —
# then join it (core owns tag creation). Never move or delete a tag.
@ -67,6 +71,11 @@ jobs:
android:
runs-on: docker-amd64
timeout-minutes: 90
outputs:
version: ${{ steps.version.outputs.version }}
tag: ${{ steps.version.outputs.tag }}
version_code: ${{ steps.version.outputs.version_code }}
dry_run: ${{ steps.version.outputs.dry_run }}
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
@ -348,31 +357,75 @@ jobs:
docker images "$ANDROID_IMAGE" --format '{{.Repository}}:{{.Tag}} {{.Size}}' || true
docker system df || true
- name: Upload dist artifact
uses: https://code.forgejo.org/actions/upload-artifact@v3
with:
name: onionwire-android
path: dist/
if-no-files-found: error
retention-days: 1
- name: Scrub keystore
if: always()
run: |
set -euo pipefail
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
echo "keystore removed from runner"
publish:
needs: android
# Pi runner, not docker-amd64: POST /releases from amd64 dind returns 422
# with an empty body (core run 116). This job only curls the Forgejo API.
if: needs.android.result == 'success' && needs.android.outputs.dry_run != 'true'
runs-on: docker
timeout-minutes: 20
steps:
- name: Checkout CI tooling
uses: https://code.forgejo.org/actions/checkout@v4
with:
path: .ci-tools
- name: Download Android dist
uses: https://code.forgejo.org/actions/download-artifact@v3
with:
path: artifacts
- name: Publish (create-or-join)
id: publish
if: steps.version.outputs.dry_run != 'true'
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
EVENT_SHA: ${{ github.sha }}
TAG: ${{ steps.version.outputs.tag }}
VERSION: ${{ steps.version.outputs.version }}
TAG: ${{ needs.android.outputs.tag }}
VERSION: ${{ needs.android.outputs.version }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
: "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}"
apk="dist/onionwire-$VERSION-android-$ONIONWIRE_ANDROID_ABI.apk"
aar="dist/onionwire-sdk-$VERSION.aar"
echo "publish host=$(hostname) arch=$(uname -m) tag=$TAG version=$VERSION"
mkdir -p dist
abi="$ONIONWIRE_ANDROID_ABI"
apk="onionwire-$VERSION-android-$abi.apk"
aar="onionwire-sdk-$VERSION.aar"
for f in "$apk" "$apk.sha256" "$aar" "$aar.sha256"; do
src=$(find artifacts -type f -name "$f" -print -quit)
if [ -z "$src" ]; then
echo "missing artifact $f" >&2
find artifacts -type f >&2 || true
exit 1
fi
cp "$src" "dist/$f"
done
for f in dist/"$apk" dist/"$apk".sha256 dist/"$aar" dist/"$aar".sha256; do
bytes=$(wc -c < "$f")
echo "on disk: $f $bytes bytes"
[ "$bytes" -gt 0 ] || { echo "refusing to publish empty $f" >&2; exit 1; }
file "$f" || true
done
tag_exists=0
i=0
while [ "$i" -lt 6 ]; do
code=$(curl -sS --http1.1 -o /tmp/tag.json -w '%{http_code}' \
-H "Authorization: Bearer $FORGEJO_TOKEN" \
-H "Authorization: Bearer ${FORGEJO_TOKEN}" \
"$REPO_API/tags/$TAG" || true)
if [ "$code" = "200" ]; then
tag_exists=1
@ -384,39 +437,18 @@ jobs:
sleep 10
done
created_tag=false
if [ "$tag_exists" = "1" ]; then
unset TARGET_COMMITISH || true
else
export TARGET_COMMITISH="$EVENT_SHA"
created_tag=true
echo "creating tag $TAG at $TARGET_COMMITISH"
fi
echo "created_tag=$created_tag" >> "$GITHUB_OUTPUT"
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
PUB_C=onionwire-android-publish-${{ github.run_id }}
docker rm -f "$PUB_C" >/dev/null 2>&1 || true
docker create --name "$PUB_C" -i \
-e FORGEJO_TOKEN \
-e REPO_API \
-e TARGET_COMMITISH="${TARGET_COMMITISH:-}" \
-e TAG \
-w /src \
"$ANDROID_IMAGE" \
bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && apt-get update && apt-get install -y --no-install-recommends python3 curl ca-certificates >/dev/null && scripts/publish-release.sh "$TAG" "OnionWire $TAG" scripts/release-body.md dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk.sha256 dist/onionwire-sdk-'"$VERSION"'.aar dist/onionwire-sdk-'"$VERSION"'.aar.sha256'
tar czf - \
--exclude=./target --exclude=./.git --exclude=./.worktrees \
--exclude=./android/.gradle --exclude=./android/app/build \
--exclude=./android/sdk/build \
--exclude=./crates/onionwire-sdk/target \
. \
| docker start -a -i "$PUB_C"
docker rm -f "$PUB_C" >/dev/null || true
- name: Scrub keystore
if: always()
run: |
set -euo pipefail
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
echo "keystore removed from runner"
echo "publishing $TAG from $REPO_API"
.ci-tools/scripts/publish-release.sh \
"$TAG" "OnionWire $TAG" \
.ci-tools/scripts/release-body.md \
"dist/$apk" \
"dist/$apk.sha256" \
"dist/$aar" \
"dist/$aar.sha256"

View file

@ -0,0 +1,72 @@
name: arti-watch
# Daily upstream check for the in-process Tor stack. Arti onion services are
# experimental (README) and tor-*/arti-* are the largest attack surface here,
# so when crates.io has a newer major.minor than the pins in Cargo.toml this
# files ONE Forgejo issue (deduped on the title — a second run is a no-op).
#
# Forgejo has no Dependabot: this workflow IS the dependency alert. It
# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain
# floor and the tests it must pass are in docs/ARTI_UPGRADE.md.
#
# NOT covered, by design: Tor Project security announcements (a fix that ships
# with no crates.io version bump is invisible here) and a yanked crate /
# vulnerability in a version that has not changed. Read
# https://blog.torproject.org/ yourself.
on:
schedule:
# 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose.
- cron: "17 6 * * *"
workflow_dispatch:
inputs:
dry_run:
description: Compare and log only, file no issue (true/false)
required: false
type: string
default: "false"
simulate_pin:
description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.'
required: false
type: string
# Never two watchers at once: two simultaneous runs could both see "no issue
# with this title yet" and file twice.
concurrency:
group: onionwire-arti-watch
cancel-in-progress: false
jobs:
watch:
# Same Pi runner + `docker` job image as ci.yml / release.yml (which run
# python3 and curl there). No cargo, no docker: four crates.io GETs and at
# most one issue POST.
runs-on: docker
timeout-minutes: 10
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
- name: Compare pins against crates.io and file an issue on a bump
shell: bash
env:
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }}
INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }}
run: |
set -euo pipefail
args=(--cargo-toml Cargo.toml)
case "${INPUT_DRY_RUN:-false}" in
true|True|TRUE|1|yes|YES) args+=(--dry-run) ;;
esac
if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then
IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN"
for pair in "${pairs[@]}"; do
pair="${pair// /}"
if [ -n "$pair" ]; then
args+=(--simulate-pin "$pair")
fi
done
fi
echo "run: python3 scripts/arti-watch.py ${args[*]}"
python3 scripts/arti-watch.py "${args[@]}"

11
Cargo.lock generated
View file

@ -2295,6 +2295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
dependencies = [
"cc",
"openssl-sys",
"pkg-config",
"vcpkg",
]
@ -2692,6 +2693,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-src"
version = "300.6.1+3.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
dependencies = [
"cc",
]
[[package]]
name = "openssl-sys"
version = "0.9.117"
@ -2700,6 +2710,7 @@ checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
dependencies = [
"cc",
"libc",
"openssl-src",
"pkg-config",
"vcpkg",
]

View file

@ -32,7 +32,7 @@ futures = "0.3"
safelog = "0.9"
ed25519-dalek = { version = "2", features = ["rand_core"] }
rand = "0.8"
rusqlite = { version = "0.36", features = ["bundled"] }
rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] }
tor-cell = "0.46"
tor-hsservice = "0.46"

View file

@ -245,19 +245,26 @@ peer and a Linux peer that exchange invites interoperate — one protocol, not t
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack
Compose + Material 3 messenger that depends on the SDK and nothing else.
It is not a WebView, and `src/tui.rs` is untouched. Both are built on a host with
the Android SDK/NDK — the Pi runner is aarch64 Linux and cannot produce an APK:
It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is
amd64-only — the Pi runner is aarch64 Linux and cannot produce an APK.
[`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml)
builds on `docker-amd64`, then a second job on the Pi (`docker`) attaches the
APK + AAR (+ `.sha256`) to the same Forgejo tag as the Linux binaries. If that
tag's release already exists and is missing the APK, the workflow **joins** it
instead of minting patch+1. Publish does not run from amd64 dind: `POST /releases`
from that egress returns 422 with an empty body.
```bash
# one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358,
# rustup target add aarch64-linux-android, cargo install cargo-ndk
scripts/build-android-local.sh # -> dist/, with .sha256 files
PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh # + upload to that release
PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh # + upload to that release
```
Every asset has a matching `.sha256` so `sha256sum -c` works. The APK is
**debug-signed** and is for sideloading, not for Play. Full build notes, the
`minSdk 26` rationale, the 16 KB page-size check and the signing story are in
Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the
repo-owned release keystore. A local run without those env vars still
debug-signs for sideload, not Play. Full build notes, the `minSdk 26`
rationale, the 16 KB page-size check and the signing story are in
[`android/README.md`](android/README.md).
## Releases (maintainers)

View file

@ -94,6 +94,49 @@ exclusions, because an auto-backup of `onionwire.db` would hand the wrapped
message key *and* the plaintext identity keys to Google Drive. Chat bodies are
encrypted at rest; identity keys are not — that is the locked v1 posture.
### The store passphrase at rest
Typing the passphrase on every launch is no longer required. On first unlock
the passphrase can be remembered (checkbox, on by default), and it is then
stored as an AES-256-GCM blob:
* the wrapping key is generated inside the **Android Keystore** under alias
`onionwire.store`, AES-256-GCM, `setUserAuthenticationRequired(false)` —
deliberately **not** biometric-gated, because a fingerprint prompt would turn
"the node opens or tells you why it did not" into "the node is unusable";
* **StrongBox is requested first** (`setIsStrongBoxBacked(true)`, guarded by
`FEATURE_STRONGBOX_KEYSTORE` on API 28+) and falls back to an ordinary
TEE-backed or software Keystore key when the chip refuses AES-256
(`StrongBoxUnavailableException is a ProviderException`). The fallback is
reported, not hidden: the lock screen prints what `KeyInfo` actually said,
and a software key is labelled **NOT hardware-backed**;
* only ciphertext + IV reach disk, at
`filesDir/secrets/store-passphrase.bin` — an `OWSEAL1` envelope of
magic + IV + ciphertext + GCM tag. No second copy, no `SharedPreferences`,
no plaintext in logs, and the typed `CharArray` is zeroed as soon as the
unlock call returns. The text field is a plain `remember`, so the typed
passphrase is never written into saved instance state;
* **Keystore invalidation is a supported path, not a crash.** A factory reset,
an app-data wipe, or a key the platform invalidates leaves a blob that cannot
authenticate: `StoredPassphraseStore.load()` returns `Unavailable`, the lock
screen explains it, and the user types the passphrase again. A failed read
does **not** delete the blob — a transient Keystore failure must not destroy
the only copy;
* `forget` deletes the blob **and** the Keystore key.
The one plaintext copy this cannot erase is the immutable `String` the UniFFI
binding takes (`openWire(home, passphrase: String)`). A follow-up SDK change
should accept the key (or a `ByteArray`) so the passphrase never becomes a
`String` at all.
`app/src/test/.../crypto/` covers the envelope and the file handling on the JVM
(the real `StoreSecret` code, with a JVM AES key standing in). The Keystore
provider only exists on a device:
```bash
./gradlew :app:connectedDebugAndroidTest # prints the KeyInfo/hardware report
```
### Signing
Release APKs are signed with a **repo-owned keystore**, not the debug key.
@ -153,5 +196,8 @@ android/
src/main/java/com/siriusdevops/onionwire/
MainActivity.kt # NavHost
WireViewModel.kt # owns the single Wire node
crypto/ # Keystore-wrapped store passphrase
ui/ # Compose screens (M3)
src/test/ # JVM tests (envelope, store, invite flow)
src/androidTest/ # device-only: AndroidKeyStore
```

View file

@ -28,6 +28,7 @@ android {
// the offline default and match the first automated tag (v0.1.0 → 100).
versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100
versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
ndk {
abiFilters += onionwireAbis
}
@ -129,4 +130,10 @@ dependencies {
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
// Device-only: the AndroidKeyStore provider does not exist in the unit-test
// JVM. These run under `./gradlew :app:connectedDebugAndroidTest`.
androidTestImplementation(libs.junit)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
}

View file

@ -0,0 +1,150 @@
package com.siriusdevops.onionwire.crypto
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
/**
* The device half of the Keystore story. The unit-test JVM has no
* `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test.
*
* Run on a real device or an emulator:
*
* ./gradlew :app:connectedDebugAndroidTest
*
* and read the `OnionWireKeystore` tag in logcat for the actual
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
* hardware-backed key on hardware that does not have one.
*/
@RunWith(AndroidJUnit4::class)
class KeystorePassphraseCipherTest {
private val context: Context =
InstrumentationRegistry.getInstrumentation().targetContext
private val cipher = KeystorePassphraseCipher(context)
private val passphrase = "correct horse battery staple".toCharArray()
@After
fun tearDown() {
cipher.deleteKey()
}
@Test
fun seal_open_round_trips_through_the_android_keystore() {
val blob = cipher.seal(passphrase)
assertTrue(
"envelope is magic + IV + ciphertext + tag",
blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9,
)
val out = cipher.open(blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun stored_blob_on_a_device_is_not_the_plaintext() {
val dir = File(context.filesDir, "secrets-test")
dir.mkdirs()
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
try {
store.save(passphrase)
val raw = File(store.path).readBytes()
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"the passphrase must not appear in the file",
String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
)
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals(passphrase, loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
} finally {
store.forget()
dir.deleteRecursively()
}
}
@Test
fun key_backing_is_reported_and_logged() {
cipher.seal(passphrase) // force key creation
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
val backing = cipher.backing()
Log.i(
"OnionWireKeystore",
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
"strongBoxAdvertised=$strongBoxAdvertised " +
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
)
if (strongBoxAdvertised) {
assertTrue(
"StrongBox is advertised but the key did not land in a secure element: $backing",
backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE,
)
} else {
assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing)
}
}
@Test
fun open_does_not_require_user_authentication() {
// The card's contract: unlocking must not need a fingerprint. If the
// key had been created with setUserAuthenticationRequired(true), this
// open() would throw UserNotAuthenticatedException.
val out = cipher.open(cipher.seal(passphrase))
StoreSecret.wipe(out)
assertTrue(cipher.keyPresent())
}
@Test
fun deleted_key_reports_unavailable_instead_of_crashing() {
val blob = cipher.seal(passphrase)
cipher.deleteKey()
assertFalse(cipher.keyPresent())
try {
cipher.open(blob)
fail("expected SecretUnavailable after the key was deleted")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("gone"))
}
}
@Test
fun a_regenerated_key_cannot_open_an_old_blob() {
val blob = cipher.seal(passphrase)
cipher.deleteKey() // a reset that leaves the app's data dir intact
cipher.seal(passphrase) // same alias, brand-new key
try {
cipher.open(blob)
fail("expected SecretUnavailable for a blob wrapped by the deleted key")
} catch (_: SecretUnavailable) {
}
}
}

View file

@ -47,10 +47,17 @@ class MainActivity : ComponentActivity() {
@Composable
private fun AppRoot(vm: WireViewModel = viewModel()) {
val phase by vm.phase.collectAsStateWithLifecycle()
val unlock by vm.unlock.collectAsStateWithLifecycle()
when (val p = phase) {
is Phase.Ready -> ReadyGraph(vm, p)
else -> UnlockScreen(phase = p, onUnlock = vm::unlock)
else -> UnlockScreen(
phase = p,
unlock = unlock,
onUnlock = vm::unlock,
onUnlockStored = vm::unlockStored,
onForgetStored = vm::forgetStoredPassphrase,
)
}
}

View file

@ -3,10 +3,16 @@ package com.siriusdevops.onionwire
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.siriusdevops.onionwire.crypto.KeyBacking
import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher
import com.siriusdevops.onionwire.crypto.StoreSecret
import com.siriusdevops.onionwire.crypto.StoredPassphraseStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import uniffi.onionwire_sdk.ChatMessage
import uniffi.onionwire_sdk.FriendInfo
import uniffi.onionwire_sdk.InviteInfo
@ -32,6 +38,23 @@ sealed interface Phase {
data class Failed(val message: String) : Phase
}
/**
* How the lock screen expects the next unlock to happen.
*
* This is a probe of local state, not a promise: [OneTap] means a blob exists
* *and* decrypted successfully during this process's lifetime.
*/
sealed interface Unlock {
/**
* The passphrase must be typed. [notice] explains why a stored one is not
* being used (key invalidated, blob corrupt, nothing stored yet).
*/
data class TypeIt(val notice: String? = null) : Unlock
/** A stored, decryptable passphrase exists — one tap. */
data class OneTap(val backing: KeyBacking) : Unlock
}
/**
* Owns the single Wire node for the process.
*
@ -43,46 +66,166 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
/** `context.filesDir` — app-private, never external storage. */
private val home: File = File(app.filesDir, "onionwire")
/**
* The Keystore-wrapped passphrase. Two files at most: this blob and the
* KeyStore key under alias [KeystorePassphraseCipher.ALIAS]. Nothing else
* on disk ever sees the plaintext.
*/
private val secrets: StoredPassphraseStore = StoredPassphraseStore(
File(File(app.filesDir, "secrets"), "store-passphrase.bin"),
KeystorePassphraseCipher(app),
)
private val _phase = MutableStateFlow<Phase>(Phase.Locked)
val phase: StateFlow<Phase> = _phase.asStateFlow()
private val _unlock = MutableStateFlow<Unlock>(Unlock.TypeIt())
val unlock: StateFlow<Unlock> = _unlock.asStateFlow()
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
private var wire: Wire? = null
init {
// Probe on a background dispatcher: this touches the Keystore and does
// a full GCM decrypt. Doing it here means a killed Keystore key is
// reported on the lock screen instead of at the first tap.
refreshUnlockState()
}
/**
* Opens (or on first run, creates) the identity and starts hosting.
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
* straight to an error, it is not a "skip" path.
*
* An empty passphrase fails closed — the SDK maps it straight to an error,
* it is not a "skip" path.
* [remember] wraps the passphrase with the Keystore key so later launches
* are one tap. It is opt-in in the UI (and on by default there); it is
* never implied by this call.
*/
fun unlock(passphrase: String) {
fun unlock(passphrase: String, remember: Boolean = false) {
if (passphrase.isEmpty()) return
openWith(passphrase.toCharArray(), storeAfterwards = remember)
}
/**
* One-tap unlock from the stored blob.
*
* Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to
* "type it" with the reason on screen. It never crashes and never silently
* unlocks with something else.
*/
fun unlockStored() {
if (_phase.value is Phase.Opening) return
_phase.value = Phase.Opening
viewModelScope.launch {
try {
val w = openWire(home.absolutePath, passphrase)
wire = w
_phase.value = Phase.Ready(
fingerprint = w.fingerprint(),
onion = w.onion(),
sdkVersion = w.version(),
)
refreshFriends()
} catch (t: Throwable) {
_phase.value = Phase.Failed(t.message ?: t.toString())
val loaded = withContext(Dispatchers.IO) { secrets.load() }
when (loaded) {
is StoredPassphraseStore.Load.Loaded ->
openWith(loaded.passphrase, storeAfterwards = false)
StoredPassphraseStore.Load.Absent -> {
_unlock.value = Unlock.TypeIt("No passphrase is stored on this device.")
}
is StoredPassphraseStore.Load.Unavailable -> {
_unlock.value = Unlock.TypeIt(unavailableNotice(loaded.reason))
}
}
}
}
/** Drops the stored passphrase and its Keystore key. Irreversible. */
fun forgetStoredPassphrase() {
viewModelScope.launch {
withContext(Dispatchers.IO) { secrets.forget() }
_unlock.value = Unlock.TypeIt(
"Stored passphrase deleted. Type it to open the store again.",
)
}
}
/** Drops our handle. The onion service stops; nothing is sent after this. */
fun lock() {
wire = null
_friends.value = emptyList()
_phase.value = Phase.Locked
refreshUnlockState()
}
private fun refreshUnlockState() {
viewModelScope.launch {
val state = withContext(Dispatchers.IO) {
when (val loaded = secrets.load()) {
is StoredPassphraseStore.Load.Loaded -> {
// We only needed to know it decrypts. Wipe immediately.
StoreSecret.wipe(loaded.passphrase)
Unlock.OneTap(secrets.backing())
}
StoredPassphraseStore.Load.Absent -> Unlock.TypeIt()
is StoredPassphraseStore.Load.Unavailable ->
Unlock.TypeIt(unavailableNotice(loaded.reason))
}
}
_unlock.value = state
}
}
/**
* The one path that calls the SDK.
*
* [secret] is wiped in `finally`, including when the Keystore write or the
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
* immutable copy is unavoidable here — see the PR description for the
* follow-up SDK signature this card cannot make itself.
*/
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
if (secret.isEmpty() || _phase.value is Phase.Opening) {
StoreSecret.wipe(secret)
return
}
_phase.value = Phase.Opening
viewModelScope.launch {
try {
val w = openWire(home.absolutePath, secret.concatToString())
wire = w
if (storeAfterwards) store(secret)
_phase.value = Phase.Ready(
fingerprint = w.fingerprint(),
onion = w.onion(),
sdkVersion = w.version(),
)
refreshFriends()
} catch (t: Throwable) {
_phase.value = Phase.Failed(t.message ?: t.toString())
} finally {
StoreSecret.wipe(secret)
}
}
}
private suspend fun store(secret: CharArray) {
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
try {
secrets.save(secret)
Result.success(secrets.backing())
} catch (t: Throwable) {
Result.failure(t)
}
}
_unlock.value = outcome.fold(
onSuccess = { Unlock.OneTap(it) },
onFailure = {
// Unlock succeeded, so this is not fatal — say so plainly
// instead of pretending the passphrase was stored.
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
},
)
}
private fun unavailableNotice(reason: String): String =
"The stored passphrase could not be read — $reason. Type it once to store it again."
private fun requireWire(): Wire = wire ?: error("locked")
suspend fun refreshFriends() {

View file

@ -0,0 +1,139 @@
package com.siriusdevops.onionwire.crypto
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyInfo
import android.security.keystore.KeyProperties
import java.security.KeyStore
import java.security.ProviderException
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
/**
* AES-256-GCM key held by the Android Keystore under [ALIAS].
*
* The key material is never readable by this process (`SecretKey.encoded` is
* null for AndroidKeyStore keys) — that is the whole point: pulling
* `/data/data/com.siriusdevops.onionwire/` off a rooted device yields the
* ciphertext, not the passphrase.
*
* StrongBox is requested first and falls back to the ordinary TEE-backed (or
* software) Keystore without a crash. The fallback is not silent: call
* [backing] and report what the Keystore actually produced.
*
* `setUserAuthenticationRequired` is deliberately **false**. Requiring a
* fingerprint to unlock the node would turn "fail closed" into "unusable
* unattended", and the SDK's contract is that an unlock either opens the node
* or reports why it did not.
*/
class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher {
private var cached: SecretKey? = null
override fun seal(plaintext: CharArray): ByteArray =
StoreSecret.seal(loadOrCreateKey(), plaintext)
/**
* Never creates a key. A freshly generated key cannot decrypt an old blob,
* and generating one here would turn "the key is gone" into a confusing
* GCM tag failure. The caller needs the real reason to tell the user.
*/
override fun open(blob: ByteArray): CharArray {
val key = cached ?: existingKey()
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
return StoreSecret.open(key, blob)
}
override fun keyPresent(): Boolean = (cached ?: existingKey()) != null
override fun backing(): KeyBacking {
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN
val info = try {
SecretKeyFactory.getInstance(key.algorithm, PROVIDER)
.getKeySpec(key, KeyInfo::class.java) as KeyInfo
} catch (_: Exception) {
// Some OEM Keystore implementations refuse getKeySpec. Report
// UNKNOWN rather than guessing hardware backing.
return KeyBacking.UNKNOWN
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX
) {
return KeyBacking.STRONGBOX
}
// Deprecated in API 31 in favour of securityLevel, but it is the only
// TEE/software answer available on 26–30, and minSdk is 26.
@Suppress("DEPRECATION")
val inSecureHardware = info.isInsideSecureHardware
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
}
override fun deleteKey() {
cached = null
try {
keyStore().deleteEntry(ALIAS)
} catch (_: Exception) {
// Nothing usable to delete.
}
}
private fun existingKey(): SecretKey? {
cached?.let { return it }
val key = try {
keyStore().getKey(ALIAS, null) as? SecretKey
} catch (_: Exception) {
null
}
cached = key
return key
}
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
private fun createKey(): SecretKey {
val strongBoxAdvertised =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
if (strongBoxAdvertised) {
try {
return generate(strongBox = true).also { cached = it }
} catch (_: ProviderException) {
// StrongBoxUnavailableException is a ProviderException: the chip
// exists but its slots are full, or it refuses AES-256. Fall
// through to a normal Keystore key instead of failing unlock.
}
}
return generate(strongBox = false).also { cached = it }
}
private fun generate(strongBox: Boolean): SecretKey {
val builder = KeyGenParameterSpec.Builder(
ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(StoreSecret.KEY_BITS)
// Our IV comes from Cipher.init, and the Keystore supplies it.
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(false)
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setIsStrongBoxBacked(true)
}
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
generator.init(builder.build())
return generator.generateKey()
}
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
companion object {
const val PROVIDER = "AndroidKeyStore"
/** One key per app: the passphrase it wraps is the only secret here. */
const val ALIAS = "onionwire.store"
}
}

View file

@ -0,0 +1,49 @@
package com.siriusdevops.onionwire.crypto
/**
* Wraps the store passphrase with a key that never leaves the Keystore.
*
* Implementations must not persist the plaintext anywhere, and must not log it.
*/
interface PassphraseCipher {
/** Encrypts [plaintext]. The returned blob is the only thing that may hit disk. */
fun seal(plaintext: CharArray): ByteArray
/**
* Decrypts a blob produced by [seal].
*
* @throws SecretUnavailable when the key is gone, invalidated, or the blob
* does not authenticate. Callers fall back to asking the user to type.
*/
fun open(blob: ByteArray): CharArray
/** True when a usable key is already in the Keystore. */
fun keyPresent(): Boolean
/**
* Where the key actually lives, as reported by the Keystore itself.
*
* This is an observation, not a claim: on a device without a StrongBox or
* TEE the honest answer is [KeyBacking.SOFTWARE], and the UI says so.
*/
fun backing(): KeyBacking
/** Removes the key. The ciphertext becomes permanently undecryptable. */
fun deleteKey()
}
/** Result of asking the Keystore where the key lives. */
enum class KeyBacking {
/** Dedicated security chip (API 28+, Pixel 3-class and up). */
STRONGBOX,
/** Key is inside a TEE. Good. */
HARDWARE,
/** Keystore software implementation. Passphrase is still not plaintext on disk. */
SOFTWARE,
/** No key created yet, or the API could not be queried. Never claim hardware here. */
UNKNOWN,
}

View file

@ -0,0 +1,130 @@
package com.siriusdevops.onionwire.crypto
import java.nio.CharBuffer
import java.nio.charset.StandardCharsets
import java.security.GeneralSecurityException
import java.util.Arrays
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* AES-256-GCM envelope for the store passphrase.
*
* This file is deliberately free of `android.*` imports so the exact
* seal/open code that runs on a device can also run in a plain JVM unit test
* with a JVM-generated AES key. The Android Keystore only supplies the key —
* the framing and the AEAD call are these functions.
*
* Wire format (little of it is secret, all of it is authenticated):
*
* magic "OWSEAL1\n" 8 bytes
* iv length 1 byte (always [IV_BYTES])
* iv [IV_BYTES] bytes, from the cipher
* ciphertext n + [TAG_BITS]/8 bytes (GCM tag is appended)
*
* The IV is generated by `Cipher.init` rather than by us: an AndroidKeyStore
* key created with `setRandomizedEncryptionRequired(true)` refuses an
* app-supplied IV, and SunJCE likewise default-generates one. Nothing here
* ever writes the plaintext passphrase to disk.
*/
object StoreSecret {
/** AES-256 per the card. Keystore key size and this constant must agree. */
const val KEY_BITS: Int = 256
/** 96-bit IV is the GCM-recommended size; AndroidKeyStore defaults to it. */
const val IV_BYTES: Int = 12
/** Full-length GCM tag. Truncating it saves 6 bytes and buys nothing. */
private const val TAG_BITS: Int = 128
private val MAGIC = byteArrayOf('O'.code.toByte(), 'W'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'A'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte(), '\n'.code.toByte())
private const val TRANSFORMATION = "AES/GCM/NoPadding"
/**
* Encrypts [plaintext] under [key]. The passphrase is never converted to a
* `String` on this path: the UTF-8 encoder reads the `CharArray` directly.
*/
fun seal(key: SecretKey, plaintext: CharArray): ByteArray {
require(plaintext.isNotEmpty()) { "refusing to seal an empty passphrase" }
val bytes = utf8(plaintext)
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, key)
val iv = cipher.iv
val ct = cipher.doFinal(bytes)
return ByteArray(MAGIC.size + 1 + iv.size + ct.size).also { out ->
var p = 0
MAGIC.copyInto(out, p); p += MAGIC.size
out[p] = iv.size.toByte(); p += 1
iv.copyInto(out, p); p += iv.size
ct.copyInto(out, p)
}
} catch (e: GeneralSecurityException) {
throw SecretUnavailable("could not encrypt the passphrase", e)
} finally {
wipe(bytes)
}
}
/**
* Reverses [seal]. Throws [SecretUnavailable] on a wrong key, a truncated
* blob, or a failed GCM tag check — never returns partial plaintext.
*/
fun open(key: SecretKey, blob: ByteArray): CharArray {
if (blob.size < MAGIC.size + 1 + IV_BYTES + TAG_BITS / 8) {
throw SecretUnavailable("stored secret is truncated")
}
for (i in MAGIC.indices) {
if (blob[i] != MAGIC[i]) throw SecretUnavailable("stored secret is not an OnionWire envelope")
}
var p = MAGIC.size
val ivLen = blob[p].toInt() and 0xFF
p += 1
if (ivLen != IV_BYTES) throw SecretUnavailable("unexpected IV length $ivLen")
if (blob.size < p + ivLen + TAG_BITS / 8) throw SecretUnavailable("stored secret is truncated")
val iv = blob.copyOfRange(p, p + ivLen)
val ct = blob.copyOfRange(p + ivLen, blob.size)
val plain = try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))
cipher.doFinal(ct)
} catch (e: GeneralSecurityException) {
throw SecretUnavailable("stored secret did not authenticate", e)
}
return try {
decodeUtf8(plain)
} finally {
wipe(plain)
}
}
/** Zeroes [bytes]. Cheap, and it shortens the window a heap dump can read. */
fun wipe(bytes: ByteArray) {
Arrays.fill(bytes, 0)
}
/** Zeroes [chars]. Kotlin/Java strings are immutable, so this is the best we get. */
fun wipe(chars: CharArray) {
Arrays.fill(chars, '\u0000')
}
private fun utf8(chars: CharArray): ByteArray {
val bb = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(chars))
return ByteArray(bb.remaining()).also(bb::get)
}
private fun decodeUtf8(bytes: ByteArray): CharArray {
val cb = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes))
return CharArray(cb.remaining()).also(cb::get)
}
}
/**
* The passphrase could not be recovered. The caller must fall back to typing
* it — a Keystore key does not survive a factory reset, a lock-screen change
* that invalidates keys, or an app-data wipe.
*/
class SecretUnavailable(message: String, cause: Throwable? = null) : RuntimeException(message, cause)

View file

@ -0,0 +1,91 @@
package com.siriusdevops.onionwire.crypto
import java.io.File
import java.io.IOException
/**
* The only on-disk copy of the passphrase: an AES-GCM blob under
* `context.filesDir`, which is app-private and excluded from backup and
* device transfer (`AndroidManifest.xml`, `res/xml/data_extraction_rules.xml`).
*
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
* There is no second copy, no SharedPreferences mirror, and nothing outside the
* app's data dir.
*/
class StoredPassphraseStore(
private val file: File,
private val cipher: PassphraseCipher,
) {
sealed interface Load {
/** Decrypted for this call only. The caller must wipe the array. */
class Loaded(val passphrase: CharArray) : Load
/** Nothing stored yet — first run, or the user forgot it. */
data object Absent : Load
/**
* Something is stored but cannot be read: the Keystore key is gone or
* invalidated, or the file is corrupt. Fall back to typing.
*/
data class Unavailable(val reason: String) : Load
}
fun exists(): Boolean = file.isFile && file.length() > 0L
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
fun backing(): KeyBacking = cipher.backing()
/** Path for diagnostics in tests. Never logged with its contents. */
val path: String get() = file.absolutePath
/**
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling
* temp file and renamed, so a crash mid-write cannot leave half a blob.
*/
fun save(passphrase: CharArray) {
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
val blob = cipher.seal(passphrase)
try {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeBytes(blob)
if (!tmp.renameTo(file)) {
file.writeBytes(blob)
tmp.delete()
}
} finally {
StoreSecret.wipe(blob)
}
}
/**
* Reads and decrypts the blob. The returned array is the caller's to wipe.
*
* A failed decrypt does **not** delete the blob: a transient Keystore
* failure must not silently destroy the user's only copy. Use [forget] to
* drop it deliberately.
*/
fun load(): Load {
if (!exists()) return Load.Absent
val blob = try {
file.readBytes()
} catch (e: IOException) {
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
}
return try {
Load.Loaded(cipher.open(blob))
} catch (e: SecretUnavailable) {
Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
} finally {
StoreSecret.wipe(blob)
}
}
/** Drops the ciphertext and the Keystore key. Irreversible. */
fun forget() {
file.delete()
File(file.parentFile, file.name + ".tmp").delete()
cipher.deleteKey()
}
}

View file

@ -2,6 +2,7 @@ package com.siriusdevops.onionwire.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
@ -11,10 +12,13 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@ -28,10 +32,38 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import com.siriusdevops.onionwire.Phase
import com.siriusdevops.onionwire.Unlock
import com.siriusdevops.onionwire.crypto.KeyBacking
/**
* Lock screen.
*
* When [Unlock.OneTap] is set, the passphrase is already on disk wrapped by the
* Android Keystore key and the user taps once. Otherwise they type it — and
* they land here, with [Unlock.TypeIt.notice] explaining why, whenever the
* stored blob cannot be read (key invalidated, device reset, corrupt file).
*
* The typed passphrase lives in a plain `remember` (not `rememberSaveable`) and
* is cleared as soon as it is handed to the ViewModel: it never survives a
* config change and never gets written to the saved-instance-state bundle.
*/
@Composable
fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
fun UnlockScreen(
phase: Phase,
unlock: Unlock,
onUnlock: (passphrase: String, remember: Boolean) -> Unit,
onUnlockStored: () -> Unit,
onForgetStored: () -> Unit,
) {
var pass by remember { mutableStateOf("") }
var storePassphrase by remember { mutableStateOf(true) }
// Only meaningful under OneTap: reveal the form without giving up the
// stored passphrase.
var typeInstead by remember { mutableStateOf(false) }
val oneTap = unlock as? Unlock.OneTap
val failed = phase is Phase.Failed
val showForm = oneTap == null || typeInstead || failed
Column(
modifier = Modifier
@ -64,38 +96,107 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
}
else -> {
Text(
"Passphrase",
style = MaterialTheme.typography.titleSmall,
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = pass,
onValueChange = { pass = it },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
label = { Text("wraps the local message key") },
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(12.dp))
Text(
"Empty is not a bypass — it fails closed. There is no recovery: " +
"lose this and the stored chat bodies stay unreadable.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(20.dp))
Button(
onClick = { onUnlock(pass) },
enabled = pass.isNotEmpty(),
modifier = Modifier.fillMaxWidth(),
) { Text("Open") }
if (oneTap != null && !failed) {
Text("Passphrase", style = MaterialTheme.typography.titleSmall)
Spacer(Modifier.height(8.dp))
Text(
"Stored on this device, wrapped by an Android Keystore key " +
"(${backingLabel(oneTap.backing)}).",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(20.dp))
Button(
onClick = onUnlockStored,
modifier = Modifier.fillMaxWidth(),
) { Text("Unlock") }
Spacer(Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
TextButton(onClick = { typeInstead = true }) {
Text("Type it instead")
}
TextButton(onClick = onForgetStored) {
Text("Forget stored passphrase")
}
}
if (showForm) {
Spacer(Modifier.height(16.dp))
HorizontalDivider()
Spacer(Modifier.height(16.dp))
}
}
if (phase is Phase.Failed) {
if (showForm) {
if (unlock is Unlock.TypeIt && unlock.notice != null) {
Text(
unlock.notice,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(16.dp))
}
OutlinedTextField(
value = pass,
onValueChange = { pass = it },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Password,
imeAction = ImeAction.Done,
),
label = { Text("wraps the local message key") },
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(12.dp))
Text(
"Empty is not a bypass — it fails closed. There is no recovery: " +
"lose this and the stored chat bodies stay unreadable.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(4.dp))
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth(),
) {
Checkbox(
checked = storePassphrase,
onCheckedChange = { storePassphrase = it },
)
Text(
"Remember on this device (wrapped by the Android Keystore, " +
"no backup)",
style = MaterialTheme.typography.bodySmall,
)
}
if (oneTap != null) {
Text(
"Typing and remembering replaces the stored passphrase.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(Modifier.height(20.dp))
Button(
onClick = {
val typed = pass
// Drop the plaintext from Compose state the moment
// it is handed over; the ViewModel wipes its copy.
pass = ""
onUnlock(typed, storePassphrase)
},
enabled = pass.isNotEmpty(),
modifier = Modifier.fillMaxWidth(),
) { Text("Open") }
}
if (failed) {
Spacer(Modifier.height(20.dp))
Text(
"Failed to start",
@ -128,3 +229,14 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
)
}
}
/**
* What the Keystore reported, verbatim. Never upgraded into a stronger claim:
* a software key says so.
*/
internal fun backingLabel(backing: KeyBacking): String = when (backing) {
KeyBacking.STRONGBOX -> "StrongBox"
KeyBacking.HARDWARE -> "TEE-backed"
KeyBacking.SOFTWARE -> "software key, NOT hardware-backed"
KeyBacking.UNKNOWN -> "backing not reported by this device"
}

View file

@ -0,0 +1,157 @@
package com.siriusdevops.onionwire.crypto
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* Exercises the real envelope code — [StoreSecret] has no `android.*` imports,
* so a JVM AES key stands in for the AndroidKeystore key.
*
* What this does NOT cover (see the PR description): the AndroidKeyStore provider
* itself (`KeyGenerator` + `KeyGenParameterSpec`, StrongBox fallback, and
* `KeyInfo.isInsideSecureHardware`). Those are device-only APIs; the unit-test
* JVM has no such provider.
*/
class StoreSecretTest {
private fun aesKey(): SecretKey =
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
private val passphrase = "correct horse battery staple".toCharArray()
@Test
fun seal_open_round_trips() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
val out = StoreSecret.open(key, blob)
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun round_trips_non_ascii_and_whitespace() {
val key = aesKey()
val weird = " ünïcödé 🔑 \n\ttab ".toCharArray()
val out = StoreSecret.open(key, StoreSecret.seal(key, weird))
try {
assertArrayEquals(weird, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun blob_does_not_contain_the_plaintext() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"ciphertext must not contain the passphrase",
blob.containsSubsequence(needle),
)
assertTrue(blob.size > needle.size)
}
@Test
fun blob_carries_the_envelope_magic() {
val blob = StoreSecret.seal(aesKey(), passphrase)
assertEquals("OWSEAL1\n", String(blob.copyOfRange(0, 8), Charsets.US_ASCII))
// Magic(8) + IV length(1) + IV(12) + tag(16)
assertEquals(8 + 1 + StoreSecret.IV_BYTES + 16, blob.size - String(passphrase).toByteArray(Charsets.UTF_8).size)
}
@Test
fun each_seal_uses_a_fresh_iv() {
val key = aesKey()
val a = StoreSecret.seal(key, passphrase)
val b = StoreSecret.seal(key, passphrase)
assertNotEquals(
"identical ciphertext means the IV was reused",
a.toList(),
b.toList(),
)
}
@Test
fun wrong_key_fails_closed() {
val blob = StoreSecret.seal(aesKey(), passphrase)
try {
StoreSecret.open(aesKey(), blob)
fail("expected SecretUnavailable")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("authenticate"))
}
}
@Test
fun tampered_ciphertext_fails_the_gcm_tag() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0x01).toByte()
try {
StoreSecret.open(key, blob)
fail("expected SecretUnavailable")
} catch (_: SecretUnavailable) {
}
}
@Test
fun truncated_blob_fails_closed() {
val key = aesKey()
val blob = StoreSecret.seal(key, passphrase)
try {
StoreSecret.open(key, blob.copyOfRange(0, 10))
fail("expected SecretUnavailable")
} catch (_: SecretUnavailable) {
}
}
@Test
fun garbage_blob_fails_closed() {
try {
StoreSecret.open(aesKey(), "not an envelope".toByteArray())
fail("expected SecretUnavailable")
} catch (e: SecretUnavailable) {
assertTrue(e.message!!.contains("truncated") || e.message!!.contains("envelope"))
}
}
@Test
fun seal_refuses_an_empty_passphrase() {
try {
StoreSecret.seal(aesKey(), CharArray(0))
fail("expected IllegalArgumentException")
} catch (_: IllegalArgumentException) {
}
}
@Test
fun wipe_zeroes() {
val bytes = byteArrayOf(1, 2, 3)
StoreSecret.wipe(bytes)
assertArrayEquals(ByteArray(3), bytes)
val chars = charArrayOf('a', 'b')
StoreSecret.wipe(chars)
assertArrayEquals(CharArray(2), chars)
}
private fun ByteArray.containsSubsequence(needle: ByteArray): Boolean {
if (needle.isEmpty() || needle.size > size) return false
outer@ for (i in 0..size - needle.size) {
for (j in needle.indices) if (this[i + j] != needle[j]) continue@outer
return true
}
return false
}
}

View file

@ -0,0 +1,167 @@
package com.siriusdevops.onionwire.crypto
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* File-level behaviour of [StoredPassphraseStore] with the real envelope from
* [StoreSecret] and a JVM AES key standing in for the Keystore key.
*
* The Keystore itself is device-only; what is proven here is that nothing
* plaintext reaches the file, that a lost key degrades instead of crashing,
* and that a lost key does not delete the user's blob.
*/
class StoredPassphraseStoreTest {
@get:Rule
val tmp = TemporaryFolder()
private val passphrase = "correct horse battery staple".toCharArray()
/** Stands in for the AndroidKeystore key: real AES-GCM, JVM-held key. */
private class JvmKeyCipher(private val key: SecretKey) : PassphraseCipher {
var deleted = false
var backingQueried = 0
override fun seal(plaintext: CharArray): ByteArray = StoreSecret.seal(key, plaintext)
override fun open(blob: ByteArray): CharArray {
if (deleted) throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
return StoreSecret.open(key, blob)
}
override fun keyPresent(): Boolean = !deleted
override fun backing(): KeyBacking {
backingQueried++
return KeyBacking.SOFTWARE
}
override fun deleteKey() {
deleted = true
}
}
private fun jvmKey(): SecretKey =
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
private fun store(cipher: PassphraseCipher) =
StoredPassphraseStore(tmp.newFile("store-passphrase.bin").also { it.delete() }, cipher)
@Test
fun save_then_load_round_trips() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
val loaded = store.load()
assertTrue(loaded is StoredPassphraseStore.Load.Loaded)
val out = (loaded as StoredPassphraseStore.Load.Loaded).passphrase
try {
assertArrayEquals(passphrase, out)
} finally {
StoreSecret.wipe(out)
}
}
@Test
fun on_disk_blob_is_not_the_plaintext() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
val raw = java.io.File(store.path).readBytes()
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
assertFalse(
"the passphrase must not appear in the file",
raw.toString(Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
)
assertTrue("expected the OWSEAL envelope", raw.size > needle.size + 20)
assertEquals("OWSEAL1\n", String(raw.copyOfRange(0, 8), Charsets.US_ASCII))
}
@Test
fun no_temp_file_is_left_behind() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
val dir = requireNotNull(java.io.File(store.path).parentFile)
val leftovers = dir.listFiles()!!.filter { it.name.endsWith(".tmp") }
assertTrue("temp files left: $leftovers", leftovers.isEmpty())
}
@Test
fun save_overwrites_the_previous_blob() {
val store = store(JvmKeyCipher(jvmKey()))
store.save("first".toCharArray())
store.save("second".toCharArray())
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
try {
assertArrayEquals("second".toCharArray(), loaded.passphrase)
} finally {
StoreSecret.wipe(loaded.passphrase)
}
}
@Test
fun absent_when_nothing_was_ever_stored() {
val store = store(JvmKeyCipher(jvmKey()))
assertFalse(store.exists())
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
}
@Test
fun lost_key_reports_unavailable_and_keeps_the_blob() {
val cipher = JvmKeyCipher(jvmKey())
val store = store(cipher)
store.save(passphrase)
cipher.deleteKey() // device reset / key invalidated
val loaded = store.load()
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
assertTrue(
(loaded as StoredPassphraseStore.Load.Unavailable).reason.contains("gone"),
)
assertTrue("a failed read must not delete the blob", store.exists())
}
@Test
fun corrupt_blob_reports_unavailable_instead_of_throwing() {
val store = store(JvmKeyCipher(jvmKey()))
store.save(passphrase)
java.io.File(store.path).writeBytes("OWSEAL1\n not really a ciphertext".toByteArray())
val loaded = store.load()
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
}
@Test
fun forget_deletes_the_blob_and_the_key() {
val cipher = JvmKeyCipher(jvmKey())
val store = store(cipher)
store.save(passphrase)
assertTrue(store.exists())
store.forget()
assertFalse(store.exists())
assertFalse(cipher.keyPresent())
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
}
@Test
fun backing_is_reported_from_the_cipher() {
val cipher = JvmKeyCipher(jvmKey())
val store = store(cipher)
store.save(passphrase)
assertEquals(KeyBacking.SOFTWARE, store.backing())
assertEquals(1, cipher.backingQueried)
}
}

View file

@ -9,11 +9,15 @@ composeBom = "2025.12.01"
jna = "5.19.1"
coroutines = "1.11.0"
junit = "4.13.2"
androidxTestJunit = "1.3.0"
androidxTestRunner = "1.7.0"
[libraries]
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
junit = { module = "junit:junit", version.ref = "junit" }
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestJunit" }
androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }

143
docs/ARTI_UPGRADE.md Normal file
View file

@ -0,0 +1,143 @@
# Upgrading the Arti / Tor crates
The in-process Tor stack is the largest attack surface in OnionWire. Arti's
onion services are still **experimental** and OnionWire does not fall back to a
C-tor subprocess, so an upstream fix only reaches users when we bump these
crates, rebuild, and cut a release.
## What is pinned
Direct dependencies that come from the Arti repository, exactly as
`Cargo.toml` has them:
| crate | requirement | features in `Cargo.toml` |
|---|---|---|
| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
| `tor-cell` | `0.46` | — |
| `tor-hsservice` | `0.46` | — |
| `tor-rtcompat` | `0.46` | `tokio` |
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
part of a Tor upgrade.
Two crate features re-expose Arti's TLS backends, which Arti marks
**non-additive** — exactly one may be selected per build graph:
* `native-tls` (default) → Linux TUI build, via OpenSSL.
* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has
no OpenSSL.
Published Arti releases move all four crates together in lockstep. Bump them as
**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is
not a configuration anyone tests upstream, and cargo will usually refuse or
silently pick one `tor-*` version and mismatched `tor-*` internals fail at
runtime.
## Toolchain floor
**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`;
the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm`
(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`).
A bump may raise the floor. Take the actual MSRV from the upstream release
notes / the crate's own `rust-version`, then raise it in the same PR:
* `rust-version` in `Cargo.toml`,
* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`,
* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it
when that lands, or ask the owner).
## How this gets noticed
`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks
crates.io for the newest stable version of each crate above. If the
major.minor moved past the pin, it files one Forgejo issue titled
`Arti upstream: <crate> <pin> → <new>`. It is deduped on that title across open
and closed issues, so re-running it never files a second issue and never
comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit.
Test the alert path without waiting for upstream (it compares real crates.io
data against a pretend pin):
```
# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45
python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45
```
**What the watcher does not cover.** It does not subscribe to Tor Project
security announcements — a fix that ships without a crates.io version bump is
invisible to it. It will not catch a yanked crate, and it will not catch a
vulnerability in a version that has not changed. Watch
<https://blog.torproject.org/> and <https://forum.torproject.org/> yourself, and
treat a Tor security advisory as an instruction to bump **now**, ahead of any
issue the watcher files.
## Procedure
1. Read the upstream release notes (Arti tags: <https://gitlab.torproject.org/tpo/core/arti/-/releases>)
and the CHANGELOG for breaking API changes. Check the new MSRV.
2. Branch from `main`; bump all four requirements in `[dependencies]` of
`Cargo.toml` together, and `rust-version` if the floor moved.
3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is
committed):
```
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat
git diff --stat Cargo.lock
```
Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate
moving alone is a sign the set is not actually lockstep — stop and look.
4. Build and run the offline suite:
```
cargo test --locked
cargo clippy --locked --all-targets -- -D warnings
```
5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish
path is slow and its circuit timeouts misbehave on hidden-service circuits,
and an upstream fix or behaviour change can make any of them wrong:
| constant | why | guard |
|---|---|---|
| `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` |
| `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` |
| `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` |
| `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` |
Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure
the rend handler is spawned *before* the probe wait, or the probe cannot
succeed at all.
6. Run the live two-node test on a networked machine. This is the only test that
proves the hidden service actually publishes and that a second node can
reach it:
```
cargo test --locked --test tor_hs -- --ignored --nocapture
```
It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant`
covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir
descriptor upload, not a hang), probe-connect against a live HS, a byte pipe
in both directions, restart, and the dormant/offline path.
7. Confirm the fail-closed path by hand if the publish wait changed at all:
with the write timeout still 360s, a peer whose onion is down must fail the
send. There is no outbox in v1 — the message must not be silently queued.
8. Rebuild the Android target — Arti's TLS backends are non-additive, and this
is the build that exercises the `rustls` feature:
```
scripts/build-android-local.sh
```
9. Verify the ciphertext claim still holds after the bump: send a message
between the two nodes, then
```
grep -r "<a distinctive message body>" <nodes' Arti state dirs and sqlite files>
```
must find nothing. The bodies live in sqlite as ciphertext, and nothing about
the plaintext should appear in Arti's state directory.
10. Open a PR against `main` describing: crates bumped, MSRV, the live-test
output, and anything upstream changed that touches `src/hs.rs`. Do not push
`main`; releases are minted by `.forgejo/workflows/release.yml` from a merge.
## Rolling back
Revert the version bump and the lockfile stanza together, re-run step 3's
`cargo update` only if the revert leaves the lockfile inconsistent, and re-run
`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and
`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the
intent.

View file

@ -19,7 +19,7 @@ SOCKS proxy.”
| Discovery | DHT + bootstrap nodes | Out-of-band invite only |
| After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion |
| Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator |
| Offline send | Expected (relays / retry) | Fail closed — no outbox |
| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) |
| Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers |
There is no directory, no name server, no introduction point of our own, and no
@ -51,8 +51,18 @@ not on the wire.
4. File transfer is N independent sessions (one handshake per chunk). There is
no multiplexed long-lived stream in v1.
If the onion is down, send fails. No retry queue except the locator-push path,
which retries for 180 seconds and then gives up.
If the onion is down, a **chat** send is persisted to the local outbox and
retried by a background worker with exponential backoff (30s, doubling, capped
at 30 min; 8 attempts, then terminal `Failed`). There is no server and no
store-and-forward relay: each attempt is a fresh handshake straight to
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
unlock/foreground, and whenever that peer is heard from (successful handshake or
`connect_onion()`). A protocol failure — signature mismatch, unknown frame,
oversize — is not a transport failure and is never queued.
File transfer and payment frames stay fail-closed: they are one-shot and are
**not** queued. The locator-push path still retries for 180 seconds and then
gives up.
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
Excess is dropped before handshake. That is availability, not anonymity.

View file

@ -16,15 +16,54 @@ A signed `loc` frame (`onion`, `ts`, `sig`) rewrites a friend’s locator **only
`F4` changes the locator only. The identity key is unchanged. Anyone who already has your pubkey can still prove they are talking to you, and a later invite paste with the same `k` updates their row. To become a new person, `/wipe-all` (new identity key). There is no in-band unfriend/revoke in v1.
## Message bodies are encrypted at rest; keys are not
## Your store is encrypted
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in the `messages.plaintext` column) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`. Swapping ciphertext between rows fails closed. A random 32-byte data key is wrapped with Argon2id (same params as identity backup) from a non-empty passphrase. Salt + wrapped key live in `store_meta`. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD.
The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`).
A 32-byte key is derived from the store passphrase with Argon2id (same params as
identity backup) over a per-install 16-byte salt in `store_salt`, and handed to
SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it.
The key is the first statement after open, so the file header, schema, identity
secret key, friend public keys, locators, profiles and payment rows are all
ciphertext on disk. There is no `identity_sk`-on-disk problem to work around
because `identity_sk` is inside the encrypted file. A wrong or empty passphrase
fails closed before any write; an encrypted store whose `store_salt` is missing
refuses to open instead of guessing.
Identity secret key, friend public keys, and locators remain plaintext in the same db. The message key is not wrapped with `identity_sk` (that key is already on disk). A seized laptop still yields who you talk to and your identity unless you add OS/FDE. sqlcipher is out of v1. `/wipe` deletes chat and payments history (overwrite message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data dir (new identity); same disk caveat.
v0.2.1 installs have a plaintext db. The first open with the right passphrase
upgrades it in place (`ATTACH … KEY` + `sqlcipher_export` after a WAL
checkpoint), and swaps the file in only after the new file opens, passes
`integrity_check` and unwraps `store_meta`. A wrong passphrase leaves the
plaintext file untouched. The `store_salt` file is not secret (a salt never is).
Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce ||
ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir ||
0x00 || row_id_le64`, plus a random 32-byte data key wrapped with Argon2id from
the same passphrase (`store_meta`). Whole-db encryption does not stop someone who
can write the file from moving one row's ciphertext into another row; the AAD
does, and it stays. Unlock is fail-closed: wrong or empty passphrase does not
open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages`
never falls back to empty AAD.
At-rest encryption is not a defense against a live compromise: while OnionWire
runs, the passphrase, the db key and decrypted bodies are in process memory, and
SQLCipher's page cache holds decrypted pages. It also does not stop an attacker
who has your passphrase. `/wipe` deletes chat and payments history (overwrite
message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a
forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data
dir (new identity); same disk caveat.
## Fail closed
Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
## Local outbox (chat retry queue) is local, and it re-dials on a schedule
A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted:
- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase.
- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure.
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
## Profile is friend-visible, not a directory
@ -65,5 +104,7 @@ the peer already knows the plaintext they sent.
## Out of v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,
sqlcipher, A/V.
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
relay, multi-device, DHT / name server, A/V. The local retry queue of the
previous section is not an outbox in the XMPP sense: it never leaves the device.

279
scripts/arti-watch.py Normal file
View file

@ -0,0 +1,279 @@
#!/usr/bin/env python3
"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins.
Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on
the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency
it reads the version requirement in Cargo.toml, asks crates.io for the newest
published versions, and — when the major.minor moved — files ONE Forgejo issue.
The issue title carries the compared pair, e.g.
Arti upstream: tor-hsservice 0.46 -> 0.47
Dedupe is on that title across all issues (open and closed), so a second run is
a no-op: no duplicate issue, no repeated comment. Nothing here bumps a
dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md.
What this does NOT cover, by design:
* It does not subscribe to Tor Project security announcements. A fix that
ships without a crates.io version bump is invisible to this script.
* It will not catch a yanked crate, and it will not catch a vulnerability in
a version that has not changed. crates.io `max_stable_version` already
ignores yanks, so a yank alone produces no alert.
Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself.
Usage:
FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \
scripts/arti-watch.py --cargo-toml Cargo.toml
scripts/arti-watch.py --dry-run # no API writes, no token
scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from dataclasses import dataclass
CRATES_API = "https://crates.io/api/v1/crates/{name}"
# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in
# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own.
USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)"
WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$")
# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch.
SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$")
def log(msg: str) -> None:
print(msg, flush=True)
class HardFail(SystemExit):
def __init__(self, msg: str) -> None:
super().__init__(2)
self.msg = msg
def curl_json(url, token=None, method="GET", body=None):
"""curl a JSON endpoint. Returns (http_status, parsed_body_or_None).
curl rather than urllib: the Cloudflare front door 403s a python-urllib
User-Agent, and curl's --retry covers transient 5xx.
"""
cmd = [
"curl", "-sS", "--http1.1",
"--retry", "5", "--retry-all-errors", "--retry-delay", "3",
"--connect-timeout", "20", "--max-time", "60",
"-H", f"User-Agent: {USER_AGENT}",
"-H", "Accept: application/json",
]
if token:
cmd += ["-H", f"Authorization: Bearer {token}"]
if body is not None:
cmd += ["-H", "Content-Type: application/json",
"-X", method, "--data-binary", json.dumps(body)]
cmd += ["-w", "\n%{http_code}", url]
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
if proc.returncode != 0:
raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}")
raw, _, code = proc.stdout.rpartition("\n")
try:
parsed = json.loads(raw) if raw.strip() else None
except json.JSONDecodeError:
parsed = None
return int(code or 0), parsed
def ver(text: str):
"""('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise
version format upstream is loud rather than silently 'not an upgrade'."""
m = SEMVER.match(text.strip())
if not m:
raise HardFail(f"cannot parse version {text!r}")
return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0))
def parse_pins(cargo_toml: str):
"""{crate: version_requirement} for the [dependencies] table only."""
pins: dict[str, str] = {}
section = ""
for line in cargo_toml.splitlines():
stripped = line.strip()
if stripped.startswith("["):
section = stripped.strip("[]").strip()
continue
if section != "dependencies" or not stripped or stripped.startswith("#"):
continue
m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped)
if not m:
continue
name, rest = m.group(1), m.group(2).split("#", 1)[0].strip()
if not WATCHED.match(name):
continue
vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest)
if vm:
pins[name] = vm.group(1)
return pins
def crates_io(name: str):
"""(stable, newest) version strings for a crate, as crates.io reports them."""
status, data = curl_json(CRATES_API.format(name=name))
if status != 200 or not isinstance(data, dict) or "crate" not in data:
raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})")
crate = data["crate"]
return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"]
@dataclass
class Row:
name: str
pin: str
pin_triple: tuple
stable: str
newest: str
source: str # "Cargo.toml" or "simulate-pin"
@property
def pin_minor(self) -> str:
return f"{self.pin_triple[0]}.{self.pin_triple[1]}"
@property
def upgrade(self) -> bool:
stable = ver(self.stable)
return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1])
def issue_title(row: Row) -> str:
stable = ver(row.stable)
return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}"
def issue_body(row: Row) -> str:
if row.source == "Cargo.toml":
lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**."
else:
lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, "
f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came "
f"from a `workflow_dispatch` test run — the repository pin has not changed.")
return f"""{lead}
| | |
|---|---|
| crate | `{row.name}` |
| pinned requirement | `"{row.pin}"` |
| pin source | {row.source} |
| newest stable upstream | `{row.stable}` |
| newest upstream (incl. pre-release) | `{row.newest}` |
| crates.io | https://crates.io/crates/{row.name} |
| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases |
Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole
`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do
not bump this one alone.
Procedure, toolchain floor, and the tests a bump must pass:
[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor
is rustc 1.91+ (Arti 0.46); a bump may raise it.
The watcher does **not** subscribe to Tor Project security announcements, and it
cannot see a yanked crate or a vulnerability that ships without a version bump.
"""
def existing_titles(repo_api: str, token: str) -> dict:
"""{title: issue_number} over every issue, open and closed, paginated."""
seen: dict[str, int] = {}
page = 1
while True:
url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}"
status, data = curl_json(url, token)
if status != 200 or not isinstance(data, list):
raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})")
for item in data:
seen[item["title"]] = item["number"]
if len(data) < 50:
return seen
page += 1
def main() -> int:
ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
ap.add_argument("--cargo-toml", default="Cargo.toml")
ap.add_argument("--dry-run", action="store_true",
help="compare and log only; file no issue and need no token")
ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION",
help="pretend CRATE is pinned at VERSION (test the alert path "
"against real crates.io data without waiting for upstream)")
args = ap.parse_args()
with open(args.cargo_toml, encoding="utf-8") as fh:
pins = parse_pins(fh.read())
if not pins:
raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}")
overrides = {}
for pair in args.simulate_pin:
name, _, version = pair.partition("=")
name, version = name.strip(), version.strip()
if name not in pins or not version:
raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}")
overrides[name] = version
rows = []
for name in sorted(pins):
source = "Cargo.toml"
pin = pins[name]
if name in overrides:
pin, source = overrides[name], "simulate-pin"
pin_triple = ver(pin)
stable, newest = crates_io(name)
rows.append(Row(name, pin, pin_triple, stable, newest, source))
log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):")
for row in rows:
log(f" {row.name}: pinned={row.pin} (from {row.source}) "
f"upstream_stable={row.stable} upstream_newest={row.newest} "
f"upgrade={'yes' if row.upgrade else 'no'}")
todo = [row for row in rows if row.upgrade]
if not todo:
log("no upgrade available: every pin already covers the newest upstream release")
return 0
if args.dry_run:
for row in todo:
log(f"dry-run: would file issue {issue_title(row)!r}")
return 0
repo_api = os.environ.get("REPO_API", "").rstrip("/")
token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split())
if not repo_api or not token:
raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run")
titles = existing_titles(repo_api, token)
filed = 0
for row in todo:
title = issue_title(row)
if title in titles:
log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one")
continue
status, created = curl_json(f"{repo_api}/issues", token, "POST",
{"title": title, "body": issue_body(row)})
if status != 201 or not isinstance(created, dict):
raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})")
filed += 1
log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})")
log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except HardFail as exc:
log(f"error: {exc.msg}")
sys.exit(exc.code)

View file

@ -5,6 +5,7 @@ pub mod frame;
pub mod hs;
pub mod loc;
pub mod node;
pub mod outbox;
pub mod pay;
pub mod profile;
pub mod qr;

View file

@ -14,6 +14,7 @@ use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT};
use crate::loc;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
use crate::profile;
use crate::qr;
@ -39,9 +40,18 @@ impl Drop for HsHandle {
}
}
/// Abort the outbox worker when the node goes away.
struct WorkerHandle(tokio::task::JoinHandle<()>);
impl Drop for WorkerHandle {
fn drop(&mut self) {
self.0.abort();
}
}
pub struct Node {
home: PathBuf,
store: Mutex<Store>,
store: Arc<Mutex<Store>>,
client: Client,
hs: Mutex<Option<HsHandle>>,
onion: Mutex<String>,
@ -49,6 +59,8 @@ pub struct Node {
wallet: Wallet,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
_outbox_worker: WorkerHandle,
}
impl Node {
@ -79,9 +91,17 @@ impl Node {
let (svc, rend) = launched;
let onion = hs::onion_string(&svc)?;
let inbox = file::Inbox::new(home.join("inbox"));
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(
Arc::clone(&store),
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
));
if let Err(e) = outbox.reset_stale() {
eprintln!("outbox: {e}");
}
let node = Arc::new(Self {
home,
store: Mutex::new(store),
store,
client,
hs: Mutex::new(None),
onion: Mutex::new(onion.clone()),
@ -89,7 +109,12 @@ impl Node {
wallet: Wallet::from_env(),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
});
// Unlock trigger: flush anything queued by a previous run now, in the
// background, rather than waiting out its backoff.
spawn_flush_all(Arc::clone(&node.outbox));
// Accept rens before waiting so a reachability probe can succeed
// while combined status is still Bootstrapping.
let rend = spawn_rend(Arc::clone(&node), rend);
@ -416,6 +441,8 @@ impl Node {
self.try_send(&onion, friend_pk, &prekey, plaintext).await
}
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
/// the outbox retry triggers.
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
tokio::time::timeout(
Duration::from_secs(20),
@ -424,6 +451,14 @@ impl Node {
.await
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
if let Ok(Some(friend)) = self
.store
.lock()
.map_err(|e| e.to_string())
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
{
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
}
Ok(())
}
@ -506,36 +541,30 @@ impl Node {
Ok(name)
}
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
let (onion, prekey) = {
let store = self.store.lock().map_err(|e| e.to_string())?;
let f = store
.get_friend(friend_pk)
.map_err(|e| e.to_string())?
.ok_or_else(|| "unknown friend".to_string())?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
(f.onion, f.prekey)
};
let deadline = Instant::now() + Duration::from_secs(180);
let mut last = None::<String>;
while Instant::now() < deadline {
match self.try_send(&onion, friend_pk, &prekey, plaintext).await {
Ok(()) => {
self.store
.lock()
.map_err(|e| e.to_string())?
.append_message(friend_pk, "out", plaintext)
.map_err(|e| e.to_string())?;
return Ok(());
}
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
Err(e) => last = Some(e),
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
Err(last.unwrap_or_else(|| "send timed out".into()))
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
/// when the peer's onion is unreachable — the outbox worker then retries with
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
/// frame) still fails immediately and is never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
self.outbox.send(friend_pk, plaintext).await
}
/// Pending and failed outbox rows for a friend, for UI surfacing.
/// Delivered rows are dropped, so a message absent here was sent.
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
self.outbox.pending(friend_pk)
}
pub fn outbox_status_of_message(
&self,
message_id: i64,
) -> Result<Option<OutboxStatus>, String> {
self.outbox.status_of_message(message_id)
}
/// Foreground/unlock trigger: try every outstanding queued send now.
pub fn flush_outbox(&self) {
spawn_flush_all(Arc::clone(&self.outbox));
}
async fn push_loc(
@ -568,20 +597,10 @@ impl Node {
remote_prekey: &[u8],
plaintext: &[u8],
) -> Result<(), String> {
let mut stream = self
.client
.connect((onion, HS_PORT))
self.outbox
.deliverer()
.deliver(onion, pinned_id, remote_prekey, plaintext)
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let keys = self.keys()?;
let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey)
.await
.map_err(session_err)?;
let ct = sess.encrypt(plaintext).map_err(session_err)?;
frame::write_frame(&mut stream, &ct)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
@ -598,6 +617,9 @@ impl Node {
})
.await
.map_err(session_err)?;
// Trigger (c): the peer just proved they are online. Try their queued
// sends now instead of waiting out the backoff, off this stream's path.
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
let pt = sess.decrypt(&ct).map_err(session_err)?;
match dispatch::classify(&pt) {
@ -814,6 +836,24 @@ fn spawn_rend(
})
}
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
fn spawn_flush_all(outbox: Arc<Outbox>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_all(unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
/// We just saw this peer (handshake or successful dial): try their queue now.
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")

308
src/outbox.rs Normal file
View file

@ -0,0 +1,308 @@
//! Local-only outbox.
//!
//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and
//! retried by a background worker with exponential backoff. There is no server
//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake
//! straight to the friend's onion, so a queued message is never handed to a
//! third party. File transfer and payment frames stay fail-closed — only chat
//! goes through here.
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::Notify;
use crate::frame;
use crate::hs::{Client, HS_PORT};
use crate::session::{self, Keys};
use crate::store::Store;
pub use crate::store::{OutboxEntry, OutboxStatus};
/// First retry waits this long.
pub const BACKOFF_START_SECS: i64 = 30;
/// Backoff never sleeps longer than this.
pub const BACKOFF_CAP_SECS: i64 = 1_800;
/// Attempts after which a queued message is terminally `Failed`.
pub const DEFAULT_MAX_ATTEMPTS: u32 = 8;
/// Worker scan period. The shortest backoff is 30s, so a slower scan still
/// lands each retry close to its schedule without busy-waiting.
pub const WORKER_TICK: Duration = Duration::from_secs(15);
/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the
/// worker.
const MAX_PER_PASS: i64 = 32;
pub type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s…
/// capped at 30 min. `attempt` is the number of retries already made.
pub fn backoff_secs(attempt: u32) -> i64 {
// 30 << 16 is the largest shift we ever need to reach the cap, so this
// cannot overflow even for a silly attempt count.
(BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS)
}
/// Protocol failures: another attempt cannot fix a bad signature, a bad frame
/// header, or an oversize payload, so they must fail loudly and never queue.
const PERMANENT_ERRORS: &[&str] = &[
"fingerprint mismatch",
"bad identity proof",
"unexpected handshake payload",
"frame too large",
"bad version",
"length mismatch",
"short frame",
];
pub fn is_permanent_send_error(err: &str) -> bool {
PERMANENT_ERRORS.iter().any(|p| err.contains(p))
}
/// One delivery attempt. Implemented by Arti for real sends and by tests for a
/// fake or flaky peer.
pub trait Deliverer: Send + Sync {
fn deliver<'a>(
&'a self,
onion: &'a str,
pinned_id: &'a [u8],
prekey: &'a [u8],
plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>>;
}
/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's
/// identity key, send exactly one application frame, drop the circuit.
pub struct ArtiDeliverer {
client: Client,
keys: Keys,
}
impl ArtiDeliverer {
pub fn new(client: Client, keys: Keys) -> Self {
Self { client, keys }
}
}
impl Deliverer for ArtiDeliverer {
fn deliver<'a>(
&'a self,
onion: &'a str,
pinned_id: &'a [u8],
prekey: &'a [u8],
plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async move {
let mut stream = self
.client
.connect((onion, HS_PORT))
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let mut sess =
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
.await
.map_err(|e| e.into_message())?;
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
frame::write_frame(&mut stream, &ct)
.await
.map_err(|e| e.to_string())?;
Ok(())
})
}
}
pub struct Outbox {
store: Arc<Mutex<Store>>,
deliverer: Arc<dyn Deliverer>,
max_attempts: u32,
wake: Notify,
}
impl Outbox {
pub fn new(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>) -> Self {
Self {
store,
deliverer,
max_attempts: DEFAULT_MAX_ATTEMPTS,
wake: Notify::new(),
}
}
pub fn with_max_attempts(mut self, max: u32) -> Self {
self.max_attempts = max.max(1);
self
}
/// The transport, for callers (locator/profile pushes) that stay fail-closed
/// and must not queue.
pub fn deliverer(&self) -> &dyn Deliverer {
self.deliverer.as_ref()
}
/// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is
/// unreachable, the message is persisted and will be retried. `Err` — a
/// protocol error or a bad local state, never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
let (onion, prekey) = self.target(friend_pk)?;
match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await {
Ok(()) => {
self.store()?.append_message(friend_pk, "out", plaintext)?;
Ok(OutboxStatus::Sent)
}
Err(e) if is_permanent_send_error(&e) => Err(e),
Err(e) => {
let now = unix_now();
let store = self.store()?;
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
store.enqueue_outbox(
friend_pk,
message_id,
1,
now + backoff_secs(0),
&e,
now,
)?;
Ok(OutboxStatus::Queued)
}
}
}
/// Timer trigger: every row whose backoff has elapsed gets one attempt.
pub async fn tick(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
let due = self.store()?.due_outbox(now, MAX_PER_PASS)?;
self.attempt(due, now).await
}
/// Unlock / foreground trigger: every outstanding row gets one attempt now,
/// regardless of where it sits in the backoff.
pub async fn flush_all(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?;
self.attempt(rows, now).await
}
/// Trigger (c): we just heard from this peer, so try their rows immediately.
pub async fn flush_friend(
&self,
friend_pk: &[u8],
now: i64,
) -> Result<Vec<(i64, OutboxStatus)>, String> {
let rows = self.store()?.outbox_for_friend(friend_pk)?;
self.attempt(rows, now).await
}
/// Pending and failed rows for one friend. Delivered rows are deleted, so a
/// message that is not here was either sent first try or flushed since.
pub fn pending(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>, String> {
self.store()?.pending_outbox(friend_pk).map_err(store_err)
}
pub fn status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>, String> {
self.store()?
.outbox_status_of_message(message_id)
.map_err(store_err)
}
/// A process that died mid-attempt leaves `sending` rows behind; requeue
/// them on unlock so they are retried instead of stranded.
pub fn reset_stale(&self) -> Result<usize, String> {
self.store()?.reset_sending_outbox().map_err(store_err)
}
/// Wake the worker (e.g. after `flush_all` was queued from a UI thread).
pub fn kick(&self) {
self.wake.notify_one();
}
/// Background retry worker. Aborted by dropping the returned handle.
pub fn spawn_worker(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
let me = Arc::clone(self);
tokio::spawn(async move {
loop {
if let Err(e) = me.tick(unix_now()).await {
eprintln!("outbox: {e}");
}
tokio::select! {
_ = tokio::time::sleep(WORKER_TICK) => {}
_ = me.wake.notified() => {}
}
}
})
}
async fn attempt(
&self,
rows: Vec<OutboxEntry>,
now: i64,
) -> Result<Vec<(i64, OutboxStatus)>, String> {
let mut out = Vec::with_capacity(rows.len());
for entry in rows {
self.store()?.mark_outbox_sending(entry.id, now)?;
let (onion, prekey) = match self.target(&entry.friend_pk) {
Ok(t) => t,
Err(e) => {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
out.push((entry.id, OutboxStatus::Failed(e)));
continue;
}
};
let result = self
.deliverer
.deliver(&onion, &entry.friend_pk, &prekey, &entry.body)
.await;
let status = match result {
Ok(()) => {
self.store()?.mark_outbox_sent(entry.id)?;
OutboxStatus::Sent
}
Err(e) if is_permanent_send_error(&e) => {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
OutboxStatus::Failed(e)
}
Err(e) => {
let attempts = entry.attempts.saturating_add(1);
if attempts >= self.max_attempts {
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
OutboxStatus::Failed(e)
} else {
let next = now + backoff_secs(attempts - 1);
self.store()?
.mark_outbox_retry(entry.id, attempts, next, now, &e)?;
OutboxStatus::Queued
}
}
};
out.push((entry.id, status));
}
Ok(out)
}
/// Friend's current locator + Noise static. Missing prekey means the invite
/// was never completed — retrying cannot fix that, so it is fatal.
fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec<u8>), String> {
let store = self.store()?;
let f = store
.get_friend(friend_pk)
.map_err(store_err)?
.ok_or_else(|| "unknown friend".to_string())?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
Ok((f.onion, f.prekey))
}
fn store(&self) -> Result<MutexGuard<'_, Store>, String> {
self.store.lock().map_err(|e| e.to_string())
}
}
fn store_err(e: crate::store::Error) -> String {
e.to_string()
}
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}

View file

@ -35,6 +35,16 @@ impl Error {
pub fn is_fingerprint_mismatch(&self) -> bool {
self.mismatch
}
/// String for the UI: a pinned-identity mismatch gets the documented banner,
/// everything else is the underlying snow/framing message.
pub fn into_message(self) -> String {
if self.mismatch {
crate::tui::fingerprint_mismatch_banner().to_string()
} else {
self.msg
}
}
}
impl std::fmt::Display for Error {

View file

@ -1,4 +1,5 @@
use std::fs;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@ -40,6 +41,15 @@ impl From<String> for Error {
}
}
/// The store error is a message and nothing else, and the rest of the crate
/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the
/// outbox boundary — no per-call `map_err`.
impl From<Error> for String {
fn from(e: Error) -> Self {
e.0
}
}
pub struct Store {
conn: Connection,
msg_key: [u8; 32],
@ -88,6 +98,64 @@ pub struct Payment {
pub created_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutboxStatus {
Queued,
Sending,
Sent,
/// Terminal: transport or protocol failure that will not be retried.
Failed(String),
}
impl OutboxStatus {
pub fn is_terminal(&self) -> bool {
matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_))
}
/// Column encoding for the `outbox.status` CHECK constraint.
pub fn as_db_str(&self) -> &'static str {
match self {
OutboxStatus::Queued => "queued",
OutboxStatus::Sending => "sending",
OutboxStatus::Sent => "sent",
OutboxStatus::Failed(_) => "failed",
}
}
pub fn from_db(status: &str, last_error: Option<&str>) -> Self {
match status {
"sending" => OutboxStatus::Sending,
"sent" => OutboxStatus::Sent,
"failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()),
_ => OutboxStatus::Queued,
}
}
}
impl std::fmt::Display for OutboxStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OutboxStatus::Failed(why) => write!(f, "failed: {why}"),
other => f.write_str(other.as_db_str()),
}
}
}
/// One queued chat send. The body is not copied: it lives in the `messages`
/// row the outbox row points at, under that row's own AEAD.
#[derive(Debug, Clone)]
pub struct OutboxEntry {
pub id: i64,
pub friend_pk: Vec<u8>,
pub message_id: i64,
pub body: Vec<u8>,
pub attempts: u32,
pub next_attempt_at: i64,
pub created_at: i64,
pub status: OutboxStatus,
pub last_error: Option<String>,
}
pub struct PaymentWrite<'a> {
pub dir: &'a str,
pub kind: &'a str,
@ -119,7 +187,7 @@ impl Store {
mkdir_700(&home.join("arti"))?;
mkdir_700(&home.join("cache"))?;
let db_path = home.join("onionwire.db");
let conn = Connection::open(&db_path)?;
let conn = open_store_db(home, &db_path, passphrase)?;
let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
if !journal.eq_ignore_ascii_case("wal") {
return Err(Error(format!("journal_mode WAL failed: {journal}")));
@ -189,6 +257,18 @@ impl Store {
verified INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
message_id INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
last_error TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
",
)?;
@ -475,6 +555,20 @@ impl Store {
.map_err(Into::into)
}
/// Locator → friend. Onions are not unique in the schema (a stale row can
/// hold a rotated address), so the first match wins; the outbox uses this
/// only to pick which queue to flush early.
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
params![onion],
friend_from_row,
)
.optional()
.map_err(Into::into)
}
pub fn list_friends(&self) -> Result<Vec<Friend>> {
let mut stmt = self.conn.prepare(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
@ -699,6 +793,17 @@ impl Store {
}
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
}
/// Same as `append_message`, returning the row id so an outbox row can
/// point at the body instead of storing a second copy.
pub fn append_message_id(
&self,
friend_pk: &[u8],
dir: &str,
plaintext: &[u8],
) -> Result<i64> {
if dir != "in" && dir != "out" {
return Err(Error("dir must be in or out".into()));
}
@ -723,7 +828,7 @@ impl Store {
params![blob, row_id],
)?;
tx.commit()?;
Ok(())
Ok(row_id)
}
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
@ -752,9 +857,194 @@ impl Store {
Ok(out)
}
/// Queue one already-stored chat message for retry. `next_attempt_at` is an
/// absolute unix second; `now` is used for created_at/updated_at so the
/// caller and the row agree on the clock.
pub fn enqueue_outbox(
&self,
friend_pk: &[u8],
message_id: i64,
attempts: u32,
next_attempt_at: i64,
last_error: &str,
now: i64,
) -> Result<i64> {
let friend_id: i64 = self
.conn
.query_row(
"SELECT id FROM friends WHERE pubkey = ?1",
params![friend_pk],
|row| row.get(0),
)
.map_err(|_| Error("friend not found".into()))?;
self.conn.execute(
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)",
params![friend_id, message_id, attempts, next_attempt_at, last_error, now],
)?;
Ok(self.conn.last_insert_rowid())
}
/// Rows whose backoff has elapsed: the timer trigger for the worker.
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1
ORDER BY o.next_attempt_at, o.id LIMIT ?2"
),
params![now, limit],
)
}
/// Unscheduleable rows for one friend (queued or mid-attempt): the
/// "we just heard from this peer" trigger, which ignores the backoff.
pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending')
ORDER BY o.id"
),
params![friend_pk],
)
}
/// Every row the worker may still try: the unlock/foreground trigger.
pub fn all_pending_outbox(&self, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status IN ('queued','sending')
ORDER BY o.next_attempt_at, o.id LIMIT ?1"
),
params![limit],
)
}
/// Pending and failed rows for one friend — what a UI shows as not-yet-sent.
/// Delivered rows are deleted, so absence means "sent".
pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed')
ORDER BY o.id"
),
params![friend_pk],
)
}
pub fn outbox_status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>> {
let row: Option<(String, Option<String>)> = self
.conn
.query_row(
"SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1",
params![message_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref())))
}
pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2",
params![now, id],
)?;
Ok(())
}
/// Delivered. The row is dropped — the chat history is the record, and a
/// per-message status table would grow without bound.
pub fn mark_outbox_sent(&self, id: i64) -> Result<()> {
self.conn
.execute("DELETE FROM outbox WHERE id = ?1", params![id])?;
Ok(())
}
pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3",
params![why, now, id],
)?;
Ok(())
}
pub fn mark_outbox_retry(
&self,
id: i64,
attempts: u32,
next_attempt_at: i64,
now: i64,
why: &str,
) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5",
params![attempts, next_attempt_at, why, now, id],
)?;
Ok(())
}
/// A row left in 'sending' means we died mid-attempt. Requeue on unlock.
pub fn reset_sending_outbox(&self) -> Result<usize> {
let n = self.conn.execute(
"UPDATE outbox SET status = 'queued' WHERE status = 'sending'",
[],
)?;
Ok(n)
}
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(args, |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, Vec<u8>>(1)?,
row.get::<_, i64>(2)?,
row.get::<_, i64>(3)?,
row.get::<_, i64>(4)?,
row.get::<_, String>(5)?,
row.get::<_, Option<String>>(6)?,
row.get::<_, i64>(7)?,
row.get::<_, i64>(8)?,
row.get::<_, String>(9)?,
row.get::<_, Vec<u8>>(10)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (
id,
friend_pk,
message_id,
attempts,
next_attempt_at,
status,
last_error,
created_at,
m_friend_id,
dir,
blob,
) = row?;
let aad = message_aad(m_friend_id, &dir, message_id);
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("outbox body decrypt failed".into()))?;
out.push(OutboxEntry {
id,
friend_pk,
message_id,
body,
attempts: attempts as u32,
next_attempt_at,
created_at,
status: OutboxStatus::from_db(&status, last_error.as_deref()),
last_error,
});
}
Ok(out)
}
/// Drop chat + payments history. Identity + friends stay.
/// Not a forensic erase: SSD wear-leveling can keep copies.
pub fn wipe_messages(&self) -> Result<()> {
self.conn.execute("DELETE FROM outbox", [])?;
self.conn.execute(
"UPDATE messages SET plaintext = zeroblob(length(plaintext))",
[],
@ -815,6 +1105,187 @@ fn gen_prekey() -> (Vec<u8>, Vec<u8>) {
(sk.to_bytes().to_vec(), pk.to_bytes().to_vec())
}
/// Per-install KDF salt for the whole-database key. Not secret (a salt never
/// is); kept in the data dir so the db key never has to live inside the db it
/// opens.
const SALT_FILE: &str = "store_salt";
const SQLITE_HEADER: &[u8] = b"SQLite format 3\0";
enum DbState {
Missing,
Empty,
Plaintext,
Encrypted,
}
fn db_state(path: &Path) -> Result<DbState> {
let meta = match fs::metadata(path) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(DbState::Missing),
Err(e) => return Err(e.into()),
};
if meta.len() == 0 {
return Ok(DbState::Empty);
}
let mut head = [0u8; 16];
let mut f = fs::File::open(path)?;
match f.read_exact(&mut head) {
Ok(()) if head.as_slice() == SQLITE_HEADER => Ok(DbState::Plaintext),
Ok(()) => Ok(DbState::Encrypted),
Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(DbState::Encrypted),
Err(e) => Err(e.into()),
}
}
fn read_salt(path: &Path) -> Result<Option<[u8; 16]>> {
match fs::read(path) {
Ok(b) if b.len() == 16 => Ok(Some(b.try_into().expect("len checked"))),
Ok(b) => Err(Error(format!("{SALT_FILE} has {} bytes, want 16", b.len()))),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
fn write_salt(path: &Path, salt: &[u8; 16]) -> Result<()> {
fs::write(path, salt)?;
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(0o600);
fs::set_permissions(path, perms)?;
Ok(())
}
fn random_salt() -> [u8; 16] {
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
salt
}
/// Opens the store, creating it encrypted and upgrading a v0.2.1 plaintext
/// file in place. Any failure before the swap leaves the old file untouched.
fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connection> {
let salt_path = home.join(SALT_FILE);
let mut salt = read_salt(&salt_path)?;
match db_state(db_path)? {
DbState::Plaintext => {
let conn = Connection::open(db_path)?;
let ok = wrapped_key_opens(&conn, passphrase)?;
drop(conn);
if !ok {
return Err(Error("wrong passphrase".into()));
}
let s = salt.unwrap_or_else(random_salt);
let key = crate::backup::kdf(passphrase, &s)?;
write_salt(&salt_path, &s)?;
migrate_plaintext_to_encrypted(db_path, &key, passphrase)?;
salt = Some(s);
}
DbState::Missing | DbState::Empty => {
if salt.is_none() {
let s = random_salt();
write_salt(&salt_path, &s)?;
salt = Some(s);
}
}
DbState::Encrypted => {}
}
let Some(salt) = salt else {
return Err(Error(format!(
"{SALT_FILE} is missing next to an encrypted onionwire.db; restore it from \
your backup, or restore the db from backup and re-import"
)));
};
let key = crate::backup::kdf(passphrase, &salt)?;
open_keyed(db_path, &key)
}
/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is
/// the key, with no second KDF pass over it.
fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
let conn = Connection::open(db_path)?;
conn.execute_batch(&pragma_key(key))?;
// A rejected key otherwise logs SQLCipher's internal "hmac check failed"
// at ERROR to stderr. A wrong passphrase is a normal user error here.
let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE");
// Force a read so a wrong key fails here, not on the first later query.
conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| {
r.get::<_, i64>(0)
})
.map_err(|_| Error("wrong passphrase or corrupt store".into()))?;
Ok(conn)
}
fn pragma_key(key: &[u8; 32]) -> String {
format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key))
}
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
/// store) accepts any passphrase, matching the v0.2.1 behaviour.
fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result<bool> {
let row: Option<(Vec<u8>, Vec<u8>)> = conn
.query_row(
"SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let Some((salt, wrapped)) = row else {
return Ok(true);
};
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok())
}
/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in.
/// The source file is only replaced after the new file opens, passes
/// `integrity_check` and unlocks with this passphrase.
fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &str) -> Result<()> {
let mut tmp_name = db_path.as_os_str().to_owned();
tmp_name.push(".migrating");
let tmp = PathBuf::from(tmp_name);
let _ = fs::remove_file(&tmp);
let mode = fs::metadata(db_path)?.permissions().mode() & 0o777;
{
// Fold the WAL in so the export sees every committed row.
let conn = Connection::open(db_path)?;
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
let target = tmp.to_string_lossy().replace('\'', "''");
conn.execute_batch(&format!(
"ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";",
hex = fingerprint(key)
))?;
conn.execute_batch("SELECT sqlcipher_export('enc');")?;
conn.execute_batch("DETACH DATABASE enc;")?;
}
let verified = (|| -> Result<()> {
let conn = open_keyed(&tmp, key)?;
let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?;
if check != "ok" {
return Err(Error(format!("migration integrity_check: {check}")));
}
if !wrapped_key_opens(&conn, passphrase)? {
return Err(Error("migrated store failed to unlock".into()));
}
Ok(())
})();
if let Err(e) = verified {
let _ = fs::remove_file(&tmp);
return Err(e);
}
fs::rename(&tmp, db_path)?;
let mut perms = fs::metadata(db_path)?.permissions();
perms.set_mode(mode);
fs::set_permissions(db_path, perms)?;
for suffix in ["-wal", "-shm"] {
let mut stale = db_path.as_os_str().to_owned();
stale.push(suffix);
let _ = fs::remove_file(PathBuf::from(stale));
}
Ok(())
}
fn home_dir() -> Result<PathBuf> {
if let Some(p) = std::env::var_os("ONIONWIRE_HOME") {
return Ok(PathBuf::from(p));
@ -859,6 +1330,12 @@ fn mkdir_700(path: &Path) -> Result<()> {
Ok(())
}
/// Base projection for outbox rows: the body comes from the `messages` row the
/// outbox row points at, so it stays under that row's AEAD + AAD.
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec<u8> {
let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8);
@ -1027,6 +1504,211 @@ mod at_rest {
}
}
/// The exact v0.2.1 on-disk layout, hand-built: a plaintext sqlite file with
/// the identity row in the clear, a `store_meta` row holding the
/// Argon2id-wrapped message key and ChaCha20-Poly1305 message rows bound to
/// their row AAD. Pin it here so the migration test cannot drift with the
/// production schema.
const LEGACY_SCHEMA: &str = "
CREATE TABLE friends (
id INTEGER PRIMARY KEY,
pubkey BLOB NOT NULL UNIQUE,
fingerprint TEXT NOT NULL,
petname TEXT,
onion TEXT NOT NULL,
onion_updated_at INTEGER NOT NULL,
added_at INTEGER NOT NULL,
last_connect_ok INTEGER NOT NULL DEFAULT 1,
prekey BLOB NOT NULL DEFAULT x''
);
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
plaintext BLOB NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE self (
id INTEGER PRIMARY KEY CHECK (id = 1),
identity_sk BLOB NOT NULL,
identity_pk BLOB NOT NULL,
onion TEXT NOT NULL,
onion_rotated_at INTEGER NOT NULL,
prekey_sk BLOB NOT NULL,
prekey_pk BLOB NOT NULL,
hs_nickname TEXT NOT NULL DEFAULT 'ow0'
);
CREATE TABLE self_profile (
id INTEGER PRIMARY KEY CHECK (id = 1),
display_name TEXT NOT NULL DEFAULT '',
bio TEXT NOT NULL DEFAULT '',
xmr_addr TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE friend_profiles (
pubkey BLOB PRIMARY KEY,
display_name TEXT NOT NULL,
bio TEXT NOT NULL,
xmr_addr TEXT NOT NULL DEFAULT '',
updated_at INTEGER NOT NULL
);
CREATE TABLE store_meta (
id INTEGER PRIMARY KEY CHECK (id = 1),
kdf_salt BLOB NOT NULL,
wrapped_key BLOB NOT NULL
);
CREATE TABLE payments (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
dir TEXT NOT NULL CHECK(dir IN ('in','out')),
kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')),
amount_atomic TEXT NOT NULL,
address TEXT NOT NULL,
memo TEXT NOT NULL DEFAULT '',
txid TEXT,
verified INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
";
const LEGACY_IDENTITY_SK: [u8; 32] = [0x11; 32];
const LEGACY_FRIEND_PK: [u8; 32] = [0x55; 32];
/// Writes a v0.2.1 store at `db_path` with no encryption at all.
fn write_legacy_plaintext_store(db_path: &Path, passphrase: &str) {
let conn = Connection::open(db_path).unwrap();
conn.execute_batch(LEGACY_SCHEMA).unwrap();
conn.execute(
"INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname)
VALUES (1, ?1, ?2, 'legacy.onion', 7, ?3, ?4, 'ow0')",
params![
LEGACY_IDENTITY_SK.to_vec(),
vec![0x22u8; 32],
vec![0x33u8; 32],
vec![0x44u8; 32]
],
)
.unwrap();
conn.execute(
"INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at, last_connect_ok, prekey)
VALUES (?1, ?2, 'legacy-friend', 'legacy-friend.onion', 7, 7, 1, x'')",
params![LEGACY_FRIEND_PK.as_slice(), fingerprint(&LEGACY_FRIEND_PK)],
)
.unwrap();
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
let mut data_key = [0u8; 32];
OsRng.fill_bytes(&mut data_key);
let wrap = crate::backup::kdf(passphrase, &salt).unwrap();
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key, b"").unwrap();
conn.execute(
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
params![salt.as_slice(), wrapped],
)
.unwrap();
for (dir, body) in [
("in", "legacy-body-xyz"),
("out", "legacy-reply-xyz"),
] {
conn.execute(
"INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)",
params![dir],
)
.unwrap();
let id = conn.last_insert_rowid();
let blob = crate::backup::aead_encrypt(
&data_key,
body.as_bytes(),
&message_aad(1, dir, id),
)
.unwrap();
conn.execute(
"UPDATE messages SET plaintext = ?1 WHERE id = ?2",
params![blob, id],
)
.unwrap();
}
conn.close().unwrap();
}
fn file_has(path: &Path, needle: &[u8]) -> bool {
let Ok(bytes) = std::fs::read(path) else {
return false;
};
bytes.windows(needle.len()).any(|w| w == needle)
}
#[test]
fn plaintext_v0_2_1_store_is_encrypted_in_place_and_keeps_history() {
let dir = tempfile::tempdir().unwrap();
let db_path = dir.path().join("onionwire.db");
write_legacy_plaintext_store(&db_path, "legacy-pass");
let raw = std::fs::read(&db_path).unwrap();
assert!(
raw.starts_with(b"SQLite format 3\0"),
"fixture must be a plaintext sqlite file"
);
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
assert_eq!(store.self_identity().unwrap().identity_sk, LEGACY_IDENTITY_SK);
let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap();
assert_eq!(msgs.len(), 2, "history must survive the upgrade");
assert_eq!(msgs[0].plaintext, b"legacy-body-xyz");
assert_eq!(msgs[1].plaintext, b"legacy-reply-xyz");
assert_eq!(
store.get_friend(&LEGACY_FRIEND_PK).unwrap().unwrap().onion,
"legacy-friend.onion"
);
drop(store);
let enc = std::fs::read(&db_path).unwrap();
assert!(
!enc.starts_with(b"SQLite format 3\0"),
"db header must be encrypted after the in-place upgrade"
);
for (needle, what) in [
(b"legacy-body-xyz".to_vec(), "message body"),
(fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"),
(LEGACY_IDENTITY_SK.to_vec(), "identity secret"),
(b"legacy-friend.onion".to_vec(), "locator"),
] {
assert!(
!file_has(&db_path, &needle),
"upgraded db still contains the {what}"
);
}
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("reopen");
assert_eq!(store.list_messages(&LEGACY_FRIEND_PK).unwrap().len(), 2);
}
#[test]
fn legacy_plaintext_store_with_wrong_passphrase_is_left_untouched() {
let dir = tempfile::tempdir().unwrap();
let db_path = dir.path().join("onionwire.db");
write_legacy_plaintext_store(&db_path, "legacy-pass");
let before = std::fs::read(&db_path).unwrap();
let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") {
Ok(_) => panic!("wrong passphrase must not open a legacy store"),
Err(e) => e,
};
assert!(
err.to_string().to_ascii_lowercase().contains("passphrase"),
"got {err}"
);
assert_eq!(
std::fs::read(&db_path).unwrap(),
before,
"a failed legacy upgrade must not modify the plaintext db"
);
assert!(
!dir.path().join("store_salt").exists(),
"a failed legacy upgrade must not leave a salt file behind"
);
}
#[test]
fn first_unlock_reencrypts_legacy_plaintext_rows() {
let dir = tempfile::tempdir().unwrap();

View file

@ -1449,8 +1449,10 @@ impl App {
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move {
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
// footer is a follow-up card, so this arm keeps today's wording.
let note = match node.send(&pk, &body).await {
Ok(()) => "sent".to_string(),
Ok(_) => "sent".to_string(),
Err(e) => format!("send failed: {e}"),
};
let _ = tx.send(note);

312
tests/outbox.rs Normal file
View file

@ -0,0 +1,312 @@
//! Local outbox: queue a chat send when the peer's onion is unreachable, retry
//! with exponential backoff, expose a terminal status. All offline — the
//! transport is a fake deliverer, so these run without Tor.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use onionwire::outbox::{
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
is_permanent_send_error,
};
use onionwire::Store;
const PASS: &str = "outbox-pass";
fn pk(tag: u8) -> [u8; 32] {
let mut k = [0u8; 32];
k[0] = tag;
k
}
/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext.
struct Flaky {
fail_times: AtomicUsize,
err: String,
calls: AtomicUsize,
delivered: Mutex<Vec<Vec<u8>>>,
}
impl Flaky {
fn new(fail_times: usize, err: &str) -> Arc<Self> {
Arc::new(Self {
fail_times: AtomicUsize::new(fail_times),
err: err.into(),
calls: AtomicUsize::new(0),
delivered: Mutex::new(Vec::new()),
})
}
fn calls(&self) -> usize {
self.calls.load(Ordering::SeqCst)
}
fn delivered(&self) -> Vec<Vec<u8>> {
self.delivered.lock().unwrap().clone()
}
}
impl Deliverer for Flaky {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
self.calls.fetch_add(1, Ordering::SeqCst);
let left = self.fail_times.load(Ordering::SeqCst);
if left > 0 {
self.fail_times.fetch_sub(1, Ordering::SeqCst);
let err = self.err.clone();
return Box::pin(async move { Err(err) });
}
self.delivered.lock().unwrap().push(plaintext.to_vec());
Box::pin(async move { Ok(()) })
}
}
fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc<Mutex<Store>> {
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
store.upsert_friend(&pk(1), onion, None).unwrap();
store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap();
Arc::new(Mutex::new(store))
}
fn outbox(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>, max_attempts: u32) -> Outbox {
Outbox::new(store, deliverer).with_max_attempts(max_attempts)
}
#[test]
fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
assert_eq!(BACKOFF_START_SECS, 30);
assert_eq!(BACKOFF_CAP_SECS, 1800);
let got: Vec<i64> = (0..9).map(backoff_secs).collect();
assert_eq!(
got,
vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800],
"exponential backoff, capped"
);
assert_eq!(
backoff_secs(u32::MAX),
BACKOFF_CAP_SECS,
"no overflow at silly attempt counts"
);
}
#[test]
fn transport_errors_are_retryable_protocol_errors_are_not() {
assert!(!is_permanent_send_error(
"connect abc.onion:80: timed out"
));
assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
assert!(is_permanent_send_error("fingerprint mismatch"));
assert!(is_permanent_send_error("frame too large"));
assert!(is_permanent_send_error("bad version"));
assert!(is_permanent_send_error("bad identity proof"));
}
#[tokio::test]
async fn send_to_dead_onion_is_queued_and_row_persists() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "dead.onion");
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead, 8);
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap();
assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err");
assert!(!status.is_terminal());
let pending = ob.pending(&pk(1)).unwrap();
assert_eq!(pending.len(), 1, "one outbox row");
assert_eq!(pending[0].status, OutboxStatus::Queued);
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
assert!(
ob.status_of_message(pending[0].message_id).unwrap().is_some(),
"status is addressable by chat row id"
);
// The chat line is already in local history while it waits.
let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap();
assert_eq!(msgs.len(), 1);
assert_eq!(msgs[0].dir, "out");
assert_eq!(msgs[0].plaintext, b"hello dead peer");
}
#[tokio::test]
async fn flaky_peer_is_flushed_by_the_worker_on_schedule() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "flaky.onion");
// First dial fails (the immediate one), the rest succeed: "peer came up".
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
let status = ob.send(&pk(1), b"late hello").await.unwrap();
assert_eq!(status, OutboxStatus::Queued);
let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
assert_eq!(
next - ob.pending(&pk(1)).unwrap()[0].created_at,
BACKOFF_START_SECS,
"first retry waits the start of the schedule"
);
// Too early: the worker must not dial out of schedule.
let t0 = next - BACKOFF_START_SECS;
let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap();
assert!(fired.is_empty(), "not due yet");
let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap();
assert_eq!(fired.len(), 1);
assert_eq!(fired[0].1, OutboxStatus::Sent);
assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]);
assert!(
ob.pending(&pk(1)).unwrap().is_empty(),
"delivered rows leave the pending set"
);
}
#[tokio::test]
async fn max_attempts_reaches_failed_and_stops_retrying() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "gone.onion");
let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead.clone(), 3);
assert_eq!(
ob.send(&pk(1), b"never lands").await.unwrap(),
OutboxStatus::Queued
);
assert_eq!(dead.calls(), 1, "immediate attempt");
// Walk the schedule forward; each tick is one more attempt.
let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
let mut last = OutboxStatus::Queued;
for _ in 0..6 {
let fired = ob.tick(now).await.unwrap();
if let Some((_, st)) = fired.first() {
last = st.clone();
}
if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) {
break;
}
now += BACKOFF_CAP_SECS;
}
assert_eq!(
last,
OutboxStatus::Failed("connect gone.onion:80: timed out".into()),
"gives up after max_attempts"
);
assert_eq!(dead.calls(), 3, "attempts stop at the cap");
let calls_at_cap = dead.calls();
for _ in 0..3 {
now += BACKOFF_CAP_SECS;
assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries");
}
assert_eq!(dead.calls(), calls_at_cap);
let pending = ob.pending(&pk(1)).unwrap();
assert_eq!(pending.len(), 1);
assert!(matches!(pending[0].status, OutboxStatus::Failed(_)));
assert!(pending[0].status.is_terminal());
}
#[tokio::test]
async fn queued_message_survives_reopen_and_flushes_after_unlock() {
let dir = tempfile::tempdir().unwrap();
let pk1 = pk(1);
let next_attempt_at = {
let store = store_and_friend(dir.path(), "later.onion");
let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead, 8);
assert_eq!(
ob.send(&pk1, b"survives restart").await.unwrap(),
OutboxStatus::Queued
);
ob.pending(&pk1).unwrap()[0].next_attempt_at
};
// Process exit: everything above is dropped and the store is reopened.
let store = Arc::new(Mutex::new(
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
));
let up = Flaky::new(0, "");
let ob = outbox(Arc::clone(&store), up.clone(), 8);
let fired = ob.flush_all(next_attempt_at).await.unwrap();
assert_eq!(fired.len(), 1);
assert_eq!(fired[0].1, OutboxStatus::Sent);
assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]);
assert!(ob.pending(&pk1).unwrap().is_empty());
}
#[tokio::test]
async fn protocol_error_fails_immediately_and_is_not_queued() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "liar.onion");
let liar = Flaky::new(usize::MAX, "fingerprint mismatch");
let ob = outbox(Arc::clone(&store), liar, 8);
let err = ob.send(&pk(1), b"hello liar").await.unwrap_err();
assert!(err.contains("fingerprint mismatch"), "got {err}");
assert!(
ob.pending(&pk(1)).unwrap().is_empty(),
"protocol errors are never queued"
);
assert!(
store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(),
"a failed protocol send is not written to history"
);
}
#[tokio::test]
async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "seen.onion");
let flaky = Flaky::new(1, "connect seen.onion:80: timed out");
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
assert_eq!(
ob.send(&pk(1), b"you are back").await.unwrap(),
OutboxStatus::Queued
);
let now = ob.pending(&pk(1)).unwrap()[0].created_at;
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
assert_eq!(fired.len(), 1, "a live handshake flushes without waiting");
assert_eq!(fired[0].1, OutboxStatus::Sent);
}
#[tokio::test]
async fn wipe_clears_outbox_rows() {
let dir = tempfile::tempdir().unwrap();
let store = store_and_friend(dir.path(), "dead.onion");
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
let ob = outbox(Arc::clone(&store), dead, 8);
assert_eq!(
ob.send(&pk(1), b"wipe me").await.unwrap(),
OutboxStatus::Queued
);
assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1);
store.lock().unwrap().wipe_messages().unwrap();
assert!(
ob.pending(&pk(1)).unwrap().is_empty(),
"wipe must drop queued sends, not only chat"
);
}
#[tokio::test]
async fn missing_prekey_is_fatal_not_queued() {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Mutex::new(
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
));
{
let s = store.lock().unwrap();
s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap();
}
let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8);
let err = ob.send(&pk(2), b"hi").await.unwrap_err();
assert!(err.contains("prekey"), "got {err}");
assert!(ob.pending(&pk(2)).unwrap().is_empty());
}

View file

@ -233,6 +233,121 @@ fn append_message_db_file_does_not_contain_plaintext() {
);
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn db_files(home: &Path) -> Vec<(String, Vec<u8>)> {
let mut out = Vec::new();
for ent in fs::read_dir(home).expect("read_dir").flatten() {
let name = ent.file_name().to_string_lossy().to_string();
if !name.starts_with("onionwire.db") {
continue;
}
out.push((name, fs::read(ent.path()).expect("read db file")));
}
out.sort();
out
}
fn store_contains(home: &Path, needle: &[u8]) -> bool {
db_files(home)
.iter()
.any(|(_, bytes)| bytes.windows(needle.len()).any(|w| w == needle))
}
#[test]
fn whole_store_file_is_encrypted_at_rest() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open");
let me = store.self_identity().unwrap();
store
.upsert_friend(&pk(7), "friend.onion", Some("alice"))
.unwrap();
store
.append_message(&pk(7), "out", b"body-at-rest-xyz")
.unwrap();
store
.append_message(&pk(7), "in", b"reply-at-rest-xyz")
.unwrap();
drop(store);
for (needle, what) in [
(b"body-at-rest-xyz".to_vec(), "chat body"),
(b"reply-at-rest-xyz".to_vec(), "inbound chat body"),
(hex(&pk(7)).into_bytes(), "friend pubkey hex"),
(b"friend.onion".to_vec(), "friend locator"),
(me.identity_sk.clone(), "identity secret key"),
] {
assert!(
!store_contains(dir.path(), &needle),
"onionwire.db* still contains the {what}"
);
}
}
#[test]
fn wrong_passphrase_touches_nothing_and_leaves_store_readable() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "right-pass").expect("open");
store.upsert_friend(&pk(1), "b.onion", None).unwrap();
store
.append_message(&pk(1), "in", b"secret-chat-body")
.unwrap();
drop(store);
let before = db_files(dir.path());
assert!(!before.is_empty(), "expected store files on disk");
let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") {
Ok(_) => panic!("wrong passphrase should fail"),
Err(e) => e,
};
let msg = err.to_string().to_ascii_lowercase();
assert!(
msg.contains("passphrase") || msg.contains("decrypt") || msg.contains("wrong"),
"got {err}"
);
assert_eq!(
db_files(dir.path()),
before,
"a failed unlock must not modify the store files"
);
let store = Store::open_at_with_passphrase(dir.path(), "right-pass").expect("reopen");
assert_eq!(
store.list_messages(&pk(1)).unwrap()[0].plaintext,
b"secret-chat-body"
);
}
#[test]
fn encrypted_store_without_salt_file_refuses_to_guess() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open");
store.upsert_friend(&pk(1), "b.onion", None).unwrap();
let me = store.self_identity().unwrap();
drop(store);
fs::remove_file(dir.path().join("store_salt")).expect("remove salt");
let err = match Store::open_at_with_passphrase(dir.path(), "at-rest-pass") {
Ok(_) => panic!("an encrypted store without its salt must not open"),
Err(e) => e,
};
assert!(err.to_string().contains("store_salt"), "got {err}");
// The salt is only a salt: putting it back restores access, no data lost.
fs::write(dir.path().join("store_salt"), [0u8; 16]).unwrap();
let err = match Store::open_at_with_passphrase(dir.path(), "at-rest-pass") {
Ok(_) => panic!("a wrong salt must not silently open the store"),
Err(e) => e,
};
assert!(
err.to_string().to_ascii_lowercase().contains("passphrase"),
"a wrong salt must not silently open the store: {err}"
);
assert_eq!(me.identity_sk.len(), 32);
}
#[test]
fn wrong_passphrase_cannot_open_or_list() {
let dir = tempfile::tempdir().expect("tempdir");