Compare commits

..
Author SHA1 Message Date
Sirius DevOps
068b655c19
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 3m22s
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 13:55:07 -04:00
23 changed files with 97 additions and 2375 deletions

View file

@ -7,10 +7,6 @@ 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.
@ -71,11 +67,6 @@ 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
@ -357,75 +348,31 @@ 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: ${{ needs.android.outputs.tag }}
VERSION: ${{ needs.android.outputs.version }}
TAG: ${{ steps.version.outputs.tag }}
VERSION: ${{ steps.version.outputs.version }}
run: |
set -euo pipefail
cd "${GITHUB_WORKSPACE}"
: "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}"
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"
apk="dist/onionwire-$VERSION-android-$ONIONWIRE_ANDROID_ABI.apk"
aar="dist/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
@ -437,18 +384,39 @@ 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"
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"
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"

View file

@ -1,72 +0,0 @@
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,7 +2295,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
dependencies = [
"cc",
"openssl-sys",
"pkg-config",
"vcpkg",
]
@ -2693,15 +2692,6 @@ 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"
@ -2710,7 +2700,6 @@ 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-sqlcipher-vendored-openssl"] }
rusqlite = { version = "0.36", features = ["bundled"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] }
tor-cell = "0.46"
tor-hsservice = "0.46"

View file

@ -245,26 +245,19 @@ 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. 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.
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:
```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.1.0 scripts/build-android-local.sh # + upload to that release
PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh # + upload to that release
```
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
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
[`android/README.md`](android/README.md).
## Releases (maintainers)

View file

@ -94,49 +94,6 @@ 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.
@ -196,8 +153,5 @@ 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,7 +28,6 @@ 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
}
@ -130,10 +129,4 @@ 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

@ -1,150 +0,0 @@
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,17 +47,10 @@ 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,
unlock = unlock,
onUnlock = vm::unlock,
onUnlockStored = vm::unlockStored,
onForgetStored = vm::forgetStoredPassphrase,
)
else -> UnlockScreen(phase = p, onUnlock = vm::unlock)
}
}

View file

@ -3,16 +3,10 @@ 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
@ -38,23 +32,6 @@ 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.
*
@ -66,130 +43,27 @@ 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()
}
/**
* Unlocks with a typed passphrase. Empty fails closed — the SDK maps it
* straight to an error, it is not a "skip" path.
* Opens (or on first run, creates) the identity and starts hosting.
*
* [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.
* An empty passphrase fails closed — the SDK maps it straight to an error,
* it is not a "skip" path.
*/
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() {
fun unlock(passphrase: String) {
if (_phase.value is Phase.Opening) return
viewModelScope.launch {
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())
val w = openWire(home.absolutePath, passphrase)
wire = w
if (storeAfterwards) store(secret)
_phase.value = Phase.Ready(
fingerprint = w.fingerprint(),
onion = w.onion(),
@ -198,34 +72,17 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
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}.")
},
)
/** Drops our handle. The onion service stops; nothing is sent after this. */
fun lock() {
wire = null
_friends.value = emptyList()
_phase.value = Phase.Locked
}
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

@ -1,139 +0,0 @@
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

@ -1,49 +0,0 @@
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

@ -1,130 +0,0 @@
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

@ -1,91 +0,0 @@
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,7 +2,6 @@ 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
@ -12,13 +11,10 @@ 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
@ -32,38 +28,10 @@ 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,
unlock: Unlock,
onUnlock: (passphrase: String, remember: Boolean) -> Unit,
onUnlockStored: () -> Unit,
onForgetStored: () -> Unit,
) {
fun UnlockScreen(phase: Phase, onUnlock: (String) -> 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
@ -96,107 +64,38 @@ fun UnlockScreen(
}
else -> {
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))
}
}
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 (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) {
if (phase is Phase.Failed) {
Spacer(Modifier.height(20.dp))
Text(
"Failed to start",
@ -229,14 +128,3 @@ fun UnlockScreen(
)
}
}
/**
* 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

@ -1,157 +0,0 @@
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

@ -1,167 +0,0 @@
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,15 +9,11 @@ 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" }

View file

@ -1,143 +0,0 @@
# 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

@ -16,41 +16,11 @@ 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.
## Your store is encrypted
## Message bodies are encrypted at rest; keys are not
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.
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.
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.
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.
## Fail closed
@ -60,7 +30,7 @@ Peer onion down → a **chat** send is queued locally and retried (see “Local
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.
- **Device seizure.** A pending (never-delivered) message sits in the same db 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. `/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.
@ -105,6 +75,6 @@ the peer already knows the plaintext they sent.
## Out of v1
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.
relay, multi-device, DHT / name server, sqlcipher, A/V. The local retry queue of
the previous section is not an outbox in the XMPP sense: it never leaves the
device.

View file

@ -1,279 +0,0 @@
#!/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

@ -1,5 +1,4 @@
use std::fs;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@ -187,7 +186,7 @@ impl Store {
mkdir_700(&home.join("arti"))?;
mkdir_700(&home.join("cache"))?;
let db_path = home.join("onionwire.db");
let conn = open_store_db(home, &db_path, passphrase)?;
let conn = Connection::open(&db_path)?;
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}")));
@ -1105,187 +1104,6 @@ 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));
@ -1504,211 +1322,6 @@ 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

@ -233,121 +233,6 @@ 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");