Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48c06df2cf |
||
|
|
c068e292a0 |
||
|
|
38fde75d40 |
||
| c39259b919 | |||
| 8eb0820df0 | |||
| 2a53bc2b89 | |||
|
|
d6d157765a |
||
| acb6c7dd65 | |||
| bf9900f9dc | |||
| 1582f7d450 | |||
| 70e70cfe8d | |||
| 27e49b4ea6 | |||
| 4338e8aeb6 | |||
|
|
fc7378596d |
||
|
|
2fd640e230 |
||
|
|
e7b37ccb40 |
||
|
|
6f96d19901 |
||
|
|
601eb35c4b |
40 changed files with 4529 additions and 229 deletions
|
|
@ -7,6 +7,10 @@ name: android-release
|
|||
# toolchain runs in a sibling debian:bookworm container,
|
||||
# the same stdin-tar + docker cp pattern as .forgejo/workflows/ci.yml.
|
||||
#
|
||||
# Publish is a separate job on the Pi runner (`docker`). POST /releases from
|
||||
# the amd64 dind egress returns 422 with an empty body (core run 116);
|
||||
# core's publish job on the Pi (run 135) is the proven path.
|
||||
#
|
||||
# First automated version with zero tags: v0.1.0. Afterwards, patch+1 from the
|
||||
# latest v*.*.* tag UNLESS that tag's release is missing the Android assets —
|
||||
# then join it (core owns tag creation). Never move or delete a tag.
|
||||
|
|
@ -67,6 +71,11 @@ jobs:
|
|||
android:
|
||||
runs-on: docker-amd64
|
||||
timeout-minutes: 90
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
tag: ${{ steps.version.outputs.tag }}
|
||||
version_code: ${{ steps.version.outputs.version_code }}
|
||||
dry_run: ${{ steps.version.outputs.dry_run }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://code.forgejo.org/actions/checkout@v4
|
||||
|
|
@ -348,31 +357,75 @@ jobs:
|
|||
docker images "$ANDROID_IMAGE" --format '{{.Repository}}:{{.Tag}} {{.Size}}' || true
|
||||
docker system df || true
|
||||
|
||||
- name: Upload dist artifact
|
||||
uses: https://code.forgejo.org/actions/upload-artifact@v3
|
||||
with:
|
||||
name: onionwire-android
|
||||
path: dist/
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- name: Scrub keystore
|
||||
if: always()
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
|
||||
echo "keystore removed from runner"
|
||||
|
||||
publish:
|
||||
needs: android
|
||||
# Pi runner, not docker-amd64: POST /releases from amd64 dind returns 422
|
||||
# with an empty body (core run 116). This job only curls the Forgejo API.
|
||||
if: needs.android.result == 'success' && needs.android.outputs.dry_run != 'true'
|
||||
runs-on: docker
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Checkout CI tooling
|
||||
uses: https://code.forgejo.org/actions/checkout@v4
|
||||
with:
|
||||
path: .ci-tools
|
||||
|
||||
- name: Download Android dist
|
||||
uses: https://code.forgejo.org/actions/download-artifact@v3
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Publish (create-or-join)
|
||||
id: publish
|
||||
if: steps.version.outputs.dry_run != 'true'
|
||||
env:
|
||||
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
|
||||
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
EVENT_SHA: ${{ github.sha }}
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
TAG: ${{ needs.android.outputs.tag }}
|
||||
VERSION: ${{ needs.android.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd "${GITHUB_WORKSPACE}"
|
||||
: "${FORGEJO_TOKEN:?FORGEJO_TOKEN secret is missing}"
|
||||
apk="dist/onionwire-$VERSION-android-$ONIONWIRE_ANDROID_ABI.apk"
|
||||
aar="dist/onionwire-sdk-$VERSION.aar"
|
||||
echo "publish host=$(hostname) arch=$(uname -m) tag=$TAG version=$VERSION"
|
||||
mkdir -p dist
|
||||
abi="$ONIONWIRE_ANDROID_ABI"
|
||||
apk="onionwire-$VERSION-android-$abi.apk"
|
||||
aar="onionwire-sdk-$VERSION.aar"
|
||||
for f in "$apk" "$apk.sha256" "$aar" "$aar.sha256"; do
|
||||
src=$(find artifacts -type f -name "$f" -print -quit)
|
||||
if [ -z "$src" ]; then
|
||||
echo "missing artifact $f" >&2
|
||||
find artifacts -type f >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
cp "$src" "dist/$f"
|
||||
done
|
||||
for f in dist/"$apk" dist/"$apk".sha256 dist/"$aar" dist/"$aar".sha256; do
|
||||
bytes=$(wc -c < "$f")
|
||||
echo "on disk: $f $bytes bytes"
|
||||
[ "$bytes" -gt 0 ] || { echo "refusing to publish empty $f" >&2; exit 1; }
|
||||
file "$f" || true
|
||||
done
|
||||
|
||||
tag_exists=0
|
||||
i=0
|
||||
while [ "$i" -lt 6 ]; do
|
||||
code=$(curl -sS --http1.1 -o /tmp/tag.json -w '%{http_code}' \
|
||||
-H "Authorization: Bearer $FORGEJO_TOKEN" \
|
||||
-H "Authorization: Bearer ${FORGEJO_TOKEN}" \
|
||||
"$REPO_API/tags/$TAG" || true)
|
||||
if [ "$code" = "200" ]; then
|
||||
tag_exists=1
|
||||
|
|
@ -384,39 +437,18 @@ jobs:
|
|||
sleep 10
|
||||
done
|
||||
|
||||
created_tag=false
|
||||
if [ "$tag_exists" = "1" ]; then
|
||||
unset TARGET_COMMITISH || true
|
||||
else
|
||||
export TARGET_COMMITISH="$EVENT_SHA"
|
||||
created_tag=true
|
||||
echo "creating tag $TAG at $TARGET_COMMITISH"
|
||||
fi
|
||||
echo "created_tag=$created_tag" >> "$GITHUB_OUTPUT"
|
||||
|
||||
export DOCKER_HOST="${DOCKER_HOST:-unix:///var/run/docker.sock}"
|
||||
PUB_C=onionwire-android-publish-${{ github.run_id }}
|
||||
docker rm -f "$PUB_C" >/dev/null 2>&1 || true
|
||||
docker create --name "$PUB_C" -i \
|
||||
-e FORGEJO_TOKEN \
|
||||
-e REPO_API \
|
||||
-e TARGET_COMMITISH="${TARGET_COMMITISH:-}" \
|
||||
-e TAG \
|
||||
-w /src \
|
||||
"$ANDROID_IMAGE" \
|
||||
bash -euxc 'mkdir -p /src && tar xzf - -C /src && cd /src && apt-get update && apt-get install -y --no-install-recommends python3 curl ca-certificates >/dev/null && scripts/publish-release.sh "$TAG" "OnionWire $TAG" scripts/release-body.md dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk dist/onionwire-'"$VERSION"'-android-'"$ONIONWIRE_ANDROID_ABI"'.apk.sha256 dist/onionwire-sdk-'"$VERSION"'.aar dist/onionwire-sdk-'"$VERSION"'.aar.sha256'
|
||||
tar czf - \
|
||||
--exclude=./target --exclude=./.git --exclude=./.worktrees \
|
||||
--exclude=./android/.gradle --exclude=./android/app/build \
|
||||
--exclude=./android/sdk/build \
|
||||
--exclude=./crates/onionwire-sdk/target \
|
||||
. \
|
||||
| docker start -a -i "$PUB_C"
|
||||
docker rm -f "$PUB_C" >/dev/null || true
|
||||
|
||||
- name: Scrub keystore
|
||||
if: always()
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -rf "$HOME/.android/onionwire-release.jks" "$HOME/.android/onionwire-release.env" .ci-android
|
||||
echo "keystore removed from runner"
|
||||
echo "publishing $TAG from $REPO_API"
|
||||
.ci-tools/scripts/publish-release.sh \
|
||||
"$TAG" "OnionWire $TAG" \
|
||||
.ci-tools/scripts/release-body.md \
|
||||
"dist/$apk" \
|
||||
"dist/$apk.sha256" \
|
||||
"dist/$aar" \
|
||||
"dist/$aar.sha256"
|
||||
|
|
|
|||
72
.forgejo/workflows/arti-watch.yml
Normal file
72
.forgejo/workflows/arti-watch.yml
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
name: arti-watch
|
||||
|
||||
# Daily upstream check for the in-process Tor stack. Arti onion services are
|
||||
# experimental (README) and tor-*/arti-* are the largest attack surface here,
|
||||
# so when crates.io has a newer major.minor than the pins in Cargo.toml this
|
||||
# files ONE Forgejo issue (deduped on the title — a second run is a no-op).
|
||||
#
|
||||
# Forgejo has no Dependabot: this workflow IS the dependency alert. It
|
||||
# deliberately bumps nothing. A bump is a reviewed PR; the procedure, toolchain
|
||||
# floor and the tests it must pass are in docs/ARTI_UPGRADE.md.
|
||||
#
|
||||
# NOT covered, by design: Tor Project security announcements (a fix that ships
|
||||
# with no crates.io version bump is invisible here) and a yanked crate /
|
||||
# vulnerability in a version that has not changed. Read
|
||||
# https://blog.torproject.org/ yourself.
|
||||
on:
|
||||
schedule:
|
||||
# 06:17 UTC daily. Forgejo cron is UTC; off the hour on purpose.
|
||||
- cron: "17 6 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: Compare and log only, file no issue (true/false)
|
||||
required: false
|
||||
type: string
|
||||
default: "false"
|
||||
simulate_pin:
|
||||
description: 'Test the alert path on real crates.io data, e.g. "arti-client=0.45,tor-hsservice=0.45". Empty = the real Cargo.toml pins.'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
# Never two watchers at once: two simultaneous runs could both see "no issue
|
||||
# with this title yet" and file twice.
|
||||
concurrency:
|
||||
group: onionwire-arti-watch
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
watch:
|
||||
# Same Pi runner + `docker` job image as ci.yml / release.yml (which run
|
||||
# python3 and curl there). No cargo, no docker: four crates.io GETs and at
|
||||
# most one issue POST.
|
||||
runs-on: docker
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://code.forgejo.org/actions/checkout@v4
|
||||
|
||||
- name: Compare pins against crates.io and file an issue on a bump
|
||||
shell: bash
|
||||
env:
|
||||
FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }}
|
||||
REPO_API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
||||
INPUT_DRY_RUN: ${{ github.event.inputs.dry_run }}
|
||||
INPUT_SIMULATE_PIN: ${{ github.event.inputs.simulate_pin }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
args=(--cargo-toml Cargo.toml)
|
||||
case "${INPUT_DRY_RUN:-false}" in
|
||||
true|True|TRUE|1|yes|YES) args+=(--dry-run) ;;
|
||||
esac
|
||||
if [ -n "${INPUT_SIMULATE_PIN:-}" ]; then
|
||||
IFS=',' read -ra pairs <<< "$INPUT_SIMULATE_PIN"
|
||||
for pair in "${pairs[@]}"; do
|
||||
pair="${pair// /}"
|
||||
if [ -n "$pair" ]; then
|
||||
args+=(--simulate-pin "$pair")
|
||||
fi
|
||||
done
|
||||
fi
|
||||
echo "run: python3 scripts/arti-watch.py ${args[*]}"
|
||||
python3 scripts/arti-watch.py "${args[@]}"
|
||||
12
Cargo.lock
generated
12
Cargo.lock
generated
|
|
@ -2295,6 +2295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"openssl-sys",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
|
@ -2653,6 +2654,7 @@ dependencies = [
|
|||
"tor-rtcompat",
|
||||
"tracing-subscriber",
|
||||
"x25519-dalek",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -2692,6 +2694,15 @@ version = "0.2.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-src"
|
||||
version = "300.6.1+3.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.117"
|
||||
|
|
@ -2700,6 +2711,7 @@ checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
|
|||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"openssl-src",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ futures = "0.3"
|
|||
safelog = "0.9"
|
||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||
rand = "0.8"
|
||||
rusqlite = { version = "0.36", features = ["bundled"] }
|
||||
rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] }
|
||||
tor-cell = "0.46"
|
||||
tor-hsservice = "0.46"
|
||||
|
|
@ -47,6 +47,7 @@ sha3 = "0.10"
|
|||
sha2 = "0.10"
|
||||
md-5 = "0.10"
|
||||
rpassword = "7"
|
||||
zeroize = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
|
|
|||
19
README.md
19
README.md
|
|
@ -245,19 +245,26 @@ peer and a Linux peer that exchange invites interoperate — one protocol, not t
|
|||
- **APK** — `onionwire-<version>-android-arm64-v8a.apk`. Kotlin + Jetpack
|
||||
Compose + Material 3 messenger that depends on the SDK and nothing else.
|
||||
|
||||
It is not a WebView, and `src/tui.rs` is untouched. Both are built on a host with
|
||||
the Android SDK/NDK — the Pi runner is aarch64 Linux and cannot produce an APK:
|
||||
It is not a WebView, and `src/tui.rs` is untouched. The APK build itself is
|
||||
amd64-only — the Pi runner is aarch64 Linux and cannot produce an APK.
|
||||
[`.forgejo/workflows/android-release.yml`](.forgejo/workflows/android-release.yml)
|
||||
builds on `docker-amd64`, then a second job on the Pi (`docker`) attaches the
|
||||
APK + AAR (+ `.sha256`) to the same Forgejo tag as the Linux binaries. If that
|
||||
tag's release already exists and is missing the APK, the workflow **joins** it
|
||||
instead of minting patch+1. Publish does not run from amd64 dind: `POST /releases`
|
||||
from that egress returns 422 with an empty body.
|
||||
|
||||
```bash
|
||||
# one-time: sdkmanager platform 36 / build-tools 36.0.0 / ndk 28.2.13676358,
|
||||
# rustup target add aarch64-linux-android, cargo install cargo-ndk
|
||||
scripts/build-android-local.sh # -> dist/, with .sha256 files
|
||||
PUBLISH_TAG=v0.3.0 scripts/build-android-local.sh # + upload to that release
|
||||
PUBLISH_TAG=v0.1.0 scripts/build-android-local.sh # + upload to that release
|
||||
```
|
||||
|
||||
Every asset has a matching `.sha256` so `sha256sum -c` works. The APK is
|
||||
**debug-signed** and is for sideloading, not for Play. Full build notes, the
|
||||
`minSdk 26` rationale, the 16 KB page-size check and the signing story are in
|
||||
Every asset has a matching `.sha256` so `sha256sum -c` works. CI signs with the
|
||||
repo-owned release keystore. A local run without those env vars still
|
||||
debug-signs for sideload, not Play. Full build notes, the `minSdk 26`
|
||||
rationale, the 16 KB page-size check and the signing story are in
|
||||
[`android/README.md`](android/README.md).
|
||||
|
||||
## Releases (maintainers)
|
||||
|
|
|
|||
|
|
@ -94,6 +94,49 @@ exclusions, because an auto-backup of `onionwire.db` would hand the wrapped
|
|||
message key *and* the plaintext identity keys to Google Drive. Chat bodies are
|
||||
encrypted at rest; identity keys are not — that is the locked v1 posture.
|
||||
|
||||
### The store passphrase at rest
|
||||
|
||||
Typing the passphrase on every launch is no longer required. On first unlock
|
||||
the passphrase can be remembered (checkbox, on by default), and it is then
|
||||
stored as an AES-256-GCM blob:
|
||||
|
||||
* the wrapping key is generated inside the **Android Keystore** under alias
|
||||
`onionwire.store`, AES-256-GCM, `setUserAuthenticationRequired(false)` —
|
||||
deliberately **not** biometric-gated, because a fingerprint prompt would turn
|
||||
"the node opens or tells you why it did not" into "the node is unusable";
|
||||
* **StrongBox is requested first** (`setIsStrongBoxBacked(true)`, guarded by
|
||||
`FEATURE_STRONGBOX_KEYSTORE` on API 28+) and falls back to an ordinary
|
||||
TEE-backed or software Keystore key when the chip refuses AES-256
|
||||
(`StrongBoxUnavailableException is a ProviderException`). The fallback is
|
||||
reported, not hidden: the lock screen prints what `KeyInfo` actually said,
|
||||
and a software key is labelled **NOT hardware-backed**;
|
||||
* only ciphertext + IV reach disk, at
|
||||
`filesDir/secrets/store-passphrase.bin` — an `OWSEAL1` envelope of
|
||||
magic + IV + ciphertext + GCM tag. No second copy, no `SharedPreferences`,
|
||||
no plaintext in logs, and the typed `CharArray` is zeroed as soon as the
|
||||
unlock call returns. The text field is a plain `remember`, so the typed
|
||||
passphrase is never written into saved instance state;
|
||||
* **Keystore invalidation is a supported path, not a crash.** A factory reset,
|
||||
an app-data wipe, or a key the platform invalidates leaves a blob that cannot
|
||||
authenticate: `StoredPassphraseStore.load()` returns `Unavailable`, the lock
|
||||
screen explains it, and the user types the passphrase again. A failed read
|
||||
does **not** delete the blob — a transient Keystore failure must not destroy
|
||||
the only copy;
|
||||
* `forget` deletes the blob **and** the Keystore key.
|
||||
|
||||
The one plaintext copy this cannot erase is the immutable `String` the UniFFI
|
||||
binding takes (`openWire(home, passphrase: String)`). A follow-up SDK change
|
||||
should accept the key (or a `ByteArray`) so the passphrase never becomes a
|
||||
`String` at all.
|
||||
|
||||
`app/src/test/.../crypto/` covers the envelope and the file handling on the JVM
|
||||
(the real `StoreSecret` code, with a JVM AES key standing in). The Keystore
|
||||
provider only exists on a device:
|
||||
|
||||
```bash
|
||||
./gradlew :app:connectedDebugAndroidTest # prints the KeyInfo/hardware report
|
||||
```
|
||||
|
||||
### Signing
|
||||
|
||||
Release APKs are signed with a **repo-owned keystore**, not the debug key.
|
||||
|
|
@ -153,5 +196,8 @@ android/
|
|||
src/main/java/com/siriusdevops/onionwire/
|
||||
MainActivity.kt # NavHost
|
||||
WireViewModel.kt # owns the single Wire node
|
||||
crypto/ # Keystore-wrapped store passphrase
|
||||
ui/ # Compose screens (M3)
|
||||
src/test/ # JVM tests (envelope, store, invite flow)
|
||||
src/androidTest/ # device-only: AndroidKeyStore
|
||||
```
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ android {
|
|||
// the offline default and match the first automated tag (v0.1.0 → 100).
|
||||
versionCode = (findProperty("onionwire.versionCode") as String?)?.toIntOrNull() ?: 100
|
||||
versionName = (findProperty("onionwire.versionName") as String?) ?: "0.1.0"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
ndk {
|
||||
abiFilters += onionwireAbis
|
||||
}
|
||||
|
|
@ -129,4 +130,10 @@ dependencies {
|
|||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
|
||||
// Device-only: the AndroidKeyStore provider does not exist in the unit-test
|
||||
// JVM. These run under `./gradlew :app:connectedDebugAndroidTest`.
|
||||
androidTestImplementation(libs.junit)
|
||||
androidTestImplementation(libs.androidx.test.ext.junit)
|
||||
androidTestImplementation(libs.androidx.test.runner)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,150 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The device half of the Keystore story. The unit-test JVM has no
|
||||
* `AndroidKeyStore` provider, so nothing here can run as a plain JUnit test.
|
||||
*
|
||||
* Run on a real device or an emulator:
|
||||
*
|
||||
* ./gradlew :app:connectedDebugAndroidTest
|
||||
*
|
||||
* and read the `OnionWireKeystore` tag in logcat for the actual
|
||||
* `KeyInfo`/`isInsideSecureHardware`/`securityLevel` report — the point of
|
||||
* [key_backing_is_reported_and_logged] is to print the truth, not to assert a
|
||||
* hardware-backed key on hardware that does not have one.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class KeystorePassphraseCipherTest {
|
||||
|
||||
private val context: Context =
|
||||
InstrumentationRegistry.getInstrumentation().targetContext
|
||||
|
||||
private val cipher = KeystorePassphraseCipher(context)
|
||||
|
||||
private val passphrase = "correct horse battery staple".toCharArray()
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
cipher.deleteKey()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun seal_open_round_trips_through_the_android_keystore() {
|
||||
val blob = cipher.seal(passphrase)
|
||||
assertTrue(
|
||||
"envelope is magic + IV + ciphertext + tag",
|
||||
blob.size >= passphrase.size + StoreSecret.IV_BYTES + 16 + 9,
|
||||
)
|
||||
val out = cipher.open(blob)
|
||||
try {
|
||||
assertArrayEquals(passphrase, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun stored_blob_on_a_device_is_not_the_plaintext() {
|
||||
val dir = File(context.filesDir, "secrets-test")
|
||||
dir.mkdirs()
|
||||
val store = StoredPassphraseStore(File(dir, "store-passphrase.bin"), cipher)
|
||||
try {
|
||||
store.save(passphrase)
|
||||
|
||||
val raw = File(store.path).readBytes()
|
||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
||||
assertFalse(
|
||||
"the passphrase must not appear in the file",
|
||||
String(raw, Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
|
||||
)
|
||||
|
||||
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
|
||||
try {
|
||||
assertArrayEquals(passphrase, loaded.passphrase)
|
||||
} finally {
|
||||
StoreSecret.wipe(loaded.passphrase)
|
||||
}
|
||||
} finally {
|
||||
store.forget()
|
||||
dir.deleteRecursively()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun key_backing_is_reported_and_logged() {
|
||||
cipher.seal(passphrase) // force key creation
|
||||
|
||||
val strongBoxAdvertised = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||
val backing = cipher.backing()
|
||||
|
||||
Log.i(
|
||||
"OnionWireKeystore",
|
||||
"alias=${KeystorePassphraseCipher.ALIAS} backing=$backing " +
|
||||
"strongBoxAdvertised=$strongBoxAdvertised " +
|
||||
"sdk=${Build.VERSION.SDK_INT} device=${Build.MANUFACTURER} ${Build.MODEL}",
|
||||
)
|
||||
|
||||
if (strongBoxAdvertised) {
|
||||
assertTrue(
|
||||
"StrongBox is advertised but the key did not land in a secure element: $backing",
|
||||
backing == KeyBacking.STRONGBOX || backing == KeyBacking.HARDWARE,
|
||||
)
|
||||
} else {
|
||||
assertNotEquals("the API refused to report the backing at all", KeyBacking.UNKNOWN, backing)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun open_does_not_require_user_authentication() {
|
||||
// The card's contract: unlocking must not need a fingerprint. If the
|
||||
// key had been created with setUserAuthenticationRequired(true), this
|
||||
// open() would throw UserNotAuthenticatedException.
|
||||
val out = cipher.open(cipher.seal(passphrase))
|
||||
StoreSecret.wipe(out)
|
||||
assertTrue(cipher.keyPresent())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun deleted_key_reports_unavailable_instead_of_crashing() {
|
||||
val blob = cipher.seal(passphrase)
|
||||
cipher.deleteKey()
|
||||
|
||||
assertFalse(cipher.keyPresent())
|
||||
try {
|
||||
cipher.open(blob)
|
||||
fail("expected SecretUnavailable after the key was deleted")
|
||||
} catch (e: SecretUnavailable) {
|
||||
assertTrue(e.message!!.contains("gone"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun a_regenerated_key_cannot_open_an_old_blob() {
|
||||
val blob = cipher.seal(passphrase)
|
||||
cipher.deleteKey() // a reset that leaves the app's data dir intact
|
||||
cipher.seal(passphrase) // same alias, brand-new key
|
||||
|
||||
try {
|
||||
cipher.open(blob)
|
||||
fail("expected SecretUnavailable for a blob wrapped by the deleted key")
|
||||
} catch (_: SecretUnavailable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -47,10 +47,17 @@ class MainActivity : ComponentActivity() {
|
|||
@Composable
|
||||
private fun AppRoot(vm: WireViewModel = viewModel()) {
|
||||
val phase by vm.phase.collectAsStateWithLifecycle()
|
||||
val unlock by vm.unlock.collectAsStateWithLifecycle()
|
||||
|
||||
when (val p = phase) {
|
||||
is Phase.Ready -> ReadyGraph(vm, p)
|
||||
else -> UnlockScreen(phase = p, onUnlock = vm::unlock)
|
||||
else -> UnlockScreen(
|
||||
phase = p,
|
||||
unlock = unlock,
|
||||
onUnlock = vm::unlock,
|
||||
onUnlockStored = vm::unlockStored,
|
||||
onForgetStored = vm::forgetStoredPassphrase,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,10 +3,19 @@ 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.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import uniffi.onionwire_sdk.ChatMessage
|
||||
import uniffi.onionwire_sdk.FriendInfo
|
||||
import uniffi.onionwire_sdk.InviteInfo
|
||||
|
|
@ -32,6 +41,31 @@ 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Teardown work must outlive the ViewModel: `onCleared()` runs *after*
|
||||
* `viewModelScope` is already cancelled, and stopping the node means draining
|
||||
* the outbox and stopping Arti, not just dropping a reference. One process-wide
|
||||
* scope is enough — there is one node per process.
|
||||
*/
|
||||
private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
/**
|
||||
* Owns the single Wire node for the process.
|
||||
*
|
||||
|
|
@ -43,27 +77,174 @@ 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
|
||||
|
||||
/**
|
||||
* Opens (or on first run, creates) the identity and starts hosting.
|
||||
*
|
||||
* An empty passphrase fails closed — the SDK maps it straight to an error,
|
||||
* it is not a "skip" path.
|
||||
* The in-flight teardown, if any. Unlocking again has to wait for it: the
|
||||
* old node holds the sqlite file and Arti's state lock until `shutdown()`
|
||||
* returns, and racing it makes the new node fail to open.
|
||||
*/
|
||||
fun unlock(passphrase: String) {
|
||||
private var stopping: Job? = 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.
|
||||
*
|
||||
* [remember] wraps the passphrase with the Keystore key so later launches
|
||||
* are one tap. It is opt-in in the UI (and on by default there); it is
|
||||
* never implied by this call.
|
||||
*/
|
||||
fun unlock(passphrase: String, remember: Boolean = false) {
|
||||
if (passphrase.isEmpty()) return
|
||||
openWith(passphrase.toCharArray(), storeAfterwards = remember)
|
||||
}
|
||||
|
||||
/**
|
||||
* One-tap unlock from the stored blob.
|
||||
*
|
||||
* Any failure — key deleted, blob corrupt, GCM tag mismatch — degrades to
|
||||
* "type it" with the reason on screen. It never crashes and never silently
|
||||
* unlocks with something else.
|
||||
*/
|
||||
fun unlockStored() {
|
||||
if (_phase.value is Phase.Opening) return
|
||||
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.",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the node and drops our handle. Nothing is sent after this.
|
||||
*
|
||||
* Flush first — the outbox is the whole point of losing the process — then
|
||||
* `shutdown()`, which stops the onion service, aborts the retry worker and
|
||||
* checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this
|
||||
* runs from an `onClick`.
|
||||
*/
|
||||
fun lock() {
|
||||
val w = wire ?: return
|
||||
wire = null
|
||||
_friends.value = emptyList()
|
||||
_phase.value = Phase.Locked
|
||||
refreshUnlockState()
|
||||
stopping = TEARDOWN.launch { stopNode(w) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The node must not outlive the UI. Doze and the background-process killer
|
||||
* skip this entirely (that is what the outbox is for), but a normal finish
|
||||
* tears Tor down here instead of leaving Arti running behind a dead screen.
|
||||
*/
|
||||
override fun onCleared() {
|
||||
val w = wire
|
||||
wire = null
|
||||
if (w != null) stopping = TEARDOWN.launch { stopNode(w) }
|
||||
super.onCleared()
|
||||
}
|
||||
|
||||
private suspend fun stopNode(w: Wire) {
|
||||
// Best effort, both steps: teardown runs on a process-scope job after
|
||||
// the UI is gone, so there is nobody to show an error to and nothing
|
||||
// useful to retry. `shutdown()` drains again with a shorter budget, so
|
||||
// a flush that times out is not fatal.
|
||||
runCatching { w.flush() }
|
||||
// A second shutdown — `lock()` and then `onCleared()`, say — lands here
|
||||
// too: the SDK reports it as a typed WireException.Stopped, never a
|
||||
// panic, so swallowing it is correct.
|
||||
runCatching { w.shutdown() }
|
||||
}
|
||||
|
||||
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 || wire != null) {
|
||||
StoreSecret.wipe(secret)
|
||||
return
|
||||
}
|
||||
_phase.value = Phase.Opening
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val w = openWire(home.absolutePath, passphrase)
|
||||
// Any previous node must be fully stopped first: the old node
|
||||
// holds the sqlite file and Arti's state lock until its teardown
|
||||
// returns, and racing it makes this open fail.
|
||||
stopping?.join()
|
||||
val w = openWire(home.absolutePath, secret.concatToString())
|
||||
wire = w
|
||||
if (storeAfterwards) store(secret)
|
||||
_phase.value = Phase.Ready(
|
||||
fingerprint = w.fingerprint(),
|
||||
onion = w.onion(),
|
||||
|
|
@ -72,17 +253,34 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
|
|||
refreshFriends()
|
||||
} catch (t: Throwable) {
|
||||
_phase.value = Phase.Failed(t.message ?: t.toString())
|
||||
} finally {
|
||||
StoreSecret.wipe(secret)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops our handle. The onion service stops; nothing is sent after this. */
|
||||
fun lock() {
|
||||
wire = null
|
||||
_friends.value = emptyList()
|
||||
_phase.value = Phase.Locked
|
||||
private suspend fun store(secret: CharArray) {
|
||||
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
secrets.save(secret)
|
||||
Result.success(secrets.backing())
|
||||
} catch (t: Throwable) {
|
||||
Result.failure(t)
|
||||
}
|
||||
}
|
||||
_unlock.value = outcome.fold(
|
||||
onSuccess = { Unlock.OneTap(it) },
|
||||
onFailure = {
|
||||
// Unlock succeeded, so this is not fatal — say so plainly
|
||||
// instead of pretending the passphrase was stored.
|
||||
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun unavailableNotice(reason: String): String =
|
||||
"The stored passphrase could not be read — $reason. Type it once to store it again."
|
||||
|
||||
private fun requireWire(): Wire = wire ?: error("locked")
|
||||
|
||||
suspend fun refreshFriends() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,139 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyInfo
|
||||
import android.security.keystore.KeyProperties
|
||||
import java.security.KeyStore
|
||||
import java.security.ProviderException
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.SecretKeyFactory
|
||||
|
||||
/**
|
||||
* AES-256-GCM key held by the Android Keystore under [ALIAS].
|
||||
*
|
||||
* The key material is never readable by this process (`SecretKey.encoded` is
|
||||
* null for AndroidKeyStore keys) — that is the whole point: pulling
|
||||
* `/data/data/com.siriusdevops.onionwire/` off a rooted device yields the
|
||||
* ciphertext, not the passphrase.
|
||||
*
|
||||
* StrongBox is requested first and falls back to the ordinary TEE-backed (or
|
||||
* software) Keystore without a crash. The fallback is not silent: call
|
||||
* [backing] and report what the Keystore actually produced.
|
||||
*
|
||||
* `setUserAuthenticationRequired` is deliberately **false**. Requiring a
|
||||
* fingerprint to unlock the node would turn "fail closed" into "unusable
|
||||
* unattended", and the SDK's contract is that an unlock either opens the node
|
||||
* or reports why it did not.
|
||||
*/
|
||||
class KeystorePassphraseCipher(private val context: Context) : PassphraseCipher {
|
||||
|
||||
private var cached: SecretKey? = null
|
||||
|
||||
override fun seal(plaintext: CharArray): ByteArray =
|
||||
StoreSecret.seal(loadOrCreateKey(), plaintext)
|
||||
|
||||
/**
|
||||
* Never creates a key. A freshly generated key cannot decrypt an old blob,
|
||||
* and generating one here would turn "the key is gone" into a confusing
|
||||
* GCM tag failure. The caller needs the real reason to tell the user.
|
||||
*/
|
||||
override fun open(blob: ByteArray): CharArray {
|
||||
val key = cached ?: existingKey()
|
||||
?: throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
||||
return StoreSecret.open(key, blob)
|
||||
}
|
||||
|
||||
override fun keyPresent(): Boolean = (cached ?: existingKey()) != null
|
||||
|
||||
override fun backing(): KeyBacking {
|
||||
val key = cached ?: existingKey() ?: return KeyBacking.UNKNOWN
|
||||
val info = try {
|
||||
SecretKeyFactory.getInstance(key.algorithm, PROVIDER)
|
||||
.getKeySpec(key, KeyInfo::class.java) as KeyInfo
|
||||
} catch (_: Exception) {
|
||||
// Some OEM Keystore implementations refuse getKeySpec. Report
|
||||
// UNKNOWN rather than guessing hardware backing.
|
||||
return KeyBacking.UNKNOWN
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
||||
info.securityLevel == KeyProperties.SECURITY_LEVEL_STRONGBOX
|
||||
) {
|
||||
return KeyBacking.STRONGBOX
|
||||
}
|
||||
// Deprecated in API 31 in favour of securityLevel, but it is the only
|
||||
// TEE/software answer available on 26–30, and minSdk is 26.
|
||||
@Suppress("DEPRECATION")
|
||||
val inSecureHardware = info.isInsideSecureHardware
|
||||
return if (inSecureHardware) KeyBacking.HARDWARE else KeyBacking.SOFTWARE
|
||||
}
|
||||
|
||||
override fun deleteKey() {
|
||||
cached = null
|
||||
try {
|
||||
keyStore().deleteEntry(ALIAS)
|
||||
} catch (_: Exception) {
|
||||
// Nothing usable to delete.
|
||||
}
|
||||
}
|
||||
|
||||
private fun existingKey(): SecretKey? {
|
||||
cached?.let { return it }
|
||||
val key = try {
|
||||
keyStore().getKey(ALIAS, null) as? SecretKey
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
cached = key
|
||||
return key
|
||||
}
|
||||
|
||||
private fun loadOrCreateKey(): SecretKey = cached ?: existingKey() ?: createKey()
|
||||
|
||||
private fun createKey(): SecretKey {
|
||||
val strongBoxAdvertised =
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.P &&
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
|
||||
if (strongBoxAdvertised) {
|
||||
try {
|
||||
return generate(strongBox = true).also { cached = it }
|
||||
} catch (_: ProviderException) {
|
||||
// StrongBoxUnavailableException is a ProviderException: the chip
|
||||
// exists but its slots are full, or it refuses AES-256. Fall
|
||||
// through to a normal Keystore key instead of failing unlock.
|
||||
}
|
||||
}
|
||||
return generate(strongBox = false).also { cached = it }
|
||||
}
|
||||
|
||||
private fun generate(strongBox: Boolean): SecretKey {
|
||||
val builder = KeyGenParameterSpec.Builder(
|
||||
ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(StoreSecret.KEY_BITS)
|
||||
// Our IV comes from Cipher.init, and the Keystore supplies it.
|
||||
.setRandomizedEncryptionRequired(true)
|
||||
.setUserAuthenticationRequired(false)
|
||||
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
builder.setIsStrongBoxBacked(true)
|
||||
}
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER)
|
||||
generator.init(builder.build())
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
private fun keyStore(): KeyStore = KeyStore.getInstance(PROVIDER).apply { load(null) }
|
||||
|
||||
companion object {
|
||||
const val PROVIDER = "AndroidKeyStore"
|
||||
|
||||
/** One key per app: the passphrase it wraps is the only secret here. */
|
||||
const val ALIAS = "onionwire.store"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
/**
|
||||
* Wraps the store passphrase with a key that never leaves the Keystore.
|
||||
*
|
||||
* Implementations must not persist the plaintext anywhere, and must not log it.
|
||||
*/
|
||||
interface PassphraseCipher {
|
||||
|
||||
/** Encrypts [plaintext]. The returned blob is the only thing that may hit disk. */
|
||||
fun seal(plaintext: CharArray): ByteArray
|
||||
|
||||
/**
|
||||
* Decrypts a blob produced by [seal].
|
||||
*
|
||||
* @throws SecretUnavailable when the key is gone, invalidated, or the blob
|
||||
* does not authenticate. Callers fall back to asking the user to type.
|
||||
*/
|
||||
fun open(blob: ByteArray): CharArray
|
||||
|
||||
/** True when a usable key is already in the Keystore. */
|
||||
fun keyPresent(): Boolean
|
||||
|
||||
/**
|
||||
* Where the key actually lives, as reported by the Keystore itself.
|
||||
*
|
||||
* This is an observation, not a claim: on a device without a StrongBox or
|
||||
* TEE the honest answer is [KeyBacking.SOFTWARE], and the UI says so.
|
||||
*/
|
||||
fun backing(): KeyBacking
|
||||
|
||||
/** Removes the key. The ciphertext becomes permanently undecryptable. */
|
||||
fun deleteKey()
|
||||
}
|
||||
|
||||
/** Result of asking the Keystore where the key lives. */
|
||||
enum class KeyBacking {
|
||||
/** Dedicated security chip (API 28+, Pixel 3-class and up). */
|
||||
STRONGBOX,
|
||||
|
||||
/** Key is inside a TEE. Good. */
|
||||
HARDWARE,
|
||||
|
||||
/** Keystore software implementation. Passphrase is still not plaintext on disk. */
|
||||
SOFTWARE,
|
||||
|
||||
/** No key created yet, or the API could not be queried. Never claim hardware here. */
|
||||
UNKNOWN,
|
||||
}
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import java.nio.CharBuffer
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.security.GeneralSecurityException
|
||||
import java.util.Arrays
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/**
|
||||
* AES-256-GCM envelope for the store passphrase.
|
||||
*
|
||||
* This file is deliberately free of `android.*` imports so the exact
|
||||
* seal/open code that runs on a device can also run in a plain JVM unit test
|
||||
* with a JVM-generated AES key. The Android Keystore only supplies the key —
|
||||
* the framing and the AEAD call are these functions.
|
||||
*
|
||||
* Wire format (little of it is secret, all of it is authenticated):
|
||||
*
|
||||
* magic "OWSEAL1\n" 8 bytes
|
||||
* iv length 1 byte (always [IV_BYTES])
|
||||
* iv [IV_BYTES] bytes, from the cipher
|
||||
* ciphertext n + [TAG_BITS]/8 bytes (GCM tag is appended)
|
||||
*
|
||||
* The IV is generated by `Cipher.init` rather than by us: an AndroidKeyStore
|
||||
* key created with `setRandomizedEncryptionRequired(true)` refuses an
|
||||
* app-supplied IV, and SunJCE likewise default-generates one. Nothing here
|
||||
* ever writes the plaintext passphrase to disk.
|
||||
*/
|
||||
object StoreSecret {
|
||||
|
||||
/** AES-256 per the card. Keystore key size and this constant must agree. */
|
||||
const val KEY_BITS: Int = 256
|
||||
|
||||
/** 96-bit IV is the GCM-recommended size; AndroidKeyStore defaults to it. */
|
||||
const val IV_BYTES: Int = 12
|
||||
|
||||
/** Full-length GCM tag. Truncating it saves 6 bytes and buys nothing. */
|
||||
private const val TAG_BITS: Int = 128
|
||||
|
||||
private val MAGIC = byteArrayOf('O'.code.toByte(), 'W'.code.toByte(), 'S'.code.toByte(), 'E'.code.toByte(), 'A'.code.toByte(), 'L'.code.toByte(), '1'.code.toByte(), '\n'.code.toByte())
|
||||
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
|
||||
/**
|
||||
* Encrypts [plaintext] under [key]. The passphrase is never converted to a
|
||||
* `String` on this path: the UTF-8 encoder reads the `CharArray` directly.
|
||||
*/
|
||||
fun seal(key: SecretKey, plaintext: CharArray): ByteArray {
|
||||
require(plaintext.isNotEmpty()) { "refusing to seal an empty passphrase" }
|
||||
val bytes = utf8(plaintext)
|
||||
try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key)
|
||||
val iv = cipher.iv
|
||||
val ct = cipher.doFinal(bytes)
|
||||
return ByteArray(MAGIC.size + 1 + iv.size + ct.size).also { out ->
|
||||
var p = 0
|
||||
MAGIC.copyInto(out, p); p += MAGIC.size
|
||||
out[p] = iv.size.toByte(); p += 1
|
||||
iv.copyInto(out, p); p += iv.size
|
||||
ct.copyInto(out, p)
|
||||
}
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw SecretUnavailable("could not encrypt the passphrase", e)
|
||||
} finally {
|
||||
wipe(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverses [seal]. Throws [SecretUnavailable] on a wrong key, a truncated
|
||||
* blob, or a failed GCM tag check — never returns partial plaintext.
|
||||
*/
|
||||
fun open(key: SecretKey, blob: ByteArray): CharArray {
|
||||
if (blob.size < MAGIC.size + 1 + IV_BYTES + TAG_BITS / 8) {
|
||||
throw SecretUnavailable("stored secret is truncated")
|
||||
}
|
||||
for (i in MAGIC.indices) {
|
||||
if (blob[i] != MAGIC[i]) throw SecretUnavailable("stored secret is not an OnionWire envelope")
|
||||
}
|
||||
var p = MAGIC.size
|
||||
val ivLen = blob[p].toInt() and 0xFF
|
||||
p += 1
|
||||
if (ivLen != IV_BYTES) throw SecretUnavailable("unexpected IV length $ivLen")
|
||||
if (blob.size < p + ivLen + TAG_BITS / 8) throw SecretUnavailable("stored secret is truncated")
|
||||
val iv = blob.copyOfRange(p, p + ivLen)
|
||||
val ct = blob.copyOfRange(p + ivLen, blob.size)
|
||||
val plain = try {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))
|
||||
cipher.doFinal(ct)
|
||||
} catch (e: GeneralSecurityException) {
|
||||
throw SecretUnavailable("stored secret did not authenticate", e)
|
||||
}
|
||||
return try {
|
||||
decodeUtf8(plain)
|
||||
} finally {
|
||||
wipe(plain)
|
||||
}
|
||||
}
|
||||
|
||||
/** Zeroes [bytes]. Cheap, and it shortens the window a heap dump can read. */
|
||||
fun wipe(bytes: ByteArray) {
|
||||
Arrays.fill(bytes, 0)
|
||||
}
|
||||
|
||||
/** Zeroes [chars]. Kotlin/Java strings are immutable, so this is the best we get. */
|
||||
fun wipe(chars: CharArray) {
|
||||
Arrays.fill(chars, '\u0000')
|
||||
}
|
||||
|
||||
private fun utf8(chars: CharArray): ByteArray {
|
||||
val bb = StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(chars))
|
||||
return ByteArray(bb.remaining()).also(bb::get)
|
||||
}
|
||||
|
||||
private fun decodeUtf8(bytes: ByteArray): CharArray {
|
||||
val cb = StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes))
|
||||
return CharArray(cb.remaining()).also(cb::get)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The passphrase could not be recovered. The caller must fall back to typing
|
||||
* it — a Keystore key does not survive a factory reset, a lock-screen change
|
||||
* that invalidates keys, or an app-data wipe.
|
||||
*/
|
||||
class SecretUnavailable(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* The only on-disk copy of the passphrase: an AES-GCM blob under
|
||||
* `context.filesDir`, which is app-private and excluded from backup and
|
||||
* device transfer (`AndroidManifest.xml`, `res/xml/data_extraction_rules.xml`).
|
||||
*
|
||||
* The blob is the envelope from [StoreSecret] — magic + IV + ciphertext + tag.
|
||||
* There is no second copy, no SharedPreferences mirror, and nothing outside the
|
||||
* app's data dir.
|
||||
*/
|
||||
class StoredPassphraseStore(
|
||||
private val file: File,
|
||||
private val cipher: PassphraseCipher,
|
||||
) {
|
||||
|
||||
sealed interface Load {
|
||||
/** Decrypted for this call only. The caller must wipe the array. */
|
||||
class Loaded(val passphrase: CharArray) : Load
|
||||
|
||||
/** Nothing stored yet — first run, or the user forgot it. */
|
||||
data object Absent : Load
|
||||
|
||||
/**
|
||||
* Something is stored but cannot be read: the Keystore key is gone or
|
||||
* invalidated, or the file is corrupt. Fall back to typing.
|
||||
*/
|
||||
data class Unavailable(val reason: String) : Load
|
||||
}
|
||||
|
||||
fun exists(): Boolean = file.isFile && file.length() > 0L
|
||||
|
||||
/** Where the wrapping key actually lives. See [PassphraseCipher.backing]. */
|
||||
fun backing(): KeyBacking = cipher.backing()
|
||||
|
||||
/** Path for diagnostics in tests. Never logged with its contents. */
|
||||
val path: String get() = file.absolutePath
|
||||
|
||||
/**
|
||||
* Encrypts and replaces the stored blob. Atomic-ish: written to a sibling
|
||||
* temp file and renamed, so a crash mid-write cannot leave half a blob.
|
||||
*/
|
||||
fun save(passphrase: CharArray) {
|
||||
require(passphrase.isNotEmpty()) { "refusing to store an empty passphrase" }
|
||||
val blob = cipher.seal(passphrase)
|
||||
try {
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parentFile, file.name + ".tmp")
|
||||
tmp.writeBytes(blob)
|
||||
if (!tmp.renameTo(file)) {
|
||||
file.writeBytes(blob)
|
||||
tmp.delete()
|
||||
}
|
||||
} finally {
|
||||
StoreSecret.wipe(blob)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and decrypts the blob. The returned array is the caller's to wipe.
|
||||
*
|
||||
* A failed decrypt does **not** delete the blob: a transient Keystore
|
||||
* failure must not silently destroy the user's only copy. Use [forget] to
|
||||
* drop it deliberately.
|
||||
*/
|
||||
fun load(): Load {
|
||||
if (!exists()) return Load.Absent
|
||||
val blob = try {
|
||||
file.readBytes()
|
||||
} catch (e: IOException) {
|
||||
return Load.Unavailable("the stored passphrase file could not be read (${e.message})")
|
||||
}
|
||||
return try {
|
||||
Load.Loaded(cipher.open(blob))
|
||||
} catch (e: SecretUnavailable) {
|
||||
Load.Unavailable(e.message ?: "the stored passphrase did not authenticate")
|
||||
} finally {
|
||||
StoreSecret.wipe(blob)
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the ciphertext and the Keystore key. Irreversible. */
|
||||
fun forget() {
|
||||
file.delete()
|
||||
File(file.parentFile, file.name + ".tmp").delete()
|
||||
cipher.deleteKey()
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ package com.siriusdevops.onionwire.ui
|
|||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
|
|
@ -11,10 +12,13 @@ import androidx.compose.foundation.rememberScrollState
|
|||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
|
|
@ -28,10 +32,38 @@ import androidx.compose.ui.text.input.KeyboardType
|
|||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.siriusdevops.onionwire.Phase
|
||||
import com.siriusdevops.onionwire.Unlock
|
||||
import com.siriusdevops.onionwire.crypto.KeyBacking
|
||||
|
||||
/**
|
||||
* Lock screen.
|
||||
*
|
||||
* When [Unlock.OneTap] is set, the passphrase is already on disk wrapped by the
|
||||
* Android Keystore key and the user taps once. Otherwise they type it — and
|
||||
* they land here, with [Unlock.TypeIt.notice] explaining why, whenever the
|
||||
* stored blob cannot be read (key invalidated, device reset, corrupt file).
|
||||
*
|
||||
* The typed passphrase lives in a plain `remember` (not `rememberSaveable`) and
|
||||
* is cleared as soon as it is handed to the ViewModel: it never survives a
|
||||
* config change and never gets written to the saved-instance-state bundle.
|
||||
*/
|
||||
@Composable
|
||||
fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
||||
fun UnlockScreen(
|
||||
phase: Phase,
|
||||
unlock: Unlock,
|
||||
onUnlock: (passphrase: String, remember: Boolean) -> Unit,
|
||||
onUnlockStored: () -> Unit,
|
||||
onForgetStored: () -> Unit,
|
||||
) {
|
||||
var pass by remember { mutableStateOf("") }
|
||||
var storePassphrase by remember { mutableStateOf(true) }
|
||||
// Only meaningful under OneTap: reveal the form without giving up the
|
||||
// stored passphrase.
|
||||
var typeInstead by remember { mutableStateOf(false) }
|
||||
|
||||
val oneTap = unlock as? Unlock.OneTap
|
||||
val failed = phase is Phase.Failed
|
||||
val showForm = oneTap == null || typeInstead || failed
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
|
|
@ -64,38 +96,107 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
|||
}
|
||||
|
||||
else -> {
|
||||
Text(
|
||||
"Passphrase",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = pass,
|
||||
onValueChange = { pass = it },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
label = { Text("wraps the local message key") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
"Empty is not a bypass — it fails closed. There is no recovery: " +
|
||||
"lose this and the stored chat bodies stay unreadable.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = { onUnlock(pass) },
|
||||
enabled = pass.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Open") }
|
||||
if (oneTap != null && !failed) {
|
||||
Text("Passphrase", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"Stored on this device, wrapped by an Android Keystore key " +
|
||||
"(${backingLabel(oneTap.backing)}).",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = onUnlockStored,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Unlock") }
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
TextButton(onClick = { typeInstead = true }) {
|
||||
Text("Type it instead")
|
||||
}
|
||||
TextButton(onClick = onForgetStored) {
|
||||
Text("Forget stored passphrase")
|
||||
}
|
||||
}
|
||||
if (showForm) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
HorizontalDivider()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (phase is Phase.Failed) {
|
||||
if (showForm) {
|
||||
if (unlock is Unlock.TypeIt && unlock.notice != null) {
|
||||
Text(
|
||||
unlock.notice,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = pass,
|
||||
onValueChange = { pass = it },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
label = { Text("wraps the local message key") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
"Empty is not a bypass — it fails closed. There is no recovery: " +
|
||||
"lose this and the stored chat bodies stay unreadable.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Checkbox(
|
||||
checked = storePassphrase,
|
||||
onCheckedChange = { storePassphrase = it },
|
||||
)
|
||||
Text(
|
||||
"Remember on this device (wrapped by the Android Keystore, " +
|
||||
"no backup)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
if (oneTap != null) {
|
||||
Text(
|
||||
"Typing and remembering replaces the stored passphrase.",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
val typed = pass
|
||||
// Drop the plaintext from Compose state the moment
|
||||
// it is handed over; the ViewModel wipes its copy.
|
||||
pass = ""
|
||||
onUnlock(typed, storePassphrase)
|
||||
},
|
||||
enabled = pass.isNotEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("Open") }
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(
|
||||
"Failed to start",
|
||||
|
|
@ -128,3 +229,14 @@ fun UnlockScreen(phase: Phase, onUnlock: (String) -> Unit) {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the Keystore reported, verbatim. Never upgraded into a stronger claim:
|
||||
* a software key says so.
|
||||
*/
|
||||
internal fun backingLabel(backing: KeyBacking): String = when (backing) {
|
||||
KeyBacking.STRONGBOX -> "StrongBox"
|
||||
KeyBacking.HARDWARE -> "TEE-backed"
|
||||
KeyBacking.SOFTWARE -> "software key, NOT hardware-backed"
|
||||
KeyBacking.UNKNOWN -> "backing not reported by this device"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,157 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
|
||||
/**
|
||||
* Exercises the real envelope code — [StoreSecret] has no `android.*` imports,
|
||||
* so a JVM AES key stands in for the AndroidKeystore key.
|
||||
*
|
||||
* What this does NOT cover (see the PR description): the AndroidKeyStore provider
|
||||
* itself (`KeyGenerator` + `KeyGenParameterSpec`, StrongBox fallback, and
|
||||
* `KeyInfo.isInsideSecureHardware`). Those are device-only APIs; the unit-test
|
||||
* JVM has no such provider.
|
||||
*/
|
||||
class StoreSecretTest {
|
||||
|
||||
private fun aesKey(): SecretKey =
|
||||
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
|
||||
|
||||
private val passphrase = "correct horse battery staple".toCharArray()
|
||||
|
||||
@Test
|
||||
fun seal_open_round_trips() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
val out = StoreSecret.open(key, blob)
|
||||
try {
|
||||
assertArrayEquals(passphrase, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun round_trips_non_ascii_and_whitespace() {
|
||||
val key = aesKey()
|
||||
val weird = " ünïcödé 🔑 \n\ttab ".toCharArray()
|
||||
val out = StoreSecret.open(key, StoreSecret.seal(key, weird))
|
||||
try {
|
||||
assertArrayEquals(weird, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blob_does_not_contain_the_plaintext() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
||||
assertFalse(
|
||||
"ciphertext must not contain the passphrase",
|
||||
blob.containsSubsequence(needle),
|
||||
)
|
||||
assertTrue(blob.size > needle.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blob_carries_the_envelope_magic() {
|
||||
val blob = StoreSecret.seal(aesKey(), passphrase)
|
||||
assertEquals("OWSEAL1\n", String(blob.copyOfRange(0, 8), Charsets.US_ASCII))
|
||||
// Magic(8) + IV length(1) + IV(12) + tag(16)
|
||||
assertEquals(8 + 1 + StoreSecret.IV_BYTES + 16, blob.size - String(passphrase).toByteArray(Charsets.UTF_8).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun each_seal_uses_a_fresh_iv() {
|
||||
val key = aesKey()
|
||||
val a = StoreSecret.seal(key, passphrase)
|
||||
val b = StoreSecret.seal(key, passphrase)
|
||||
assertNotEquals(
|
||||
"identical ciphertext means the IV was reused",
|
||||
a.toList(),
|
||||
b.toList(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wrong_key_fails_closed() {
|
||||
val blob = StoreSecret.seal(aesKey(), passphrase)
|
||||
try {
|
||||
StoreSecret.open(aesKey(), blob)
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (e: SecretUnavailable) {
|
||||
assertTrue(e.message!!.contains("authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tampered_ciphertext_fails_the_gcm_tag() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
blob[blob.size - 1] = (blob[blob.size - 1].toInt() xor 0x01).toByte()
|
||||
try {
|
||||
StoreSecret.open(key, blob)
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (_: SecretUnavailable) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun truncated_blob_fails_closed() {
|
||||
val key = aesKey()
|
||||
val blob = StoreSecret.seal(key, passphrase)
|
||||
try {
|
||||
StoreSecret.open(key, blob.copyOfRange(0, 10))
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (_: SecretUnavailable) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun garbage_blob_fails_closed() {
|
||||
try {
|
||||
StoreSecret.open(aesKey(), "not an envelope".toByteArray())
|
||||
fail("expected SecretUnavailable")
|
||||
} catch (e: SecretUnavailable) {
|
||||
assertTrue(e.message!!.contains("truncated") || e.message!!.contains("envelope"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun seal_refuses_an_empty_passphrase() {
|
||||
try {
|
||||
StoreSecret.seal(aesKey(), CharArray(0))
|
||||
fail("expected IllegalArgumentException")
|
||||
} catch (_: IllegalArgumentException) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wipe_zeroes() {
|
||||
val bytes = byteArrayOf(1, 2, 3)
|
||||
StoreSecret.wipe(bytes)
|
||||
assertArrayEquals(ByteArray(3), bytes)
|
||||
|
||||
val chars = charArrayOf('a', 'b')
|
||||
StoreSecret.wipe(chars)
|
||||
assertArrayEquals(CharArray(2), chars)
|
||||
}
|
||||
|
||||
private fun ByteArray.containsSubsequence(needle: ByteArray): Boolean {
|
||||
if (needle.isEmpty() || needle.size > size) return false
|
||||
outer@ for (i in 0..size - needle.size) {
|
||||
for (j in needle.indices) if (this[i + j] != needle[j]) continue@outer
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
package com.siriusdevops.onionwire.crypto
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
|
||||
/**
|
||||
* File-level behaviour of [StoredPassphraseStore] with the real envelope from
|
||||
* [StoreSecret] and a JVM AES key standing in for the Keystore key.
|
||||
*
|
||||
* The Keystore itself is device-only; what is proven here is that nothing
|
||||
* plaintext reaches the file, that a lost key degrades instead of crashing,
|
||||
* and that a lost key does not delete the user's blob.
|
||||
*/
|
||||
class StoredPassphraseStoreTest {
|
||||
|
||||
@get:Rule
|
||||
val tmp = TemporaryFolder()
|
||||
|
||||
private val passphrase = "correct horse battery staple".toCharArray()
|
||||
|
||||
/** Stands in for the AndroidKeystore key: real AES-GCM, JVM-held key. */
|
||||
private class JvmKeyCipher(private val key: SecretKey) : PassphraseCipher {
|
||||
var deleted = false
|
||||
var backingQueried = 0
|
||||
|
||||
override fun seal(plaintext: CharArray): ByteArray = StoreSecret.seal(key, plaintext)
|
||||
|
||||
override fun open(blob: ByteArray): CharArray {
|
||||
if (deleted) throw SecretUnavailable("the device's Keystore key for OnionWire is gone")
|
||||
return StoreSecret.open(key, blob)
|
||||
}
|
||||
|
||||
override fun keyPresent(): Boolean = !deleted
|
||||
|
||||
override fun backing(): KeyBacking {
|
||||
backingQueried++
|
||||
return KeyBacking.SOFTWARE
|
||||
}
|
||||
|
||||
override fun deleteKey() {
|
||||
deleted = true
|
||||
}
|
||||
}
|
||||
|
||||
private fun jvmKey(): SecretKey =
|
||||
KeyGenerator.getInstance("AES").apply { init(StoreSecret.KEY_BITS) }.generateKey()
|
||||
|
||||
private fun store(cipher: PassphraseCipher) =
|
||||
StoredPassphraseStore(tmp.newFile("store-passphrase.bin").also { it.delete() }, cipher)
|
||||
|
||||
@Test
|
||||
fun save_then_load_round_trips() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
|
||||
val loaded = store.load()
|
||||
assertTrue(loaded is StoredPassphraseStore.Load.Loaded)
|
||||
val out = (loaded as StoredPassphraseStore.Load.Loaded).passphrase
|
||||
try {
|
||||
assertArrayEquals(passphrase, out)
|
||||
} finally {
|
||||
StoreSecret.wipe(out)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun on_disk_blob_is_not_the_plaintext() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
|
||||
val raw = java.io.File(store.path).readBytes()
|
||||
val needle = String(passphrase).toByteArray(Charsets.UTF_8)
|
||||
assertFalse(
|
||||
"the passphrase must not appear in the file",
|
||||
raw.toString(Charsets.ISO_8859_1).contains(String(needle, Charsets.ISO_8859_1)),
|
||||
)
|
||||
assertTrue("expected the OWSEAL envelope", raw.size > needle.size + 20)
|
||||
assertEquals("OWSEAL1\n", String(raw.copyOfRange(0, 8), Charsets.US_ASCII))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun no_temp_file_is_left_behind() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
val dir = requireNotNull(java.io.File(store.path).parentFile)
|
||||
val leftovers = dir.listFiles()!!.filter { it.name.endsWith(".tmp") }
|
||||
assertTrue("temp files left: $leftovers", leftovers.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun save_overwrites_the_previous_blob() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save("first".toCharArray())
|
||||
store.save("second".toCharArray())
|
||||
|
||||
val loaded = store.load() as StoredPassphraseStore.Load.Loaded
|
||||
try {
|
||||
assertArrayEquals("second".toCharArray(), loaded.passphrase)
|
||||
} finally {
|
||||
StoreSecret.wipe(loaded.passphrase)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun absent_when_nothing_was_ever_stored() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
assertFalse(store.exists())
|
||||
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lost_key_reports_unavailable_and_keeps_the_blob() {
|
||||
val cipher = JvmKeyCipher(jvmKey())
|
||||
val store = store(cipher)
|
||||
store.save(passphrase)
|
||||
|
||||
cipher.deleteKey() // device reset / key invalidated
|
||||
|
||||
val loaded = store.load()
|
||||
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
|
||||
assertTrue(
|
||||
(loaded as StoredPassphraseStore.Load.Unavailable).reason.contains("gone"),
|
||||
)
|
||||
assertTrue("a failed read must not delete the blob", store.exists())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corrupt_blob_reports_unavailable_instead_of_throwing() {
|
||||
val store = store(JvmKeyCipher(jvmKey()))
|
||||
store.save(passphrase)
|
||||
java.io.File(store.path).writeBytes("OWSEAL1\n not really a ciphertext".toByteArray())
|
||||
|
||||
val loaded = store.load()
|
||||
assertTrue(loaded is StoredPassphraseStore.Load.Unavailable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forget_deletes_the_blob_and_the_key() {
|
||||
val cipher = JvmKeyCipher(jvmKey())
|
||||
val store = store(cipher)
|
||||
store.save(passphrase)
|
||||
assertTrue(store.exists())
|
||||
|
||||
store.forget()
|
||||
|
||||
assertFalse(store.exists())
|
||||
assertFalse(cipher.keyPresent())
|
||||
assertEquals(StoredPassphraseStore.Load.Absent, store.load())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backing_is_reported_from_the_cipher() {
|
||||
val cipher = JvmKeyCipher(jvmKey())
|
||||
val store = store(cipher)
|
||||
store.save(passphrase)
|
||||
|
||||
assertEquals(KeyBacking.SOFTWARE, store.backing())
|
||||
assertEquals(1, cipher.backingQueried)
|
||||
}
|
||||
}
|
||||
|
|
@ -9,11 +9,15 @@ composeBom = "2025.12.01"
|
|||
jna = "5.19.1"
|
||||
coroutines = "1.11.0"
|
||||
junit = "4.13.2"
|
||||
androidxTestJunit = "1.3.0"
|
||||
androidxTestRunner = "1.7.0"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" }
|
||||
jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
|
||||
junit = { module = "junit:junit", version.ref = "junit" }
|
||||
androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestJunit" }
|
||||
androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }
|
||||
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
|
||||
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" }
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" }
|
||||
|
|
|
|||
|
|
@ -13,13 +13,20 @@
|
|||
//! Orbot pipe. If the onion service cannot publish, this fails closed.
|
||||
//! * Chat bodies are encrypted at rest. Identity keys in sqlite are not.
|
||||
//!
|
||||
//! Lifecycle: a node is started by [`open_wire`] and stopped by
|
||||
//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable
|
||||
//! state and [`Wire::flush`] is "deliver what is deliverable now". A process
|
||||
//! killed by Doze or the background-process killer never runs `shutdown`, which
|
||||
//! is exactly why queued sends live in sqlite and not in memory.
|
||||
//!
|
||||
//! The façade deliberately exposes only plain data (records + hex strings) so
|
||||
//! no TUI/ratatui type leaks into the AAR.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use onionwire::node::Node;
|
||||
use onionwire::hs::TorState as CoreTorState;
|
||||
use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node};
|
||||
use onionwire::qr;
|
||||
|
||||
uniffi::setup_scaffolding!();
|
||||
|
|
@ -54,6 +61,12 @@ pub fn install_crypto_provider() {
|
|||
pub enum WireError {
|
||||
#[error("{message}")]
|
||||
Failed { message: String },
|
||||
/// The node was shut down (or never opened). Distinct from `Failed` so
|
||||
/// Kotlin can branch on it instead of string-matching a message, and so
|
||||
/// "you must unlock again" is a different UI state from "the network is
|
||||
/// broken".
|
||||
#[error("node stopped: {message}")]
|
||||
Stopped { message: String },
|
||||
}
|
||||
|
||||
impl WireError {
|
||||
|
|
@ -62,6 +75,12 @@ impl WireError {
|
|||
message: e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn stopped(what: &str) -> Self {
|
||||
Self::Stopped {
|
||||
message: format!("{what} called on a shut-down node"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type WResult<T> = std::result::Result<T, WireError>;
|
||||
|
|
@ -98,10 +117,70 @@ pub struct InviteInfo {
|
|||
pub onion: String,
|
||||
}
|
||||
|
||||
/// Observable lifecycle state of the node's onion service.
|
||||
///
|
||||
/// Mirrors Arti's own service status, projected onto the four states a UI
|
||||
/// actually acts on. It is the same distinction `hs::hs_is_ready` makes when it
|
||||
/// decides whether the onion is reachable yet.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
|
||||
pub enum TorState {
|
||||
/// Bootstrap or descriptor upload still in flight. Not reliably reachable.
|
||||
Bootstrapping,
|
||||
/// Onion service running and its descriptor published.
|
||||
Published,
|
||||
/// Reachable, but Arti reports the service degraded. Usable — worth saying
|
||||
/// so, not identical to `Published`.
|
||||
DegradedReachable,
|
||||
/// Shut down: no onion service, no dials, store checkpointed. Every method
|
||||
/// on the node now returns `WireError.Stopped`.
|
||||
Stopped,
|
||||
}
|
||||
|
||||
impl From<CoreTorState> for TorState {
|
||||
fn from(s: CoreTorState) -> Self {
|
||||
match s {
|
||||
CoreTorState::Bootstrapping => Self::Bootstrapping,
|
||||
CoreTorState::Published => Self::Published,
|
||||
CoreTorState::DegradedReachable => Self::DegradedReachable,
|
||||
CoreTorState::Stopped => Self::Stopped,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`Wire::flush`] managed to do.
|
||||
#[derive(Debug, Clone, Copy, uniffi::Record)]
|
||||
pub struct FlushOutcome {
|
||||
/// Rows the pass started a delivery for. `0` when the pass hit its time
|
||||
/// budget before finishing — the rows are still queued, we just stopped
|
||||
/// counting.
|
||||
pub attempted: u32,
|
||||
/// Rows delivered now. A message absent from `remaining` was sent.
|
||||
pub delivered: u32,
|
||||
/// Rows still queued or terminally failed afterwards.
|
||||
pub remaining: u32,
|
||||
}
|
||||
|
||||
/// A running OnionWire node: identity + Arti client + hosted v3 onion service.
|
||||
///
|
||||
/// Holds the node handle. [`Wire::shutdown`] takes it out and drops it, which
|
||||
/// is what lets the last reference to the Tor client and the store go away —
|
||||
/// there is no hidden global keeping Arti (or the sqlite connection) alive
|
||||
/// after the UI is gone.
|
||||
#[derive(uniffi::Object)]
|
||||
pub struct Wire {
|
||||
inner: Arc<Node>,
|
||||
node: Mutex<Option<Arc<Node>>>,
|
||||
}
|
||||
|
||||
impl Wire {
|
||||
/// The live node, or `Stopped` if this handle was shut down. A poisoned
|
||||
/// mutex is reported the same way rather than panicking: a caller that sees
|
||||
/// `Stopped` unlocks again, which is the correct recovery either way.
|
||||
fn node(&self) -> WResult<Arc<Node>> {
|
||||
let guard = self.node.lock().map_err(|_| WireError::Stopped {
|
||||
message: "node handle lock poisoned by a panic; reopen the identity".to_string(),
|
||||
})?;
|
||||
guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Open (or create) the identity in `home` and start hosting an onion service.
|
||||
|
|
@ -111,6 +190,11 @@ pub struct Wire {
|
|||
///
|
||||
/// This resolves only once the onion service is published — on a cold network
|
||||
/// that is minutes, not seconds. Call it off the main thread.
|
||||
///
|
||||
/// The returned handle owns the node: it lives until [`Wire::shutdown`], or
|
||||
/// until the handle itself is dropped (which the JVM does without running the
|
||||
/// drain, so call `shutdown()` from teardown — see the foreground-service
|
||||
/// caller).
|
||||
#[uniffi::export(async_runtime = "tokio")]
|
||||
pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
|
||||
// Before anything that can build a TLS config: Arti's rustls backend dies
|
||||
|
|
@ -120,7 +204,9 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult<Arc<Wire>> {
|
|||
let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase)
|
||||
.await
|
||||
.map_err(WireError::new)?;
|
||||
Ok(Arc::new(Wire { inner: node }))
|
||||
Ok(Arc::new(Wire {
|
||||
node: Mutex::new(Some(node)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Decode an invite without adding the friend. Verifies the signature.
|
||||
|
|
@ -135,24 +221,81 @@ pub fn decode_invite(invite: String) -> WResult<InviteInfo> {
|
|||
|
||||
#[uniffi::export(async_runtime = "tokio")]
|
||||
impl Wire {
|
||||
/// Stop the node: give every queued outbox row one last bounded delivery
|
||||
/// attempt, stop the onion service, abort the retry worker, checkpoint the
|
||||
/// sqlite WAL, and drop the Tor client.
|
||||
///
|
||||
/// The *node* teardown is idempotent: a second `Node::shutdown()` returns
|
||||
/// `Ok` without repeating the work. This handle is spent by the first call,
|
||||
/// so a second `Wire::shutdown()` — or two concurrent teardowns — returns
|
||||
/// the typed `WireError.Stopped` instead of a silent `Ok`: a double
|
||||
/// teardown is a caller bug worth surfacing, and `Stopped` is already the
|
||||
/// answer every other method gives. It never panics.
|
||||
///
|
||||
/// After it, every other method on this handle — including `send` —
|
||||
/// returns `WireError.Stopped` instead of touching a dead client.
|
||||
///
|
||||
/// Never called at all when the process is killed outright (Doze, the
|
||||
/// background-process killer, a force-stop): that is the case [`flush`]
|
||||
/// (Self::flush) and the sqlite outbox exist for. Once shut down, this
|
||||
/// handle is spent — unlock again to get a new one.
|
||||
pub async fn shutdown(&self) -> WResult<()> {
|
||||
let node = self.node()?;
|
||||
node.shutdown().await.map_err(WireError::new)?;
|
||||
// Drop our handle to the node. With the onion service and the outbox
|
||||
// worker aborted this is the last reference to the Tor client and the
|
||||
// store, so Arti's runtime and the sqlite connection are released here.
|
||||
let mut guard = self.node.lock().map_err(|_| WireError::Stopped {
|
||||
message: "node handle lock poisoned by a panic".to_string(),
|
||||
})?;
|
||||
*guard = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drain the outbox: one delivery attempt for every queued row, now,
|
||||
/// ignoring its retry backoff, then checkpoint the WAL.
|
||||
///
|
||||
/// Bounded by the SDK (30s): a dead peer's onion can hold a dial for ~20s
|
||||
/// and this is called from UI/lifecycle threads. Rows that did not go out
|
||||
/// stay queued; the retry worker keeps its normal schedule. Safe to call
|
||||
/// repeatedly — use it on unlock, on foreground, and before `shutdown`.
|
||||
pub async fn flush(&self) -> WResult<FlushOutcome> {
|
||||
let node = self.node()?;
|
||||
let out = node.flush().await.map_err(WireError::new)?;
|
||||
Ok(from_core_flush(out))
|
||||
}
|
||||
|
||||
/// Where the onion service is right now. Cheap and read-only, no I/O: a
|
||||
/// notification or a settings screen can call it directly.
|
||||
pub fn tor_state(&self) -> TorState {
|
||||
match self.node.lock() {
|
||||
Ok(guard) => match guard.as_ref() {
|
||||
Some(node) => node.tor_state().into(),
|
||||
None => TorState::Stopped,
|
||||
},
|
||||
// Poisoned: same answer as shut down — the node is unusable.
|
||||
Err(_) => TorState::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fingerprint of our own identity key. Stable forever for this install.
|
||||
pub async fn fingerprint(&self) -> WResult<String> {
|
||||
self.inner.fingerprint().map_err(WireError::new)
|
||||
self.node()?.fingerprint().map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Current onion locator. Changes on rotate; identity does not.
|
||||
pub async fn onion(&self) -> String {
|
||||
self.inner.onion()
|
||||
pub async fn onion(&self) -> WResult<String> {
|
||||
Ok(self.node()?.onion())
|
||||
}
|
||||
|
||||
/// `onionwire:v1:…` invite string to hand to the other person out of band.
|
||||
pub async fn invite(&self) -> WResult<String> {
|
||||
self.inner.qr_payload().map_err(WireError::new)
|
||||
self.node()?.qr_payload().map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Roster, sorted by petname then fingerprint.
|
||||
pub async fn friends(&self) -> WResult<Vec<FriendInfo>> {
|
||||
let list = self.inner.list_friends().map_err(WireError::new)?;
|
||||
let list = self.node()?.list_friends().map_err(WireError::new)?;
|
||||
Ok(list
|
||||
.into_iter()
|
||||
.map(|f| FriendInfo {
|
||||
|
|
@ -168,9 +311,10 @@ impl Wire {
|
|||
/// Add a friend from an invite, or update the locator if the key is known.
|
||||
/// Same `k` never creates a second row.
|
||||
pub async fn add_friend(&self, invite: String) -> WResult<FriendInfo> {
|
||||
self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?;
|
||||
let node = self.node()?;
|
||||
node.add_friend_from_qr(&invite).map_err(WireError::new)?;
|
||||
let p = qr::decode(&invite).map_err(WireError::new)?;
|
||||
let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?;
|
||||
let f = node.friend(&p.pubkey).map_err(WireError::new)?;
|
||||
Ok(FriendInfo {
|
||||
pubkey_hex: hex(&f.pubkey),
|
||||
fingerprint: f.fingerprint,
|
||||
|
|
@ -183,26 +327,32 @@ impl Wire {
|
|||
/// Local label. Pass `None` to clear. Never goes on the wire.
|
||||
pub async fn set_petname(&self, pubkey_hex: String, petname: Option<String>) -> WResult<()> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
self.inner
|
||||
self.node()?
|
||||
.set_petname(&pk, petname.as_deref())
|
||||
.map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Send one message. Fail closed: if the peer's onion is down, this errors
|
||||
/// after retrying. There is no outbox in v1 — no silent spooling.
|
||||
/// Send one message. Returns once the outcome is known: delivered now, or
|
||||
/// queued for retry because the peer's onion is unreachable. A protocol
|
||||
/// error (bad signature, bad frame) still fails immediately and is never
|
||||
/// queued. Use [`flush`](Self::flush) to retry the queue on demand.
|
||||
pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
self.inner
|
||||
self.node()?
|
||||
.send(&pk, body.as_bytes())
|
||||
.await
|
||||
.map_err(WireError::new)
|
||||
.map_err(WireError::new)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Chat history for a friend, oldest first. Bodies are decrypted here;
|
||||
/// they are stored encrypted at rest.
|
||||
pub async fn messages(&self, pubkey_hex: String) -> WResult<Vec<ChatMessage>> {
|
||||
let pk = unhex(&pubkey_hex)?;
|
||||
let rows = self.inner.list_messages(&pk).map_err(WireError::new)?;
|
||||
let rows = self
|
||||
.node()?
|
||||
.list_messages(&pk)
|
||||
.map_err(WireError::new)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|m| ChatMessage {
|
||||
|
|
@ -214,7 +364,7 @@ impl Wire {
|
|||
|
||||
/// Delete every message body. Identity and friends survive.
|
||||
pub async fn wipe_messages(&self) -> WResult<()> {
|
||||
self.inner.wipe_messages().map_err(WireError::new)
|
||||
self.node()?.wipe_messages().map_err(WireError::new)
|
||||
}
|
||||
|
||||
/// Publish a NEW onion service and hard-cut the old one, then push a signed
|
||||
|
|
@ -224,7 +374,7 @@ impl Wire {
|
|||
/// you until they rescan your invite — that is the documented v1 behaviour,
|
||||
/// not a bug. Confirm with a typed phrase in the UI; never one tap.
|
||||
pub async fn rotate_onion(&self) -> WResult<RotateOutcome> {
|
||||
let r = self.inner.rotate().await.map_err(WireError::new)?;
|
||||
let r = self.node()?.rotate().await.map_err(WireError::new)?;
|
||||
Ok(RotateOutcome {
|
||||
notified: r.notified as u32,
|
||||
friends: r.friends as u32,
|
||||
|
|
@ -237,6 +387,14 @@ impl Wire {
|
|||
}
|
||||
}
|
||||
|
||||
fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome {
|
||||
FlushOutcome {
|
||||
attempted: o.attempted as u32,
|
||||
delivered: o.delivered as u32,
|
||||
remaining: o.remaining as u32,
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
|
|
@ -256,3 +414,72 @@ fn unhex(s: &str) -> WResult<Vec<u8>> {
|
|||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! No Tor here on purpose: these exercise the *lifecycle* contract of the
|
||||
//! handle, which is what a shut-down node must guarantee. A `Wire` with no
|
||||
//! node is exactly the state `shutdown()` leaves behind.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn stopped_wire() -> Wire {
|
||||
Wire {
|
||||
node: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn block_on<F: std::future::Future>(f: F) -> F::Output {
|
||||
// No `macros` feature on tokio in this crate, so build the runtime.
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.expect("runtime")
|
||||
.block_on(f)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_state_of_a_stopped_handle_is_stopped() {
|
||||
assert_eq!(stopped_wire().tor_state(), TorState::Stopped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_after_shutdown_are_typed_errors_not_panics() {
|
||||
let wire = stopped_wire();
|
||||
|
||||
let err = block_on(wire.flush()).expect_err("flush after shutdown must fail");
|
||||
assert!(
|
||||
matches!(err, WireError::Stopped { .. }),
|
||||
"flush returned {err:?}, want WireError::Stopped"
|
||||
);
|
||||
|
||||
let err = block_on(wire.send("00".repeat(32), "hi".to_string()))
|
||||
.expect_err("send after shutdown must fail");
|
||||
assert!(
|
||||
matches!(err, WireError::Stopped { .. }),
|
||||
"send returned {err:?}, want WireError::Stopped"
|
||||
);
|
||||
|
||||
let err = block_on(wire.friends()).expect_err("friends after shutdown must fail");
|
||||
assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}");
|
||||
|
||||
let err = block_on(wire.shutdown()).expect_err("second shutdown must not re-run");
|
||||
assert!(
|
||||
matches!(err, WireError::Stopped { .. }),
|
||||
"second shutdown returned {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_state_maps_every_core_state() {
|
||||
assert_eq!(
|
||||
TorState::from(CoreTorState::Bootstrapping),
|
||||
TorState::Bootstrapping
|
||||
);
|
||||
assert_eq!(TorState::from(CoreTorState::Published), TorState::Published);
|
||||
assert_eq!(
|
||||
TorState::from(CoreTorState::DegradedReachable),
|
||||
TorState::DegradedReachable
|
||||
);
|
||||
assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
143
docs/ARTI_UPGRADE.md
Normal file
143
docs/ARTI_UPGRADE.md
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
# Upgrading the Arti / Tor crates
|
||||
|
||||
The in-process Tor stack is the largest attack surface in OnionWire. Arti's
|
||||
onion services are still **experimental** and OnionWire does not fall back to a
|
||||
C-tor subprocess, so an upstream fix only reaches users when we bump these
|
||||
crates, rebuild, and cut a release.
|
||||
|
||||
## What is pinned
|
||||
|
||||
Direct dependencies that come from the Arti repository, exactly as
|
||||
`Cargo.toml` has them:
|
||||
|
||||
| crate | requirement | features in `Cargo.toml` |
|
||||
|---|---|---|
|
||||
| `arti-client` | `0.46` | `default-features = false`; `tokio`, `onion-service-client`, `onion-service-service`, `compression` |
|
||||
| `tor-cell` | `0.46` | — |
|
||||
| `tor-hsservice` | `0.46` | — |
|
||||
| `tor-rtcompat` | `0.46` | `tokio` |
|
||||
|
||||
`snow`, `rusqlite`, `ratatui`, and the rest are unrelated to Arti and are not
|
||||
part of a Tor upgrade.
|
||||
|
||||
Two crate features re-expose Arti's TLS backends, which Arti marks
|
||||
**non-additive** — exactly one may be selected per build graph:
|
||||
|
||||
* `native-tls` (default) → Linux TUI build, via OpenSSL.
|
||||
* `rustls` → the Android SDK crate (`crates/onionwire-sdk`), because the NDK has
|
||||
no OpenSSL.
|
||||
|
||||
Published Arti releases move all four crates together in lockstep. Bump them as
|
||||
**one set**. A mixed set (e.g. `arti-client` 0.47 with `tor-hsservice` 0.46) is
|
||||
not a configuration anyone tests upstream, and cargo will usually refuse or
|
||||
silently pick one `tor-*` version and mismatched `tor-*` internals fail at
|
||||
runtime.
|
||||
|
||||
## Toolchain floor
|
||||
|
||||
**rustc 1.91+.** `Cargo.toml` sets `edition = "2024"` and `rust-version = "1.91"`;
|
||||
the Arti 0.46 crates require 1.91. CI builds inside `rust:1.91-bookworm`
|
||||
(`RUST_IMAGE` in `.forgejo/workflows/ci.yml` and `release.yml`).
|
||||
|
||||
A bump may raise the floor. Take the actual MSRV from the upstream release
|
||||
notes / the crate's own `rust-version`, then raise it in the same PR:
|
||||
|
||||
* `rust-version` in `Cargo.toml`,
|
||||
* `RUST_IMAGE` in `.forgejo/workflows/ci.yml` **and** `.forgejo/workflows/release.yml`,
|
||||
* the "Rust 1.91+" line in `README.md` (owned by another PR right now — add it
|
||||
when that lands, or ask the owner).
|
||||
|
||||
## How this gets noticed
|
||||
|
||||
`.forgejo/workflows/arti-watch.yml` runs daily (and on demand) and asks
|
||||
crates.io for the newest stable version of each crate above. If the
|
||||
major.minor moved past the pin, it files one Forgejo issue titled
|
||||
`Arti upstream: <crate> <pin> → <new>`. It is deduped on that title across open
|
||||
and closed issues, so re-running it never files a second issue and never
|
||||
comments. It changes nothing: no `Cargo.toml`, no lockfile, no commit.
|
||||
|
||||
Test the alert path without waiting for upstream (it compares real crates.io
|
||||
data against a pretend pin):
|
||||
|
||||
```
|
||||
# Actions → arti-watch → Run workflow, simulate_pin = arti-client=0.45
|
||||
python3 scripts/arti-watch.py --dry-run --cargo-toml Cargo.toml --simulate-pin arti-client=0.45
|
||||
```
|
||||
|
||||
**What the watcher does not cover.** It does not subscribe to Tor Project
|
||||
security announcements — a fix that ships without a crates.io version bump is
|
||||
invisible to it. It will not catch a yanked crate, and it will not catch a
|
||||
vulnerability in a version that has not changed. Watch
|
||||
<https://blog.torproject.org/> and <https://forum.torproject.org/> yourself, and
|
||||
treat a Tor security advisory as an instruction to bump **now**, ahead of any
|
||||
issue the watcher files.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. Read the upstream release notes (Arti tags: <https://gitlab.torproject.org/tpo/core/arti/-/releases>)
|
||||
and the CHANGELOG for breaking API changes. Check the new MSRV.
|
||||
2. Branch from `main`; bump all four requirements in `[dependencies]` of
|
||||
`Cargo.toml` together, and `rust-version` if the floor moved.
|
||||
3. Refresh the lockfile (CI builds with `--locked` and `Cargo.lock` is
|
||||
committed):
|
||||
```
|
||||
cargo update -p arti-client -p tor-cell -p tor-hsservice -p tor-rtcompat
|
||||
git diff --stat Cargo.lock
|
||||
```
|
||||
Expect the whole `tor-*` family to move in the diff. A single `tor-*` crate
|
||||
moving alone is a sign the set is not actually lockstep — stop and look.
|
||||
4. Build and run the offline suite:
|
||||
```
|
||||
cargo test --locked
|
||||
cargo clippy --locked --all-targets -- -D warnings
|
||||
```
|
||||
5. Re-check the workarounds in `src/hs.rs`. They exist because Arti's publish
|
||||
path is slow and its circuit timeouts misbehave on hidden-service circuits,
|
||||
and an upstream fix or behaviour change can make any of them wrong:
|
||||
|
||||
| constant | why | guard |
|
||||
|---|---|---|
|
||||
| `PUBLISH_WAIT` (360s) | a 180s wait cut a working HsDir upload while status was still `Bootstrapping`; Arti's per-HsDir `OVERALL_UPLOAD_TIMEOUT` is 5 min | `tests/hs.rs::publish_wait_covers_hsdir_retries` |
|
||||
| `CBT_MIN_TIMEOUT_MS` / `CBT_INITIAL_TIMEOUT_MS` (≥ 10s) | learned circuit-build timeouts can drop to ~1s and kill 4-hop vanguard HsDir circuits | `tests/hs.rs::cbt_min_timeout_floor_is_at_least_10s`, `cbt_initial_timeout_matches_the_floor` |
|
||||
| `PREEMPTIVE_PREDICTED_PORTS` (empty) | Arti's default predicted 80/443 exit circuits starve IPT + HsDir builds; OnionWire never exits | `tests/hs.rs::no_preemptive_exit_ports` |
|
||||
| `hs_is_ready` probe semantics | combined status stays `Bootstrapping` after descriptors are already fetchable | `tests/hs.rs::bootstrapping_is_not_ready_until_a_probe_connects` |
|
||||
|
||||
Do not paper over a slow publish by raising `PUBLISH_WAIT` — first make sure
|
||||
the rend handler is spawned *before* the probe wait, or the probe cannot
|
||||
succeed at all.
|
||||
6. Run the live two-node test on a networked machine. This is the only test that
|
||||
proves the hidden service actually publishes and that a second node can
|
||||
reach it:
|
||||
```
|
||||
cargo test --locked --test tor_hs -- --ignored --nocapture
|
||||
```
|
||||
It needs minutes of real Tor network. `two_node_byte_pipe_restart_and_dormant`
|
||||
covers: onion publish (first-run `hs status: Bootstrapping` spam is HsDir
|
||||
descriptor upload, not a hang), probe-connect against a live HS, a byte pipe
|
||||
in both directions, restart, and the dormant/offline path.
|
||||
7. Confirm the fail-closed path by hand if the publish wait changed at all:
|
||||
with the write timeout still 360s, a peer whose onion is down must fail the
|
||||
send. There is no outbox in v1 — the message must not be silently queued.
|
||||
8. Rebuild the Android target — Arti's TLS backends are non-additive, and this
|
||||
is the build that exercises the `rustls` feature:
|
||||
```
|
||||
scripts/build-android-local.sh
|
||||
```
|
||||
9. Verify the ciphertext claim still holds after the bump: send a message
|
||||
between the two nodes, then
|
||||
```
|
||||
grep -r "<a distinctive message body>" <nodes' Arti state dirs and sqlite files>
|
||||
```
|
||||
must find nothing. The bodies live in sqlite as ciphertext, and nothing about
|
||||
the plaintext should appear in Arti's state directory.
|
||||
10. Open a PR against `main` describing: crates bumped, MSRV, the live-test
|
||||
output, and anything upstream changed that touches `src/hs.rs`. Do not push
|
||||
`main`; releases are minted by `.forgejo/workflows/release.yml` from a merge.
|
||||
|
||||
## Rolling back
|
||||
|
||||
Revert the version bump and the lockfile stanza together, re-run step 3's
|
||||
`cargo update` only if the revert leaves the lockfile inconsistent, and re-run
|
||||
`cargo test --locked` plus the live two-node test. Never leave `Cargo.toml` and
|
||||
`Cargo.lock` out of step: CI builds with `--locked` and will fail, which is the
|
||||
intent.
|
||||
|
|
@ -19,7 +19,7 @@ SOCKS proxy.”
|
|||
| Discovery | DHT + bootstrap nodes | Out-of-band invite only |
|
||||
| After lookup | Direct IP or TCP relay (SOCKS if you forced it) | v3 onion ↔ v3 onion |
|
||||
| Address | Tox ID lives in the DHT | ed25519 pubkey is identity; onion is a locator |
|
||||
| Offline send | Expected (relays / retry) | Fail closed — no outbox |
|
||||
| Offline send | Expected (relays / retry) | Queued locally, retried peer-to-peer (no relay) |
|
||||
| Mixed clearnet | ToT can still talk to non-Tor Tox | No clearnet peers |
|
||||
|
||||
There is no directory, no name server, no introduction point of our own, and no
|
||||
|
|
@ -51,8 +51,18 @@ not on the wire.
|
|||
4. File transfer is N independent sessions (one handshake per chunk). There is
|
||||
no multiplexed long-lived stream in v1.
|
||||
|
||||
If the onion is down, send fails. No retry queue except the locator-push path,
|
||||
which retries for 180 seconds and then gives up.
|
||||
If the onion is down, a **chat** send is persisted to the local outbox and
|
||||
retried by a background worker with exponential backoff (30s, doubling, capped
|
||||
at 30 min; 8 attempts, then terminal `Failed`). There is no server and no
|
||||
store-and-forward relay: each attempt is a fresh handshake straight to
|
||||
`(friend.onion, 80)`, exactly as above. Retries fire on a timer, on
|
||||
unlock/foreground, and whenever that peer is heard from (successful handshake or
|
||||
`connect_onion()`). A protocol failure — signature mismatch, unknown frame,
|
||||
oversize — is not a transport failure and is never queued.
|
||||
|
||||
File transfer and payment frames stay fail-closed: they are one-shot and are
|
||||
**not** queued. The locator-push path still retries for 180 seconds and then
|
||||
gives up.
|
||||
|
||||
Incoming rendezvous accepts are token-bucket limited: 30 per 60s, burst 10.
|
||||
Excess is dropped before handshake. That is availability, not anonymity.
|
||||
|
|
|
|||
|
|
@ -16,15 +16,54 @@ A signed `loc` frame (`onion`, `ts`, `sig`) rewrites a friend’s locator **only
|
|||
|
||||
`F4` changes the locator only. The identity key is unchanged. Anyone who already has your pubkey can still prove they are talking to you, and a later invite paste with the same `k` updates their row. To become a new person, `/wipe-all` (new identity key). There is no in-band unfriend/revoke in v1.
|
||||
|
||||
## Message bodies are encrypted at rest; keys are not
|
||||
## Your store is encrypted
|
||||
|
||||
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in the `messages.plaintext` column) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`. Swapping ciphertext between rows fails closed. A random 32-byte data key is wrapped with Argon2id (same params as identity backup) from a non-empty passphrase. Salt + wrapped key live in `store_meta`. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD.
|
||||
The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`).
|
||||
A 32-byte key is derived from the store passphrase with Argon2id (same params as
|
||||
identity backup) over a per-install 16-byte salt in `store_salt`, and handed to
|
||||
SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it.
|
||||
The key is the first statement after open, so the file header, schema, identity
|
||||
secret key, friend public keys, locators, profiles and payment rows are all
|
||||
ciphertext on disk. There is no `identity_sk`-on-disk problem to work around
|
||||
because `identity_sk` is inside the encrypted file. A wrong or empty passphrase
|
||||
fails closed before any write; an encrypted store whose `store_salt` is missing
|
||||
refuses to open instead of guessing.
|
||||
|
||||
Identity secret key, friend public keys, and locators remain plaintext in the same db. The message key is not wrapped with `identity_sk` (that key is already on disk). A seized laptop still yields who you talk to and your identity unless you add OS/FDE. sqlcipher is out of v1. `/wipe` deletes chat and payments history (overwrite message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data dir (new identity); same disk caveat.
|
||||
v0.2.1 installs have a plaintext db. The first open with the right passphrase
|
||||
upgrades it in place (`ATTACH … KEY` + `sqlcipher_export` after a WAL
|
||||
checkpoint), and swaps the file in only after the new file opens, passes
|
||||
`integrity_check` and unwraps `store_meta`. A wrong passphrase leaves the
|
||||
plaintext file untouched. The `store_salt` file is not secret (a salt never is).
|
||||
|
||||
Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce ||
|
||||
ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir ||
|
||||
0x00 || row_id_le64`, plus a random 32-byte data key wrapped with Argon2id from
|
||||
the same passphrase (`store_meta`). Whole-db encryption does not stop someone who
|
||||
can write the file from moving one row's ciphertext into another row; the AAD
|
||||
does, and it stays. Unlock is fail-closed: wrong or empty passphrase does not
|
||||
open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages`
|
||||
never falls back to empty AAD.
|
||||
|
||||
At-rest encryption is not a defense against a live compromise: while OnionWire
|
||||
runs, the passphrase, the db key and decrypted bodies are in process memory, and
|
||||
SQLCipher's page cache holds decrypted pages. It also does not stop an attacker
|
||||
who has your passphrase. `/wipe` deletes chat and payments history (overwrite
|
||||
message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a
|
||||
forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data
|
||||
dir (new identity); same disk caveat.
|
||||
|
||||
## Fail closed
|
||||
|
||||
Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
|
||||
Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
|
||||
|
||||
## Local outbox (chat retry queue) is local, and it re-dials on a schedule
|
||||
|
||||
A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted:
|
||||
|
||||
- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase.
|
||||
- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure.
|
||||
|
||||
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
|
||||
|
||||
## Profile is friend-visible, not a directory
|
||||
|
||||
|
|
@ -65,5 +104,7 @@ the peer already knows the plaintext they sent.
|
|||
|
||||
## Out of v1
|
||||
|
||||
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,
|
||||
sqlcipher, A/V.
|
||||
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
|
||||
relay, multi-device, DHT / name server, A/V. The local retry queue of the
|
||||
previous section is not an outbox in the XMPP sense: it never leaves the device.
|
||||
|
||||
|
|
|
|||
279
scripts/arti-watch.py
Normal file
279
scripts/arti-watch.py
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Watch upstream Arti / tor-* releases against OnionWire's Cargo.toml pins.
|
||||
|
||||
Runs from .forgejo/workflows/arti-watch.yml (daily cron + workflow_dispatch) on
|
||||
the self-hosted Forgejo runner. For every `tor-*` / `arti-*` direct dependency
|
||||
it reads the version requirement in Cargo.toml, asks crates.io for the newest
|
||||
published versions, and — when the major.minor moved — files ONE Forgejo issue.
|
||||
The issue title carries the compared pair, e.g.
|
||||
|
||||
Arti upstream: tor-hsservice 0.46 -> 0.47
|
||||
|
||||
Dedupe is on that title across all issues (open and closed), so a second run is
|
||||
a no-op: no duplicate issue, no repeated comment. Nothing here bumps a
|
||||
dependency — that stays a reviewed PR; see docs/ARTI_UPGRADE.md.
|
||||
|
||||
What this does NOT cover, by design:
|
||||
* It does not subscribe to Tor Project security announcements. A fix that
|
||||
ships without a crates.io version bump is invisible to this script.
|
||||
* It will not catch a yanked crate, and it will not catch a vulnerability in
|
||||
a version that has not changed. crates.io `max_stable_version` already
|
||||
ignores yanks, so a yank alone produces no alert.
|
||||
Read https://blog.torproject.org/ and https://forum.torproject.org/ yourself.
|
||||
|
||||
Usage:
|
||||
FORGEJO_TOKEN=… REPO_API=https://host/api/v1/repos/owner/repo \
|
||||
scripts/arti-watch.py --cargo-toml Cargo.toml
|
||||
scripts/arti-watch.py --dry-run # no API writes, no token
|
||||
scripts/arti-watch.py --dry-run --simulate-pin arti-client=0.45
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
|
||||
CRATES_API = "https://crates.io/api/v1/crates/{name}"
|
||||
# crates.io rejects a request without a User-Agent (HTTP 403), and Cloudflare in
|
||||
# front of the Forgejo API 403s (error 1010) a python-urllib one. Send our own.
|
||||
USER_AGENT = "onionwire-arti-watch (+https://forgejo.siriusdevops.com/sirius/onionwire)"
|
||||
WATCHED = re.compile(r"^(?:tor|arti)-[a-z0-9-]+$")
|
||||
# "0.46" / "0.46.0" / "0.46.0-alpha.1" — Arti crates publish plain major.minor.patch.
|
||||
SEMVER = re.compile(r"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$")
|
||||
|
||||
|
||||
def log(msg: str) -> None:
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
class HardFail(SystemExit):
|
||||
def __init__(self, msg: str) -> None:
|
||||
super().__init__(2)
|
||||
self.msg = msg
|
||||
|
||||
|
||||
def curl_json(url, token=None, method="GET", body=None):
|
||||
"""curl a JSON endpoint. Returns (http_status, parsed_body_or_None).
|
||||
|
||||
curl rather than urllib: the Cloudflare front door 403s a python-urllib
|
||||
User-Agent, and curl's --retry covers transient 5xx.
|
||||
"""
|
||||
cmd = [
|
||||
"curl", "-sS", "--http1.1",
|
||||
"--retry", "5", "--retry-all-errors", "--retry-delay", "3",
|
||||
"--connect-timeout", "20", "--max-time", "60",
|
||||
"-H", f"User-Agent: {USER_AGENT}",
|
||||
"-H", "Accept: application/json",
|
||||
]
|
||||
if token:
|
||||
cmd += ["-H", f"Authorization: Bearer {token}"]
|
||||
if body is not None:
|
||||
cmd += ["-H", "Content-Type: application/json",
|
||||
"-X", method, "--data-binary", json.dumps(body)]
|
||||
cmd += ["-w", "\n%{http_code}", url]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
|
||||
if proc.returncode != 0:
|
||||
raise HardFail(f"curl exited {proc.returncode} for {method} {url}: {proc.stderr.strip()}")
|
||||
raw, _, code = proc.stdout.rpartition("\n")
|
||||
try:
|
||||
parsed = json.loads(raw) if raw.strip() else None
|
||||
except json.JSONDecodeError:
|
||||
parsed = None
|
||||
return int(code or 0), parsed
|
||||
|
||||
|
||||
def ver(text: str):
|
||||
"""('0.46') -> (0, 46, 0). Hard-fails on anything else, so a surprise
|
||||
version format upstream is loud rather than silently 'not an upgrade'."""
|
||||
m = SEMVER.match(text.strip())
|
||||
if not m:
|
||||
raise HardFail(f"cannot parse version {text!r}")
|
||||
return (int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0))
|
||||
|
||||
|
||||
def parse_pins(cargo_toml: str):
|
||||
"""{crate: version_requirement} for the [dependencies] table only."""
|
||||
pins: dict[str, str] = {}
|
||||
section = ""
|
||||
for line in cargo_toml.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("["):
|
||||
section = stripped.strip("[]").strip()
|
||||
continue
|
||||
if section != "dependencies" or not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
m = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped)
|
||||
if not m:
|
||||
continue
|
||||
name, rest = m.group(1), m.group(2).split("#", 1)[0].strip()
|
||||
if not WATCHED.match(name):
|
||||
continue
|
||||
vm = re.match(r'"([^"]+)"', rest) or re.search(r'version\s*=\s*"([^"]+)"', rest)
|
||||
if vm:
|
||||
pins[name] = vm.group(1)
|
||||
return pins
|
||||
|
||||
|
||||
def crates_io(name: str):
|
||||
"""(stable, newest) version strings for a crate, as crates.io reports them."""
|
||||
status, data = curl_json(CRATES_API.format(name=name))
|
||||
if status != 200 or not isinstance(data, dict) or "crate" not in data:
|
||||
raise HardFail(f"crates.io GET {name} -> HTTP {status} (body: {str(data)[:200]})")
|
||||
crate = data["crate"]
|
||||
return crate["max_stable_version"], crate.get("newest_version") or crate["max_stable_version"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Row:
|
||||
name: str
|
||||
pin: str
|
||||
pin_triple: tuple
|
||||
stable: str
|
||||
newest: str
|
||||
source: str # "Cargo.toml" or "simulate-pin"
|
||||
|
||||
@property
|
||||
def pin_minor(self) -> str:
|
||||
return f"{self.pin_triple[0]}.{self.pin_triple[1]}"
|
||||
|
||||
@property
|
||||
def upgrade(self) -> bool:
|
||||
stable = ver(self.stable)
|
||||
return (stable[0], stable[1]) > (self.pin_triple[0], self.pin_triple[1])
|
||||
|
||||
|
||||
def issue_title(row: Row) -> str:
|
||||
stable = ver(row.stable)
|
||||
return f"Arti upstream: {row.name} {row.pin_minor} \u2192 {stable[0]}.{stable[1]}"
|
||||
|
||||
|
||||
def issue_body(row: Row) -> str:
|
||||
if row.source == "Cargo.toml":
|
||||
lead = f"`{row.name}` is pinned at `{row.pin}` in `Cargo.toml`; crates.io now has **{row.stable}**."
|
||||
else:
|
||||
lead = (f"`{row.name}` is pinned at `{row.pin}` in the `simulate_pin` test input, "
|
||||
f"**not** in `Cargo.toml`; crates.io now has **{row.stable}**. This issue came "
|
||||
f"from a `workflow_dispatch` test run — the repository pin has not changed.")
|
||||
return f"""{lead}
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| crate | `{row.name}` |
|
||||
| pinned requirement | `"{row.pin}"` |
|
||||
| pin source | {row.source} |
|
||||
| newest stable upstream | `{row.stable}` |
|
||||
| newest upstream (incl. pre-release) | `{row.newest}` |
|
||||
| crates.io | https://crates.io/crates/{row.name} |
|
||||
| releases | https://gitlab.torproject.org/tpo/core/arti/-/releases |
|
||||
|
||||
Filed automatically by `.forgejo/workflows/arti-watch.yml`. This is the whole
|
||||
`tor-*` / `arti-*` set moving together — Arti publishes them in lockstep, so do
|
||||
not bump this one alone.
|
||||
|
||||
Procedure, toolchain floor, and the tests a bump must pass:
|
||||
[`docs/ARTI_UPGRADE.md`](../blob/main/docs/ARTI_UPGRADE.md). Rust toolchain floor
|
||||
is rustc 1.91+ (Arti 0.46); a bump may raise it.
|
||||
|
||||
The watcher does **not** subscribe to Tor Project security announcements, and it
|
||||
cannot see a yanked crate or a vulnerability that ships without a version bump.
|
||||
"""
|
||||
|
||||
|
||||
def existing_titles(repo_api: str, token: str) -> dict:
|
||||
"""{title: issue_number} over every issue, open and closed, paginated."""
|
||||
seen: dict[str, int] = {}
|
||||
page = 1
|
||||
while True:
|
||||
url = f"{repo_api}/issues?state=all&type=issues&limit=50&page={page}"
|
||||
status, data = curl_json(url, token)
|
||||
if status != 200 or not isinstance(data, list):
|
||||
raise HardFail(f"GET {url} -> HTTP {status} (body: {str(data)[:200]})")
|
||||
for item in data:
|
||||
seen[item["title"]] = item["number"]
|
||||
if len(data) < 50:
|
||||
return seen
|
||||
page += 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
|
||||
ap.add_argument("--cargo-toml", default="Cargo.toml")
|
||||
ap.add_argument("--dry-run", action="store_true",
|
||||
help="compare and log only; file no issue and need no token")
|
||||
ap.add_argument("--simulate-pin", action="append", default=[], metavar="CRATE=VERSION",
|
||||
help="pretend CRATE is pinned at VERSION (test the alert path "
|
||||
"against real crates.io data without waiting for upstream)")
|
||||
args = ap.parse_args()
|
||||
|
||||
with open(args.cargo_toml, encoding="utf-8") as fh:
|
||||
pins = parse_pins(fh.read())
|
||||
if not pins:
|
||||
raise HardFail(f"no tor-*/arti-* pin found in [dependencies] of {args.cargo_toml}")
|
||||
|
||||
overrides = {}
|
||||
for pair in args.simulate_pin:
|
||||
name, _, version = pair.partition("=")
|
||||
name, version = name.strip(), version.strip()
|
||||
if name not in pins or not version:
|
||||
raise HardFail(f"--simulate-pin {pair!r} is not a watched crate in {args.cargo_toml}")
|
||||
overrides[name] = version
|
||||
|
||||
rows = []
|
||||
for name in sorted(pins):
|
||||
source = "Cargo.toml"
|
||||
pin = pins[name]
|
||||
if name in overrides:
|
||||
pin, source = overrides[name], "simulate-pin"
|
||||
pin_triple = ver(pin)
|
||||
stable, newest = crates_io(name)
|
||||
rows.append(Row(name, pin, pin_triple, stable, newest, source))
|
||||
|
||||
log(f"crates.io comparison ({len(rows)} watched crate(s) from {args.cargo_toml}):")
|
||||
for row in rows:
|
||||
log(f" {row.name}: pinned={row.pin} (from {row.source}) "
|
||||
f"upstream_stable={row.stable} upstream_newest={row.newest} "
|
||||
f"upgrade={'yes' if row.upgrade else 'no'}")
|
||||
|
||||
todo = [row for row in rows if row.upgrade]
|
||||
if not todo:
|
||||
log("no upgrade available: every pin already covers the newest upstream release")
|
||||
return 0
|
||||
|
||||
if args.dry_run:
|
||||
for row in todo:
|
||||
log(f"dry-run: would file issue {issue_title(row)!r}")
|
||||
return 0
|
||||
|
||||
repo_api = os.environ.get("REPO_API", "").rstrip("/")
|
||||
token = "".join((os.environ.get("FORGEJO_TOKEN") or "").split())
|
||||
if not repo_api or not token:
|
||||
raise HardFail("REPO_API and FORGEJO_TOKEN are required unless --dry-run")
|
||||
|
||||
titles = existing_titles(repo_api, token)
|
||||
filed = 0
|
||||
for row in todo:
|
||||
title = issue_title(row)
|
||||
if title in titles:
|
||||
log(f"dedupe: issue #{titles[title]} already carries the title {title!r} — not filing a second one")
|
||||
continue
|
||||
status, created = curl_json(f"{repo_api}/issues", token, "POST",
|
||||
{"title": title, "body": issue_body(row)})
|
||||
if status != 201 or not isinstance(created, dict):
|
||||
raise HardFail(f"POST {repo_api}/issues -> HTTP {status} (body: {str(created)[:300]})")
|
||||
filed += 1
|
||||
log(f"filed issue #{created['number']}: {title} ({created.get('html_url', '')})")
|
||||
log(f"done: {filed} issue(s) filed, {len(todo) - filed} already tracked")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except HardFail as exc:
|
||||
log(f"error: {exc.msg}")
|
||||
sys.exit(exc.code)
|
||||
|
|
@ -4,6 +4,7 @@ use argon2::{Algorithm, Argon2, Params, Version};
|
|||
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
|
||||
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
|
||||
use rand::RngCore;
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
|
||||
|
||||
pub const MAGIC: &[u8] = b"owbak1";
|
||||
const SALT_LEN: usize = 16;
|
||||
|
|
@ -11,17 +12,31 @@ const NONCE_LEN: usize = 12;
|
|||
const KEY_LEN: usize = 32;
|
||||
const PLAIN_LEN: usize = KEY_LEN * 4;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
/// The identity bundle. Secret halves wipe on drop; `Debug` never prints them.
|
||||
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
|
||||
pub struct BackupKeys {
|
||||
pub identity_sk: [u8; 32],
|
||||
#[zeroize(skip)]
|
||||
pub identity_pk: [u8; 32],
|
||||
pub prekey_sk: [u8; 32],
|
||||
#[zeroize(skip)]
|
||||
pub prekey_pk: [u8; 32],
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BackupKeys {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("BackupKeys")
|
||||
.field("identity_sk", &"<redacted>")
|
||||
.field("identity_pk", &self.identity_pk)
|
||||
.field("prekey_sk", &"<redacted>")
|
||||
.field("prekey_pk", &self.prekey_pk)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl BackupKeys {
|
||||
pub fn to_bytes(&self) -> [u8; PLAIN_LEN] {
|
||||
let mut out = [0u8; PLAIN_LEN];
|
||||
pub fn to_bytes(&self) -> Zeroizing<[u8; PLAIN_LEN]> {
|
||||
let mut out = Zeroizing::new([0u8; PLAIN_LEN]);
|
||||
out[0..32].copy_from_slice(&self.identity_sk);
|
||||
out[32..64].copy_from_slice(&self.identity_pk);
|
||||
out[64..96].copy_from_slice(&self.prekey_sk);
|
||||
|
|
@ -42,7 +57,7 @@ impl BackupKeys {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> {
|
||||
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, String> {
|
||||
if passphrase.is_empty() {
|
||||
return Err("empty passphrase".into());
|
||||
}
|
||||
|
|
@ -51,9 +66,9 @@ pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> {
|
|||
}
|
||||
let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?;
|
||||
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
||||
let mut key = [0u8; 32];
|
||||
let mut key = Zeroizing::new([0u8; 32]);
|
||||
argon
|
||||
.hash_password_into(passphrase.as_bytes(), salt, &mut key)
|
||||
.hash_password_into(passphrase.as_bytes(), salt, &mut key[..])
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(key)
|
||||
}
|
||||
|
|
@ -62,13 +77,13 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result<Vec<u8>, String> {
|
|||
let mut salt = [0u8; SALT_LEN];
|
||||
rand::rngs::OsRng.fill_bytes(&mut salt);
|
||||
let key = kdf(passphrase, &salt)?;
|
||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key));
|
||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
||||
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
|
||||
if nonce.len() != NONCE_LEN {
|
||||
return Err("nonce length".into());
|
||||
}
|
||||
let ct = cipher
|
||||
.encrypt(&nonce, keys.to_bytes().as_ref())
|
||||
.encrypt(&nonce, &keys.to_bytes()[..])
|
||||
.map_err(|_| "encrypt failed".to_string())?;
|
||||
let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len());
|
||||
out.extend_from_slice(MAGIC);
|
||||
|
|
@ -88,11 +103,13 @@ pub fn open(passphrase: &str, blob: &[u8]) -> Result<BackupKeys, String> {
|
|||
let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]);
|
||||
let ct = &blob[nonce_off + NONCE_LEN..];
|
||||
let key = kdf(passphrase, salt)?;
|
||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key));
|
||||
let pt = cipher
|
||||
.decrypt(nonce, ct)
|
||||
.map_err(|_| "wrong passphrase or corrupt backup".to_string())?;
|
||||
BackupKeys::from_bytes(&pt)
|
||||
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
|
||||
let pt = Zeroizing::new(
|
||||
cipher
|
||||
.decrypt(nonce, ct)
|
||||
.map_err(|_| "wrong passphrase or corrupt backup".to_string())?,
|
||||
);
|
||||
BackupKeys::from_bytes(&pt[..])
|
||||
}
|
||||
|
||||
pub(crate) fn aead_encrypt(
|
||||
|
|
@ -133,3 +150,45 @@ pub(crate) fn aead_decrypt(key: &[u8; 32], blob: &[u8], aad: &[u8]) -> Result<Ve
|
|||
)
|
||||
.map_err(|_| "wrong passphrase or corrupt".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn keys(tag: u8) -> BackupKeys {
|
||||
BackupKeys {
|
||||
identity_sk: [tag; 32],
|
||||
identity_pk: [tag.wrapping_add(1); 32],
|
||||
prekey_sk: [tag.wrapping_add(2); 32],
|
||||
prekey_pk: [tag.wrapping_add(3); 32],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_wrap_key_is_a_zeroizing_buffer() {
|
||||
let mut key = kdf("correct horse", &[7u8; 16]).expect("kdf");
|
||||
let _: &Zeroizing<[u8; 32]> = &key;
|
||||
let before = *key;
|
||||
assert_ne!(before, [0u8; 32]);
|
||||
key.zeroize();
|
||||
assert_eq!(*key, [0u8; 32], "derived key not wiped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_plaintext_buffer_is_a_zeroizing_buffer() {
|
||||
let mut bytes = keys(5).to_bytes();
|
||||
let _: &Zeroizing<[u8; PLAIN_LEN]> = &bytes;
|
||||
assert_eq!(&bytes[..32], &[5u8; 32][..]);
|
||||
bytes.zeroize();
|
||||
assert_eq!(&bytes[..], &[0u8; PLAIN_LEN][..], "backup plaintext kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_keys_debug_redacts_the_secret_halves() {
|
||||
let dbg = format!("{:?}", keys(0xAB));
|
||||
assert!(!dbg.contains("171"), "identity secret in Debug: {dbg}");
|
||||
assert!(!dbg.contains("173"), "prekey secret in Debug: {dbg}");
|
||||
assert!(dbg.contains("<redacted>"), "{dbg}");
|
||||
assert!(dbg.contains("174"), "public half should stay: {dbg}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
58
src/hs.rs
58
src/hs.rs
|
|
@ -96,6 +96,64 @@ pub fn hs_is_ready(state: State, probe_ok: bool) -> bool {
|
|||
}
|
||||
}
|
||||
|
||||
/// Observable lifecycle state of the node's onion service.
|
||||
///
|
||||
/// This is the four-state projection callers actually act on: is the onion
|
||||
/// service serving, is it serving but unhealthy, is it still coming up, or did
|
||||
/// we stop it. A process that gets killed by the Android background-process
|
||||
/// killer never observes `Stopped` — that is why `Wire.flush()` exists — but a
|
||||
/// clean teardown always does.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TorState {
|
||||
/// Bootstrap or HsDir descriptor upload is still in flight: the service is
|
||||
/// not reliably reachable yet.
|
||||
Bootstrapping,
|
||||
/// The onion service is running and its descriptor is published.
|
||||
Published,
|
||||
/// Reachable through the service, but Arti reports the service degraded.
|
||||
/// Usable, worth surfacing, not identical to `Published`.
|
||||
DegradedReachable,
|
||||
/// The node was shut down: no onion service, no client dials, and the
|
||||
/// store is checkpointed.
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// Project an Arti onion-service status onto [`TorState`].
|
||||
///
|
||||
/// Deliberately mirrors `hs_is_ready`: `Running` and `DegradedReachable` are
|
||||
/// the states a probe could already reach, everything transient is
|
||||
/// `Bootstrapping`, and a shut-down service is `Stopped`.
|
||||
///
|
||||
/// `reachable` is the same evidence `wait_until_published` accepts from a
|
||||
/// probe: a successful connect to our own onion means some HsDir already has
|
||||
/// the descriptor even though Arti's combined status is still `Bootstrapping`
|
||||
/// (that mismatch is exactly what the 360s publish wait exists for). Without
|
||||
/// it, a node that is live and reachable would report `Bootstrapping` for
|
||||
/// another few minutes.
|
||||
///
|
||||
/// Two statuses look terminal but are not:
|
||||
/// * `Shutdown` on a *live* node is transient — a freshly launched service
|
||||
/// reports it before its publish reactor starts, which is why a live node
|
||||
/// reads `Bootstrapping` there and only the explicit stop flag produces
|
||||
/// `Stopped`. (Caught on device-real conditions by the live test: the
|
||||
/// first `tor_state()` after `start()` returned `Shutdown`.)
|
||||
/// * `Broken` maps to `Bootstrapping` rather than a state of its own: Arti
|
||||
/// reads `Broken` while the HsDir retry loop is still going, and
|
||||
/// `wait_until_published` is where a genuinely dead service surfaces as an
|
||||
/// error instead of a flag the UI would have to poll for.
|
||||
pub fn tor_state_of(state: State, stopped: bool, reachable: bool) -> TorState {
|
||||
if stopped {
|
||||
return TorState::Stopped;
|
||||
}
|
||||
match state {
|
||||
State::Running => TorState::Published,
|
||||
State::DegradedReachable => TorState::DegradedReachable,
|
||||
State::Broken | State::Shutdown => TorState::Bootstrapping,
|
||||
_ if reachable => TorState::Published,
|
||||
_ => TorState::Bootstrapping,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn wait_until_published(
|
||||
client: &Client,
|
||||
svc: &RunningOnionService,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ pub mod frame;
|
|||
pub mod hs;
|
||||
pub mod loc;
|
||||
pub mod node;
|
||||
pub mod outbox;
|
||||
pub mod pay;
|
||||
pub mod profile;
|
||||
pub mod qr;
|
||||
|
|
|
|||
423
src/node.rs
423
src/node.rs
|
|
@ -1,6 +1,7 @@
|
|||
//! Two-node onion session: host HS, Noise IK, persist plaintext locally.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
|
|
@ -8,12 +9,14 @@ use futures::StreamExt;
|
|||
use futures::io::{AsyncRead, AsyncWrite};
|
||||
use tor_cell::relaycell::msg::Connected;
|
||||
use tor_hsservice::{RunningOnionService, handle_rend_requests};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::dispatch::{self, Kind};
|
||||
use crate::file;
|
||||
use crate::frame;
|
||||
use crate::hs::{self, Client, HS_PORT};
|
||||
use crate::hs::{self, Client, HS_PORT, TorState};
|
||||
use crate::loc;
|
||||
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
|
||||
use crate::pay;
|
||||
use crate::profile;
|
||||
use crate::qr;
|
||||
|
|
@ -28,8 +31,27 @@ pub struct RotateResult {
|
|||
pub friends: usize,
|
||||
}
|
||||
|
||||
/// What a `flush` actually managed to do, for UI surfacing.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FlushOutcome {
|
||||
/// Outbox rows we tried to deliver in this pass.
|
||||
pub attempted: usize,
|
||||
/// Rows delivered now — their outbox rows are gone.
|
||||
pub delivered: usize,
|
||||
/// Rows still queued or terminally failed after the pass.
|
||||
pub remaining: usize,
|
||||
}
|
||||
|
||||
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
|
||||
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
|
||||
/// the retry worker picks it up on its normal schedule.
|
||||
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
|
||||
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
|
||||
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
struct HsHandle {
|
||||
_svc: Arc<RunningOnionService>,
|
||||
svc: Arc<RunningOnionService>,
|
||||
rend: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
|
|
@ -39,9 +61,18 @@ impl Drop for HsHandle {
|
|||
}
|
||||
}
|
||||
|
||||
/// Abort the outbox worker when the node goes away.
|
||||
struct WorkerHandle(tokio::task::JoinHandle<()>);
|
||||
|
||||
impl Drop for WorkerHandle {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Node {
|
||||
home: PathBuf,
|
||||
store: Mutex<Store>,
|
||||
store: Arc<Mutex<Store>>,
|
||||
client: Client,
|
||||
hs: Mutex<Option<HsHandle>>,
|
||||
onion: Mutex<String>,
|
||||
|
|
@ -49,16 +80,30 @@ pub struct Node {
|
|||
wallet: Wallet,
|
||||
incoming_limit: Mutex<TokenBucket>,
|
||||
inbox: Mutex<file::Inbox>,
|
||||
outbox: Arc<Outbox>,
|
||||
worker: Mutex<Option<WorkerHandle>>,
|
||||
/// Set by `shutdown`. Checked before any operation that would touch Tor or
|
||||
/// the store, so a stopped node fails cleanly instead of dialing.
|
||||
stopped: AtomicBool,
|
||||
/// Has this node's onion service ever crossed the reachability bar (status
|
||||
/// `Running`/`DegradedReachable`, or a successful probe of our own onion)?
|
||||
/// Arti's combined status can stay `Bootstrapping` for minutes *after* the
|
||||
/// descriptor is downloadable, so without this the UI would keep saying
|
||||
/// "starting" long past the point where friends can reach us. Cleared when
|
||||
/// `rotate` hard-cuts the service.
|
||||
onion_reachable: AtomicBool,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> {
|
||||
let pass = std::env::var("ONIONWIRE_STORE_PASSPHRASE")
|
||||
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?;
|
||||
let pass = Zeroizing::new(
|
||||
std::env::var("ONIONWIRE_STORE_PASSPHRASE")
|
||||
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?,
|
||||
);
|
||||
if pass.is_empty() {
|
||||
return Err("empty passphrase".into());
|
||||
}
|
||||
Self::start_with_passphrase(home, &pass).await
|
||||
Self::start_with_passphrase(home, pass.as_str()).await
|
||||
}
|
||||
|
||||
pub async fn start_with_passphrase(
|
||||
|
|
@ -79,9 +124,17 @@ impl Node {
|
|||
let (svc, rend) = launched;
|
||||
let onion = hs::onion_string(&svc)?;
|
||||
let inbox = file::Inbox::new(home.join("inbox"));
|
||||
let store = Arc::new(Mutex::new(store));
|
||||
let outbox = Arc::new(Outbox::new(
|
||||
Arc::clone(&store),
|
||||
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
|
||||
));
|
||||
if let Err(e) = outbox.reset_stale() {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
let node = Arc::new(Self {
|
||||
home,
|
||||
store: Mutex::new(store),
|
||||
store,
|
||||
client,
|
||||
hs: Mutex::new(None),
|
||||
onion: Mutex::new(onion.clone()),
|
||||
|
|
@ -89,15 +142,26 @@ impl Node {
|
|||
wallet: Wallet::from_env(),
|
||||
incoming_limit: Mutex::new(TokenBucket::default()),
|
||||
inbox: Mutex::new(inbox),
|
||||
outbox: Arc::clone(&outbox),
|
||||
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
|
||||
stopped: AtomicBool::new(false),
|
||||
onion_reachable: AtomicBool::new(false),
|
||||
});
|
||||
// Unlock trigger: flush anything queued by a previous run now, in the
|
||||
// background, rather than waiting out its backoff.
|
||||
spawn_flush_all(Arc::clone(&node.outbox));
|
||||
// Accept rens before waiting so a reachability probe can succeed
|
||||
// while combined status is still Bootstrapping.
|
||||
let rend = spawn_rend(Arc::clone(&node), rend);
|
||||
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
||||
_svc: Arc::clone(&svc),
|
||||
svc: Arc::clone(&svc),
|
||||
rend,
|
||||
});
|
||||
hs::wait_until_published(&node.client, &svc, &onion).await?;
|
||||
// Published by the same bar `wait_until_published` uses — a probe
|
||||
// success counts, which is the whole reason `tor_state` tracks it
|
||||
// separately from Arti's (slower, flappier) combined status.
|
||||
node.onion_reachable.store(true, Ordering::SeqCst);
|
||||
node.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
|
|
@ -106,6 +170,141 @@ impl Node {
|
|||
Ok(node)
|
||||
}
|
||||
|
||||
/// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` /
|
||||
/// `DegradedReachable` / `Stopped`.
|
||||
///
|
||||
/// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a
|
||||
/// foreground-service notification can poll it instead of guessing from a
|
||||
/// timer. A poisoned handle is reported as `Stopped` rather than panicking:
|
||||
/// the node is unusable either way, and the caller is often a UI thread.
|
||||
pub fn tor_state(&self) -> TorState {
|
||||
let stopped = self.stopped.load(Ordering::SeqCst);
|
||||
let reachable = self.onion_reachable.load(Ordering::SeqCst);
|
||||
match self.hs.lock() {
|
||||
Ok(guard) => match guard.as_ref() {
|
||||
Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable),
|
||||
// Between `rotate`'s hard cut and the new service being
|
||||
// installed there is no handle; before the first publish there
|
||||
// is none either. Both are "not serving *yet*" unless we stopped.
|
||||
None if stopped => TorState::Stopped,
|
||||
None => TorState::Bootstrapping,
|
||||
},
|
||||
Err(_) => TorState::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Drain the outbox: one delivery attempt for every outstanding row, now,
|
||||
/// ignoring its retry schedule. Then checkpoint the WAL.
|
||||
///
|
||||
/// This is the "deliver what is deliverable before we lose the process"
|
||||
/// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a
|
||||
/// dial for ~20s and the caller is usually a UI thread. Rows that could not
|
||||
/// be delivered stay queued and are picked up by the retry worker on its
|
||||
/// normal backoff.
|
||||
pub async fn flush(&self) -> Result<FlushOutcome, String> {
|
||||
self.ensure_running()?;
|
||||
let outcome = self.drain(FLUSH_TIMEOUT).await?;
|
||||
self.checkpoint();
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Stop the node.
|
||||
///
|
||||
/// Order matters: drain the outbox while the Tor client is still alive,
|
||||
/// then drop the onion service (its rendezvous task is aborted and the v3
|
||||
/// service goes down), then abort the retry worker so nothing dials after
|
||||
/// this, then checkpoint the WAL.
|
||||
///
|
||||
/// Idempotent: the flag is swapped first, so a second call — or a call
|
||||
/// racing another teardown — returns `Ok(())` without touching anything
|
||||
/// twice. Every other method on a stopped node returns a clean `Err`, never
|
||||
/// a panic. A process killed outright never gets here at all, which is why
|
||||
/// [`flush`](Self::flush) exists.
|
||||
pub async fn shutdown(&self) -> Result<(), String> {
|
||||
if self.stopped.swap(true, Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
// Bounded: teardown must not hang behind a Tor dial. Undelivered rows
|
||||
// survive in sqlite and are retried on the next unlock.
|
||||
match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await {
|
||||
Ok(o) if o.remaining > 0 => {
|
||||
eprintln!("shutdown: {} outbox row(s) still pending", o.remaining)
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => eprintln!("shutdown: drain failed: {e}"),
|
||||
}
|
||||
match self.hs.lock() {
|
||||
Ok(mut g) => *g = None,
|
||||
Err(_) => eprintln!("shutdown: onion-service lock poisoned"),
|
||||
}
|
||||
match self.worker.lock() {
|
||||
Ok(mut g) => drop(g.take()),
|
||||
Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"),
|
||||
}
|
||||
self.checkpoint();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One bounded pass over every outstanding outbox row.
|
||||
///
|
||||
/// A timeout cancels the pass mid-flight, which can leave a row in
|
||||
/// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the
|
||||
/// same recovery the parent uses for a process that died mid-attempt.
|
||||
async fn drain(&self, budget: Duration) -> Result<FlushOutcome, String> {
|
||||
let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await {
|
||||
Ok(Ok(rows)) => Some(rows),
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => {
|
||||
eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued");
|
||||
None
|
||||
}
|
||||
};
|
||||
let delivered = attempted
|
||||
.as_ref()
|
||||
.map(|rows| {
|
||||
rows.iter()
|
||||
.filter(|(_, s)| matches!(s, OutboxStatus::Sent))
|
||||
.count()
|
||||
})
|
||||
.unwrap_or(0);
|
||||
Ok(FlushOutcome {
|
||||
// `None` means the pass was cancelled: we know how many rows are
|
||||
// still queued, not how many were started.
|
||||
attempted: attempted.as_ref().map(Vec::len).unwrap_or(0),
|
||||
delivered,
|
||||
remaining: self.pending_rows()?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Rows the outbox still holds for every friend, queued or terminally
|
||||
/// failed. A message absent here was delivered.
|
||||
fn pending_rows(&self) -> Result<usize, String> {
|
||||
let friends = self.list_friends()?;
|
||||
let mut n = 0usize;
|
||||
for f in &friends {
|
||||
n += self.outbox.pending(&f.pubkey)?.len();
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Checkpoint the sqlite WAL into the main db file and truncate it.
|
||||
///
|
||||
/// Best effort on purpose: WAL replay on open recovers everything committed,
|
||||
/// so this is about leaving less to replay (and less on disk) if the
|
||||
/// process is killed right after teardown — not about correctness.
|
||||
fn checkpoint(&self) {
|
||||
if let Err(e) = checkpoint_wal(&self.home) {
|
||||
eprintln!("wal checkpoint: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_running(&self) -> Result<(), String> {
|
||||
if self.stopped.load(Ordering::SeqCst) {
|
||||
return Err("node is stopped — open the identity again".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn onion(&self) -> String {
|
||||
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
|
||||
}
|
||||
|
|
@ -406,6 +605,7 @@ impl Node {
|
|||
}
|
||||
|
||||
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
|
||||
self.ensure_running()?;
|
||||
let (onion, prekey) = {
|
||||
let f = self.friend(friend_pk)?;
|
||||
if f.prekey.len() != 32 {
|
||||
|
|
@ -416,7 +616,10 @@ impl Node {
|
|||
self.try_send(&onion, friend_pk, &prekey, plaintext).await
|
||||
}
|
||||
|
||||
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
|
||||
/// the outbox retry triggers.
|
||||
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
|
||||
self.ensure_running()?;
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(20),
|
||||
self.client.connect((onion, HS_PORT)),
|
||||
|
|
@ -424,10 +627,19 @@ impl Node {
|
|||
.await
|
||||
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
if let Ok(Some(friend)) = self
|
||||
.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
|
||||
{
|
||||
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
|
||||
self.ensure_running()?;
|
||||
let old_nick = self
|
||||
.store
|
||||
.lock()
|
||||
|
|
@ -444,12 +656,16 @@ impl Node {
|
|||
let onion = hs::onion_string(&svc)?;
|
||||
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
|
||||
*self.hs.lock().map_err(|e| e.to_string())? = None;
|
||||
// The new service is not reachable until it publishes: the locator in
|
||||
// flight is dead until then, so do not carry the old verdict over.
|
||||
self.onion_reachable.store(false, Ordering::SeqCst);
|
||||
let rend = spawn_rend(Arc::clone(self), rend);
|
||||
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
|
||||
_svc: Arc::clone(&svc),
|
||||
svc: Arc::clone(&svc),
|
||||
rend,
|
||||
});
|
||||
hs::wait_until_published(&self.client, &svc, &onion).await?;
|
||||
self.onion_reachable.store(true, Ordering::SeqCst);
|
||||
{
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
store.set_onion(&onion).map_err(|e| e.to_string())?;
|
||||
|
|
@ -506,36 +722,31 @@ impl Node {
|
|||
Ok(name)
|
||||
}
|
||||
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
|
||||
let (onion, prekey) = {
|
||||
let store = self.store.lock().map_err(|e| e.to_string())?;
|
||||
let f = store
|
||||
.get_friend(friend_pk)
|
||||
.map_err(|e| e.to_string())?
|
||||
.ok_or_else(|| "unknown friend".to_string())?;
|
||||
if f.prekey.len() != 32 {
|
||||
return Err("friend missing prekey".into());
|
||||
}
|
||||
(f.onion, f.prekey)
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(180);
|
||||
let mut last = None::<String>;
|
||||
while Instant::now() < deadline {
|
||||
match self.try_send(&onion, friend_pk, &prekey, plaintext).await {
|
||||
Ok(()) => {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
.append_message(friend_pk, "out", plaintext)
|
||||
.map_err(|e| e.to_string())?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
}
|
||||
Err(last.unwrap_or_else(|| "send timed out".into()))
|
||||
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
|
||||
/// when the peer's onion is unreachable — the outbox worker then retries with
|
||||
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
|
||||
/// frame) still fails immediately and is never retried.
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||
self.ensure_running()?;
|
||||
self.outbox.send(friend_pk, plaintext).await
|
||||
}
|
||||
|
||||
/// Pending and failed outbox rows for a friend, for UI surfacing.
|
||||
/// Delivered rows are dropped, so a message absent here was sent.
|
||||
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
|
||||
self.outbox.pending(friend_pk)
|
||||
}
|
||||
|
||||
pub fn outbox_status_of_message(
|
||||
&self,
|
||||
message_id: i64,
|
||||
) -> Result<Option<OutboxStatus>, String> {
|
||||
self.outbox.status_of_message(message_id)
|
||||
}
|
||||
|
||||
/// Foreground/unlock trigger: try every outstanding queued send now.
|
||||
pub fn flush_outbox(&self) {
|
||||
spawn_flush_all(Arc::clone(&self.outbox));
|
||||
}
|
||||
|
||||
async fn push_loc(
|
||||
|
|
@ -568,20 +779,10 @@ impl Node {
|
|||
remote_prekey: &[u8],
|
||||
plaintext: &[u8],
|
||||
) -> Result<(), String> {
|
||||
let mut stream = self
|
||||
.client
|
||||
.connect((onion, HS_PORT))
|
||||
self.outbox
|
||||
.deliverer()
|
||||
.deliver(onion, pinned_id, remote_prekey, plaintext)
|
||||
.await
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
let keys = self.keys()?;
|
||||
let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey)
|
||||
.await
|
||||
.map_err(session_err)?;
|
||||
let ct = sess.encrypt(plaintext).map_err(session_err)?;
|
||||
frame::write_frame(&mut stream, &ct)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
|
||||
|
|
@ -598,6 +799,9 @@ impl Node {
|
|||
})
|
||||
.await
|
||||
.map_err(session_err)?;
|
||||
// Trigger (c): the peer just proved they are online. Try their queued
|
||||
// sends now instead of waiting out the backoff, off this stream's path.
|
||||
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
|
||||
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
|
||||
let pt = sess.decrypt(&ct).map_err(session_err)?;
|
||||
match dispatch::classify(&pt) {
|
||||
|
|
@ -814,6 +1018,67 @@ fn spawn_rend(
|
|||
})
|
||||
}
|
||||
|
||||
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
|
||||
fn spawn_flush_all(outbox: Arc<Outbox>) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = outbox.flush_all(unix_now()).await {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// We just saw this peer (handshake or successful dial): try their queue now.
|
||||
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Checkpoint the sqlite WAL into the main db file and truncate it.
|
||||
///
|
||||
/// `Store` owns the write connection and deliberately does not lend it out, and
|
||||
/// a checkpoint is a property of the *database*, not of one connection — so a
|
||||
/// short-lived second connection to the same file is the least invasive way to
|
||||
/// reach it from the node without widening `Store`'s API.
|
||||
///
|
||||
/// That works because the connection needs no passphrase: it moves
|
||||
/// already-committed pages, it does not decrypt them. It stops working the
|
||||
/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only
|
||||
/// inside `Store` and a second connection cannot read the file at all. That case
|
||||
/// is detected and reported as a skip rather than a failure: nothing is lost
|
||||
/// (sqlite folds the WAL into the db when the last connection closes) — the
|
||||
/// explicit truncation just has to move inside `Store` to happen here.
|
||||
fn checkpoint_wal(home: &Path) -> Result<(), String> {
|
||||
let db = home.join("onionwire.db");
|
||||
if !db.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
|
||||
let (busy, log, checkpointed): (i64, i64, i64) = conn
|
||||
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
})
|
||||
.map_err(|e| {
|
||||
let msg = e.to_string();
|
||||
if msg.contains("not a database") {
|
||||
// SQLCipher store: no key here, so this connection sees noise.
|
||||
format!("store is SQLCipher-encrypted — skipped ({msg})")
|
||||
} else {
|
||||
format!("wal_checkpoint: {msg}")
|
||||
}
|
||||
})?;
|
||||
if busy != 0 {
|
||||
// Another connection is reading/writing: pages are still safe in the
|
||||
// WAL, they just were not moved this time.
|
||||
return Err(format!(
|
||||
"busy ({checkpointed}/{log} pages moved, another connection active)"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_hs_nickname(cur: &str) -> String {
|
||||
let n = cur
|
||||
.strip_prefix("ow")
|
||||
|
|
@ -856,3 +1121,57 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
|
|||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod lifecycle_tests {
|
||||
//! Offline half of the shutdown contract. The live-Tor half lives in
|
||||
//! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// `checkpoint_wal` reaches the database through a *second* connection,
|
||||
/// because `Store` owns the write one. That assumption is the whole reason
|
||||
/// the helper can live in `node.rs`, so prove it against a real WAL.
|
||||
#[test]
|
||||
fn checkpoint_wal_truncates_a_live_wal() {
|
||||
let root = tempfile::tempdir().expect("tempdir");
|
||||
let home = root.path();
|
||||
let db = home.join("onionwire.db");
|
||||
let conn = rusqlite::Connection::open(&db).expect("open db");
|
||||
let mode: String = conn
|
||||
.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
|
||||
.expect("wal mode");
|
||||
assert_eq!(mode.to_lowercase(), "wal");
|
||||
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
|
||||
.expect("create table");
|
||||
for _ in 0..64 {
|
||||
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]])
|
||||
.expect("insert");
|
||||
}
|
||||
|
||||
let wal = home.join("onionwire.db-wal");
|
||||
let before = std::fs::metadata(&wal).expect("wal file").len();
|
||||
assert!(before > 0, "expected pending WAL frames, got {before}");
|
||||
|
||||
checkpoint_wal(home).expect("checkpoint");
|
||||
|
||||
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
|
||||
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
|
||||
|
||||
// The rows are still there — a checkpoint moves pages, it never drops
|
||||
// committed data.
|
||||
let n: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
|
||||
.expect("count");
|
||||
assert_eq!(n, 64);
|
||||
}
|
||||
|
||||
/// A home directory with no store yet is not an error: `shutdown` and
|
||||
/// `flush` are safe to call on a node whose db was never created (tests,
|
||||
/// wiped installs).
|
||||
#[test]
|
||||
fn checkpoint_wal_is_a_no_op_without_a_database() {
|
||||
let root = tempfile::tempdir().expect("tempdir");
|
||||
checkpoint_wal(root.path()).expect("no db, no error");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
308
src/outbox.rs
Normal file
308
src/outbox.rs
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
//! Local-only outbox.
|
||||
//!
|
||||
//! When a peer's v3 onion cannot be dialed, a chat send is persisted locally and
|
||||
//! retried by a background worker with exponential backoff. There is no server
|
||||
//! and no store-and-forward relay: every attempt is a fresh Noise IK handshake
|
||||
//! straight to the friend's onion, so a queued message is never handed to a
|
||||
//! third party. File transfer and payment frames stay fail-closed — only chat
|
||||
//! goes through here.
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tokio::sync::Notify;
|
||||
|
||||
use crate::frame;
|
||||
use crate::hs::{Client, HS_PORT};
|
||||
use crate::session::{self, Keys};
|
||||
use crate::store::Store;
|
||||
|
||||
pub use crate::store::{OutboxEntry, OutboxStatus};
|
||||
|
||||
/// First retry waits this long.
|
||||
pub const BACKOFF_START_SECS: i64 = 30;
|
||||
/// Backoff never sleeps longer than this.
|
||||
pub const BACKOFF_CAP_SECS: i64 = 1_800;
|
||||
/// Attempts after which a queued message is terminally `Failed`.
|
||||
pub const DEFAULT_MAX_ATTEMPTS: u32 = 8;
|
||||
/// Worker scan period. The shortest backoff is 30s, so a slower scan still
|
||||
/// lands each retry close to its schedule without busy-waiting.
|
||||
pub const WORKER_TICK: Duration = Duration::from_secs(15);
|
||||
/// Cap on rows attempted in one pass, so a big backlog cannot monopolize the
|
||||
/// worker.
|
||||
const MAX_PER_PASS: i64 = 32;
|
||||
|
||||
pub type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Pure backoff schedule, asserted numerically by a unit test: 30s, 60s, 120s…
|
||||
/// capped at 30 min. `attempt` is the number of retries already made.
|
||||
pub fn backoff_secs(attempt: u32) -> i64 {
|
||||
// 30 << 16 is the largest shift we ever need to reach the cap, so this
|
||||
// cannot overflow even for a silly attempt count.
|
||||
(BACKOFF_START_SECS << attempt.min(16)).min(BACKOFF_CAP_SECS)
|
||||
}
|
||||
|
||||
/// Protocol failures: another attempt cannot fix a bad signature, a bad frame
|
||||
/// header, or an oversize payload, so they must fail loudly and never queue.
|
||||
const PERMANENT_ERRORS: &[&str] = &[
|
||||
"fingerprint mismatch",
|
||||
"bad identity proof",
|
||||
"unexpected handshake payload",
|
||||
"frame too large",
|
||||
"bad version",
|
||||
"length mismatch",
|
||||
"short frame",
|
||||
];
|
||||
|
||||
pub fn is_permanent_send_error(err: &str) -> bool {
|
||||
PERMANENT_ERRORS.iter().any(|p| err.contains(p))
|
||||
}
|
||||
|
||||
/// One delivery attempt. Implemented by Arti for real sends and by tests for a
|
||||
/// fake or flaky peer.
|
||||
pub trait Deliverer: Send + Sync {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
onion: &'a str,
|
||||
pinned_id: &'a [u8],
|
||||
prekey: &'a [u8],
|
||||
plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>>;
|
||||
}
|
||||
|
||||
/// Real transport: dial the v3 onion, Noise IK handshake pinned to the friend's
|
||||
/// identity key, send exactly one application frame, drop the circuit.
|
||||
pub struct ArtiDeliverer {
|
||||
client: Client,
|
||||
keys: Keys,
|
||||
}
|
||||
|
||||
impl ArtiDeliverer {
|
||||
pub fn new(client: Client, keys: Keys) -> Self {
|
||||
Self { client, keys }
|
||||
}
|
||||
}
|
||||
|
||||
impl Deliverer for ArtiDeliverer {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
onion: &'a str,
|
||||
pinned_id: &'a [u8],
|
||||
prekey: &'a [u8],
|
||||
plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>> {
|
||||
Box::pin(async move {
|
||||
let mut stream = self
|
||||
.client
|
||||
.connect((onion, HS_PORT))
|
||||
.await
|
||||
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
|
||||
let mut sess =
|
||||
session::handshake_initiator(&mut stream, &self.keys, pinned_id, prekey)
|
||||
.await
|
||||
.map_err(|e| e.into_message())?;
|
||||
let ct = sess.encrypt(plaintext).map_err(|e| e.into_message())?;
|
||||
frame::write_frame(&mut stream, &ct)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Outbox {
|
||||
store: Arc<Mutex<Store>>,
|
||||
deliverer: Arc<dyn Deliverer>,
|
||||
max_attempts: u32,
|
||||
wake: Notify,
|
||||
}
|
||||
|
||||
impl Outbox {
|
||||
pub fn new(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>) -> Self {
|
||||
Self {
|
||||
store,
|
||||
deliverer,
|
||||
max_attempts: DEFAULT_MAX_ATTEMPTS,
|
||||
wake: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_max_attempts(mut self, max: u32) -> Self {
|
||||
self.max_attempts = max.max(1);
|
||||
self
|
||||
}
|
||||
|
||||
/// The transport, for callers (locator/profile pushes) that stay fail-closed
|
||||
/// and must not queue.
|
||||
pub fn deliverer(&self) -> &dyn Deliverer {
|
||||
self.deliverer.as_ref()
|
||||
}
|
||||
|
||||
/// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is
|
||||
/// unreachable, the message is persisted and will be retried. `Err` — a
|
||||
/// protocol error or a bad local state, never retried.
|
||||
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
|
||||
let (onion, prekey) = self.target(friend_pk)?;
|
||||
match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await {
|
||||
Ok(()) => {
|
||||
self.store()?.append_message(friend_pk, "out", plaintext)?;
|
||||
Ok(OutboxStatus::Sent)
|
||||
}
|
||||
Err(e) if is_permanent_send_error(&e) => Err(e),
|
||||
Err(e) => {
|
||||
let now = unix_now();
|
||||
let store = self.store()?;
|
||||
let message_id = store.append_message_id(friend_pk, "out", plaintext)?;
|
||||
store.enqueue_outbox(
|
||||
friend_pk,
|
||||
message_id,
|
||||
1,
|
||||
now + backoff_secs(0),
|
||||
&e,
|
||||
now,
|
||||
)?;
|
||||
Ok(OutboxStatus::Queued)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timer trigger: every row whose backoff has elapsed gets one attempt.
|
||||
pub async fn tick(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let due = self.store()?.due_outbox(now, MAX_PER_PASS)?;
|
||||
self.attempt(due, now).await
|
||||
}
|
||||
|
||||
/// Unlock / foreground trigger: every outstanding row gets one attempt now,
|
||||
/// regardless of where it sits in the backoff.
|
||||
pub async fn flush_all(&self, now: i64) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let rows = self.store()?.all_pending_outbox(MAX_PER_PASS)?;
|
||||
self.attempt(rows, now).await
|
||||
}
|
||||
|
||||
/// Trigger (c): we just heard from this peer, so try their rows immediately.
|
||||
pub async fn flush_friend(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
now: i64,
|
||||
) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let rows = self.store()?.outbox_for_friend(friend_pk)?;
|
||||
self.attempt(rows, now).await
|
||||
}
|
||||
|
||||
/// Pending and failed rows for one friend. Delivered rows are deleted, so a
|
||||
/// message that is not here was either sent first try or flushed since.
|
||||
pub fn pending(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>, String> {
|
||||
self.store()?.pending_outbox(friend_pk).map_err(store_err)
|
||||
}
|
||||
|
||||
pub fn status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>, String> {
|
||||
self.store()?
|
||||
.outbox_status_of_message(message_id)
|
||||
.map_err(store_err)
|
||||
}
|
||||
|
||||
/// A process that died mid-attempt leaves `sending` rows behind; requeue
|
||||
/// them on unlock so they are retried instead of stranded.
|
||||
pub fn reset_stale(&self) -> Result<usize, String> {
|
||||
self.store()?.reset_sending_outbox().map_err(store_err)
|
||||
}
|
||||
|
||||
/// Wake the worker (e.g. after `flush_all` was queued from a UI thread).
|
||||
pub fn kick(&self) {
|
||||
self.wake.notify_one();
|
||||
}
|
||||
|
||||
/// Background retry worker. Aborted by dropping the returned handle.
|
||||
pub fn spawn_worker(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
|
||||
let me = Arc::clone(self);
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
if let Err(e) = me.tick(unix_now()).await {
|
||||
eprintln!("outbox: {e}");
|
||||
}
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(WORKER_TICK) => {}
|
||||
_ = me.wake.notified() => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn attempt(
|
||||
&self,
|
||||
rows: Vec<OutboxEntry>,
|
||||
now: i64,
|
||||
) -> Result<Vec<(i64, OutboxStatus)>, String> {
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for entry in rows {
|
||||
self.store()?.mark_outbox_sending(entry.id, now)?;
|
||||
let (onion, prekey) = match self.target(&entry.friend_pk) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
|
||||
out.push((entry.id, OutboxStatus::Failed(e)));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let result = self
|
||||
.deliverer
|
||||
.deliver(&onion, &entry.friend_pk, &prekey, &entry.body)
|
||||
.await;
|
||||
let status = match result {
|
||||
Ok(()) => {
|
||||
self.store()?.mark_outbox_sent(entry.id)?;
|
||||
OutboxStatus::Sent
|
||||
}
|
||||
Err(e) if is_permanent_send_error(&e) => {
|
||||
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
|
||||
OutboxStatus::Failed(e)
|
||||
}
|
||||
Err(e) => {
|
||||
let attempts = entry.attempts.saturating_add(1);
|
||||
if attempts >= self.max_attempts {
|
||||
self.store()?.mark_outbox_failed(entry.id, now, &e)?;
|
||||
OutboxStatus::Failed(e)
|
||||
} else {
|
||||
let next = now + backoff_secs(attempts - 1);
|
||||
self.store()?
|
||||
.mark_outbox_retry(entry.id, attempts, next, now, &e)?;
|
||||
OutboxStatus::Queued
|
||||
}
|
||||
}
|
||||
};
|
||||
out.push((entry.id, status));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Friend's current locator + Noise static. Missing prekey means the invite
|
||||
/// was never completed — retrying cannot fix that, so it is fatal.
|
||||
fn target(&self, friend_pk: &[u8]) -> Result<(String, Vec<u8>), String> {
|
||||
let store = self.store()?;
|
||||
let f = store
|
||||
.get_friend(friend_pk)
|
||||
.map_err(store_err)?
|
||||
.ok_or_else(|| "unknown friend".to_string())?;
|
||||
if f.prekey.len() != 32 {
|
||||
return Err("friend missing prekey".into());
|
||||
}
|
||||
Ok((f.onion, f.prekey))
|
||||
}
|
||||
|
||||
fn store(&self) -> Result<MutexGuard<'_, Store>, String> {
|
||||
self.store.lock().map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn store_err(e: crate::store::Error) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
fn unix_now() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
10
src/pay.rs
10
src/pay.rs
|
|
@ -1,5 +1,6 @@
|
|||
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
||||
use sha3::{Digest, Keccak256};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
|
|
@ -386,9 +387,12 @@ fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec<u8> {
|
|||
}
|
||||
|
||||
fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result<Vec<u8>> {
|
||||
let sk_bytes: [u8; 32] = identity_sk
|
||||
.try_into()
|
||||
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
|
||||
// ed25519-dalek's `SigningKey` wipes itself on drop (its default `zeroize`
|
||||
// feature); the raw copy we make to build it is ours to wipe.
|
||||
let sk_bytes = Zeroizing::new(
|
||||
<[u8; 32]>::try_from(identity_sk)
|
||||
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?,
|
||||
);
|
||||
let sk = SigningKey::from_bytes(&sk_bytes);
|
||||
Ok(sk.sign(msg).to_bytes().to_vec())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
|
|
@ -34,9 +35,10 @@ pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result<S
|
|||
if !is_v3_onion(onion) {
|
||||
return Err(Error("o must be a v3 onion".into()));
|
||||
}
|
||||
let sk_bytes: [u8; 32] = identity_sk
|
||||
.try_into()
|
||||
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
|
||||
let sk_bytes = Zeroizing::new(
|
||||
<[u8; 32]>::try_from(identity_sk)
|
||||
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?,
|
||||
);
|
||||
let sk = SigningKey::from_bytes(&sk_bytes);
|
||||
let k = to_hex(&sk.verifying_key().to_bytes());
|
||||
let spk = to_hex(signed_prekey);
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
|
|||
use rand::rngs::OsRng;
|
||||
use snow::Builder;
|
||||
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
|
||||
|
||||
use crate::store::SelfIdentity;
|
||||
|
||||
|
|
@ -35,6 +36,16 @@ impl Error {
|
|||
pub fn is_fingerprint_mismatch(&self) -> bool {
|
||||
self.mismatch
|
||||
}
|
||||
|
||||
/// String for the UI: a pinned-identity mismatch gets the documented banner,
|
||||
/// everything else is the underlying snow/framing message.
|
||||
pub fn into_message(self) -> String {
|
||||
if self.mismatch {
|
||||
crate::tui::fingerprint_mismatch_banner().to_string()
|
||||
} else {
|
||||
self.msg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
|
|
@ -51,11 +62,15 @@ impl From<snow::Error> for Error {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
/// Local secret keys. `Clone` copies the secrets, but the copy is itself
|
||||
/// `ZeroizeOnDrop`, so no clone outlives its owner un-wiped.
|
||||
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
|
||||
pub struct Keys {
|
||||
pub identity_sk: [u8; 32],
|
||||
#[zeroize(skip)]
|
||||
pub identity_pk: [u8; 32],
|
||||
pub prekey_sk: [u8; 32],
|
||||
#[zeroize(skip)]
|
||||
pub prekey_pk: [u8; 32],
|
||||
}
|
||||
|
||||
|
|
@ -121,7 +136,7 @@ pub fn handshake_pinned(init: &Keys, resp: &Keys, pinned: &[u8; 32]) -> Result<(
|
|||
.prologue(PROLOGUE)?
|
||||
.build_responder()?;
|
||||
|
||||
let mut buf = vec![0u8; MSG_BUF];
|
||||
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
|
||||
let n = initiator.write_message(&[], &mut buf)?;
|
||||
let msg1 = buf[..n].to_vec();
|
||||
let n = responder.read_message(&msg1, &mut buf)?;
|
||||
|
|
@ -190,7 +205,7 @@ where
|
|||
.prologue(PROLOGUE)?
|
||||
.build_initiator()?;
|
||||
|
||||
let mut buf = vec![0u8; MSG_BUF];
|
||||
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
|
||||
let n = hs.write_message(&[], &mut buf)?;
|
||||
crate::frame::write_frame(stream, &buf[..n])
|
||||
.await
|
||||
|
|
@ -244,7 +259,7 @@ where
|
|||
.prologue(PROLOGUE)?
|
||||
.build_responder()?;
|
||||
|
||||
let mut buf = vec![0u8; MSG_BUF];
|
||||
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
|
||||
let msg1 = crate::frame::read_frame(stream)
|
||||
.await
|
||||
.map_err(|e| Error::new(e.to_string()))?;
|
||||
|
|
|
|||
763
src/store.rs
763
src/store.rs
|
|
@ -1,4 +1,5 @@
|
|||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
|
@ -8,6 +9,7 @@ use rand::RngCore;
|
|||
use rand::rngs::OsRng;
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
|
|
@ -40,16 +42,26 @@ impl From<String> for Error {
|
|||
}
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
conn: Connection,
|
||||
msg_key: [u8; 32],
|
||||
/// The store error is a message and nothing else, and the rest of the crate
|
||||
/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the
|
||||
/// outbox boundary — no per-call `map_err`.
|
||||
impl From<Error> for String {
|
||||
fn from(e: Error) -> Self {
|
||||
e.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Store {
|
||||
conn: Connection,
|
||||
msg_key: Zeroizing<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// The identity row. Secret halves wipe when this is dropped.
|
||||
pub struct SelfIdentity {
|
||||
pub identity_sk: Vec<u8>,
|
||||
pub identity_sk: Zeroizing<Vec<u8>>,
|
||||
pub identity_pk: Vec<u8>,
|
||||
pub onion: String,
|
||||
pub prekey_sk: Vec<u8>,
|
||||
pub prekey_sk: Zeroizing<Vec<u8>>,
|
||||
pub prekey_pk: Vec<u8>,
|
||||
}
|
||||
|
||||
|
|
@ -88,6 +100,64 @@ pub struct Payment {
|
|||
pub created_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum OutboxStatus {
|
||||
Queued,
|
||||
Sending,
|
||||
Sent,
|
||||
/// Terminal: transport or protocol failure that will not be retried.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl OutboxStatus {
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_))
|
||||
}
|
||||
|
||||
/// Column encoding for the `outbox.status` CHECK constraint.
|
||||
pub fn as_db_str(&self) -> &'static str {
|
||||
match self {
|
||||
OutboxStatus::Queued => "queued",
|
||||
OutboxStatus::Sending => "sending",
|
||||
OutboxStatus::Sent => "sent",
|
||||
OutboxStatus::Failed(_) => "failed",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_db(status: &str, last_error: Option<&str>) -> Self {
|
||||
match status {
|
||||
"sending" => OutboxStatus::Sending,
|
||||
"sent" => OutboxStatus::Sent,
|
||||
"failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()),
|
||||
_ => OutboxStatus::Queued,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for OutboxStatus {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
OutboxStatus::Failed(why) => write!(f, "failed: {why}"),
|
||||
other => f.write_str(other.as_db_str()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One queued chat send. The body is not copied: it lives in the `messages`
|
||||
/// row the outbox row points at, under that row's own AEAD.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OutboxEntry {
|
||||
pub id: i64,
|
||||
pub friend_pk: Vec<u8>,
|
||||
pub message_id: i64,
|
||||
pub body: Vec<u8>,
|
||||
pub attempts: u32,
|
||||
pub next_attempt_at: i64,
|
||||
pub created_at: i64,
|
||||
pub status: OutboxStatus,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
pub struct PaymentWrite<'a> {
|
||||
pub dir: &'a str,
|
||||
pub kind: &'a str,
|
||||
|
|
@ -108,7 +178,8 @@ impl Store {
|
|||
}
|
||||
|
||||
pub fn open_at(home: &Path) -> Result<Self> {
|
||||
Self::open_at_with_passphrase(home, &passphrase_from_env()?)
|
||||
let passphrase = passphrase_from_env()?;
|
||||
Self::open_at_with_passphrase(home, passphrase.as_str())
|
||||
}
|
||||
|
||||
pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result<Self> {
|
||||
|
|
@ -119,7 +190,7 @@ impl Store {
|
|||
mkdir_700(&home.join("arti"))?;
|
||||
mkdir_700(&home.join("cache"))?;
|
||||
let db_path = home.join("onionwire.db");
|
||||
let conn = Connection::open(&db_path)?;
|
||||
let conn = open_store_db(home, &db_path, passphrase)?;
|
||||
let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
|
||||
if !journal.eq_ignore_ascii_case("wal") {
|
||||
return Err(Error(format!("journal_mode WAL failed: {journal}")));
|
||||
|
|
@ -189,6 +260,18 @@ impl Store {
|
|||
verified INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS outbox (
|
||||
id INTEGER PRIMARY KEY,
|
||||
friend_id INTEGER NOT NULL REFERENCES friends(id),
|
||||
message_id INTEGER NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_attempt_at INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
|
||||
last_error TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
|
||||
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
|
||||
",
|
||||
)?;
|
||||
|
|
@ -198,7 +281,7 @@ impl Store {
|
|||
}
|
||||
let mut store = Self {
|
||||
conn,
|
||||
msg_key: [0u8; 32],
|
||||
msg_key: Zeroizing::new([0u8; 32]),
|
||||
};
|
||||
store.migrate()?;
|
||||
store.ensure_self()?;
|
||||
|
|
@ -274,8 +357,11 @@ impl Store {
|
|||
match row {
|
||||
Some((salt, wrapped)) => {
|
||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
||||
let raw = crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
||||
.map_err(|_| Error("wrong passphrase".into()))?;
|
||||
// The unwrapped data key lands in a Zeroizing buffer immediately.
|
||||
let raw = Zeroizing::new(
|
||||
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
|
||||
.map_err(|_| Error("wrong passphrase".into()))?,
|
||||
);
|
||||
if raw.len() != 32 {
|
||||
return Err(Error("wrapped message key length".into()));
|
||||
}
|
||||
|
|
@ -284,12 +370,12 @@ impl Store {
|
|||
Ok(())
|
||||
}
|
||||
None => {
|
||||
let mut data_key = [0u8; 32];
|
||||
OsRng.fill_bytes(&mut data_key);
|
||||
let mut data_key = Zeroizing::new([0u8; 32]);
|
||||
OsRng.fill_bytes(&mut data_key[..]);
|
||||
let mut salt = [0u8; 16];
|
||||
OsRng.fill_bytes(&mut salt);
|
||||
let wrap_key = crate::backup::kdf(passphrase, &salt)?;
|
||||
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key, b"")?;
|
||||
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
|
||||
self.conn.execute(
|
||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
||||
params![salt.as_slice(), wrapped],
|
||||
|
|
@ -383,13 +469,13 @@ impl Store {
|
|||
})?;
|
||||
if exists == 0 {
|
||||
let signing = SigningKey::generate(&mut OsRng);
|
||||
let sk = signing.to_bytes().to_vec();
|
||||
let sk = Zeroizing::new(signing.to_bytes().to_vec());
|
||||
let pk = signing.verifying_key().to_bytes().to_vec();
|
||||
let (psk, ppk) = gen_prekey();
|
||||
self.conn.execute(
|
||||
"INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname)
|
||||
VALUES (1, ?1, ?2, '', 0, ?3, ?4, 'ow0')",
|
||||
params![sk, pk, psk, ppk],
|
||||
params![&sk[..], pk, &psk[..], ppk],
|
||||
)?;
|
||||
} else {
|
||||
let empty: i64 = self.conn.query_row(
|
||||
|
|
@ -401,7 +487,7 @@ impl Store {
|
|||
let (psk, ppk) = gen_prekey();
|
||||
self.conn.execute(
|
||||
"UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1",
|
||||
params![psk, ppk],
|
||||
params![&psk[..], ppk],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
|
@ -415,10 +501,10 @@ impl Store {
|
|||
[],
|
||||
|row| {
|
||||
Ok(SelfIdentity {
|
||||
identity_sk: row.get(0)?,
|
||||
identity_sk: Zeroizing::new(row.get(0)?),
|
||||
identity_pk: row.get(1)?,
|
||||
onion: row.get(2)?,
|
||||
prekey_sk: row.get(3)?,
|
||||
prekey_sk: Zeroizing::new(row.get(3)?),
|
||||
prekey_pk: row.get(4)?,
|
||||
})
|
||||
},
|
||||
|
|
@ -475,6 +561,20 @@ impl Store {
|
|||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Locator → friend. Onions are not unique in the schema (a stale row can
|
||||
/// hold a rotated address), so the first match wins; the outbox uses this
|
||||
/// only to pick which queue to flush early.
|
||||
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
|
||||
params![onion],
|
||||
friend_from_row,
|
||||
)
|
||||
.optional()
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn list_friends(&self) -> Result<Vec<Friend>> {
|
||||
let mut stmt = self.conn.prepare(
|
||||
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
|
||||
|
|
@ -699,6 +799,17 @@ impl Store {
|
|||
}
|
||||
|
||||
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
|
||||
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
|
||||
}
|
||||
|
||||
/// Same as `append_message`, returning the row id so an outbox row can
|
||||
/// point at the body instead of storing a second copy.
|
||||
pub fn append_message_id(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
dir: &str,
|
||||
plaintext: &[u8],
|
||||
) -> Result<i64> {
|
||||
if dir != "in" && dir != "out" {
|
||||
return Err(Error("dir must be in or out".into()));
|
||||
}
|
||||
|
|
@ -723,7 +834,7 @@ impl Store {
|
|||
params![blob, row_id],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
Ok(row_id)
|
||||
}
|
||||
|
||||
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
|
||||
|
|
@ -752,9 +863,194 @@ impl Store {
|
|||
Ok(out)
|
||||
}
|
||||
|
||||
/// Queue one already-stored chat message for retry. `next_attempt_at` is an
|
||||
/// absolute unix second; `now` is used for created_at/updated_at so the
|
||||
/// caller and the row agree on the clock.
|
||||
pub fn enqueue_outbox(
|
||||
&self,
|
||||
friend_pk: &[u8],
|
||||
message_id: i64,
|
||||
attempts: u32,
|
||||
next_attempt_at: i64,
|
||||
last_error: &str,
|
||||
now: i64,
|
||||
) -> Result<i64> {
|
||||
let friend_id: i64 = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT id FROM friends WHERE pubkey = ?1",
|
||||
params![friend_pk],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.map_err(|_| Error("friend not found".into()))?;
|
||||
self.conn.execute(
|
||||
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)",
|
||||
params![friend_id, message_id, attempts, next_attempt_at, last_error, now],
|
||||
)?;
|
||||
Ok(self.conn.last_insert_rowid())
|
||||
}
|
||||
|
||||
/// Rows whose backoff has elapsed: the timer trigger for the worker.
|
||||
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
|
||||
self.outbox_query(
|
||||
&format!(
|
||||
"{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1
|
||||
ORDER BY o.next_attempt_at, o.id LIMIT ?2"
|
||||
),
|
||||
params![now, limit],
|
||||
)
|
||||
}
|
||||
|
||||
/// Unscheduleable rows for one friend (queued or mid-attempt): the
|
||||
/// "we just heard from this peer" trigger, which ignores the backoff.
|
||||
pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
|
||||
self.outbox_query(
|
||||
&format!(
|
||||
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending')
|
||||
ORDER BY o.id"
|
||||
),
|
||||
params![friend_pk],
|
||||
)
|
||||
}
|
||||
|
||||
/// Every row the worker may still try: the unlock/foreground trigger.
|
||||
pub fn all_pending_outbox(&self, limit: i64) -> Result<Vec<OutboxEntry>> {
|
||||
self.outbox_query(
|
||||
&format!(
|
||||
"{OUTBOX_SELECT} WHERE o.status IN ('queued','sending')
|
||||
ORDER BY o.next_attempt_at, o.id LIMIT ?1"
|
||||
),
|
||||
params![limit],
|
||||
)
|
||||
}
|
||||
|
||||
/// Pending and failed rows for one friend — what a UI shows as not-yet-sent.
|
||||
/// Delivered rows are deleted, so absence means "sent".
|
||||
pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
|
||||
self.outbox_query(
|
||||
&format!(
|
||||
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed')
|
||||
ORDER BY o.id"
|
||||
),
|
||||
params![friend_pk],
|
||||
)
|
||||
}
|
||||
|
||||
pub fn outbox_status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>> {
|
||||
let row: Option<(String, Option<String>)> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1",
|
||||
params![message_id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref())))
|
||||
}
|
||||
|
||||
pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2",
|
||||
params![now, id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delivered. The row is dropped — the chat history is the record, and a
|
||||
/// per-message status table would grow without bound.
|
||||
pub fn mark_outbox_sent(&self, id: i64) -> Result<()> {
|
||||
self.conn
|
||||
.execute("DELETE FROM outbox WHERE id = ?1", params![id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3",
|
||||
params![why, now, id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mark_outbox_retry(
|
||||
&self,
|
||||
id: i64,
|
||||
attempts: u32,
|
||||
next_attempt_at: i64,
|
||||
now: i64,
|
||||
why: &str,
|
||||
) -> Result<()> {
|
||||
self.conn.execute(
|
||||
"UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5",
|
||||
params![attempts, next_attempt_at, why, now, id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A row left in 'sending' means we died mid-attempt. Requeue on unlock.
|
||||
pub fn reset_sending_outbox(&self) -> Result<usize> {
|
||||
let n = self.conn.execute(
|
||||
"UPDATE outbox SET status = 'queued' WHERE status = 'sending'",
|
||||
[],
|
||||
)?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
|
||||
let mut stmt = self.conn.prepare(sql)?;
|
||||
let rows = stmt.query_map(args, |row| {
|
||||
Ok((
|
||||
row.get::<_, i64>(0)?,
|
||||
row.get::<_, Vec<u8>>(1)?,
|
||||
row.get::<_, i64>(2)?,
|
||||
row.get::<_, i64>(3)?,
|
||||
row.get::<_, i64>(4)?,
|
||||
row.get::<_, String>(5)?,
|
||||
row.get::<_, Option<String>>(6)?,
|
||||
row.get::<_, i64>(7)?,
|
||||
row.get::<_, i64>(8)?,
|
||||
row.get::<_, String>(9)?,
|
||||
row.get::<_, Vec<u8>>(10)?,
|
||||
))
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (
|
||||
id,
|
||||
friend_pk,
|
||||
message_id,
|
||||
attempts,
|
||||
next_attempt_at,
|
||||
status,
|
||||
last_error,
|
||||
created_at,
|
||||
m_friend_id,
|
||||
dir,
|
||||
blob,
|
||||
) = row?;
|
||||
let aad = message_aad(m_friend_id, &dir, message_id);
|
||||
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
|
||||
.map_err(|_| Error("outbox body decrypt failed".into()))?;
|
||||
out.push(OutboxEntry {
|
||||
id,
|
||||
friend_pk,
|
||||
message_id,
|
||||
body,
|
||||
attempts: attempts as u32,
|
||||
next_attempt_at,
|
||||
created_at,
|
||||
status: OutboxStatus::from_db(&status, last_error.as_deref()),
|
||||
last_error,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Drop chat + payments history. Identity + friends stay.
|
||||
/// Not a forensic erase: SSD wear-leveling can keep copies.
|
||||
pub fn wipe_messages(&self) -> Result<()> {
|
||||
self.conn.execute("DELETE FROM outbox", [])?;
|
||||
self.conn.execute(
|
||||
"UPDATE messages SET plaintext = zeroblob(length(plaintext))",
|
||||
[],
|
||||
|
|
@ -809,10 +1105,194 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
|
|||
})
|
||||
}
|
||||
|
||||
fn gen_prekey() -> (Vec<u8>, Vec<u8>) {
|
||||
fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
|
||||
let sk = StaticSecret::random_from_rng(OsRng);
|
||||
let pk = X25519Public::from(&sk);
|
||||
(sk.to_bytes().to_vec(), pk.to_bytes().to_vec())
|
||||
(Zeroizing::new(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).as_str())?;
|
||||
// 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)
|
||||
}
|
||||
|
||||
/// SQLCipher's key material as hex inside the pragma text. The `String` holds
|
||||
/// the database key, so it wipes on drop.
|
||||
fn pragma_key(key: &[u8; 32]) -> Zeroizing<String> {
|
||||
Zeroizing::new(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('\'', "''");
|
||||
let attach = Zeroizing::new(format!(
|
||||
"ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";",
|
||||
hex = fingerprint(key)
|
||||
));
|
||||
conn.execute_batch(attach.as_str())?;
|
||||
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> {
|
||||
|
|
@ -823,29 +1303,29 @@ fn home_dir() -> Result<PathBuf> {
|
|||
Ok(PathBuf::from(home).join(".local/share/onionwire"))
|
||||
}
|
||||
|
||||
fn passphrase_from_env() -> Result<String> {
|
||||
fn passphrase_from_env() -> Result<Zeroizing<String>> {
|
||||
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
|
||||
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
|
||||
Ok(p) => Ok(p),
|
||||
Ok(p) => Ok(Zeroizing::new(p)),
|
||||
Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Env `ONIONWIRE_STORE_PASSPHRASE` if set (non-empty). Otherwise `read_secret`
|
||||
/// (TTY, no echo). Empty values fail closed.
|
||||
/// (TTY, no echo). Empty values fail closed. The passphrase is wiped on drop.
|
||||
pub fn resolve_store_passphrase(
|
||||
read_secret: impl FnOnce(&str) -> std::io::Result<String>,
|
||||
) -> Result<String> {
|
||||
) -> Result<Zeroizing<String>> {
|
||||
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
|
||||
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
|
||||
Ok(p) => Ok(p),
|
||||
Ok(p) => Ok(Zeroizing::new(p)),
|
||||
Err(_) => {
|
||||
let s = read_secret("onionwire: store passphrase: ")?;
|
||||
let s = s.trim_end_matches(['\n', '\r']).to_string();
|
||||
if s.is_empty() {
|
||||
Err(Error("empty passphrase".into()))
|
||||
} else {
|
||||
Ok(s)
|
||||
Ok(Zeroizing::new(s))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -859,6 +1339,12 @@ fn mkdir_700(path: &Path) -> Result<()> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Base projection for outbox rows: the body comes from the `messages` row the
|
||||
/// outbox row points at, so it stays under that row's AEAD + AAD.
|
||||
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
|
||||
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \
|
||||
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
|
||||
|
||||
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
|
||||
fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec<u8> {
|
||||
let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8);
|
||||
|
|
@ -884,6 +1370,21 @@ fn fingerprint(pubkey: &[u8]) -> String {
|
|||
#[cfg(test)]
|
||||
mod at_rest {
|
||||
use super::*;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
#[test]
|
||||
fn store_data_key_is_a_zeroizing_wrapper_that_wipes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").unwrap();
|
||||
|
||||
// Type-level: the field is `Zeroizing<[u8; 32]>`, so its Drop wipes it.
|
||||
let _: &Zeroizing<[u8; 32]> = &store.msg_key;
|
||||
let before = *store.msg_key;
|
||||
assert_ne!(before, [0u8; 32], "store has no data key");
|
||||
|
||||
store.msg_key.zeroize();
|
||||
assert_eq!(*store.msg_key, [0u8; 32], "store data key not wiped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapped_ciphertext_does_not_show_other_friends_body() {
|
||||
|
|
@ -1027,6 +1528,214 @@ 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 = Zeroizing::new([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();
|
||||
|
|
|
|||
|
|
@ -1449,8 +1449,10 @@ impl App {
|
|||
let (tx, rx) = mpsc::channel();
|
||||
self.status_note = Some("sending".into());
|
||||
std::mem::drop(self.rt.spawn(async move {
|
||||
// send() now reports `Sent`/`Queued`; surfacing `queued` in the
|
||||
// footer is a follow-up card, so this arm keeps today's wording.
|
||||
let note = match node.send(&pk, &body).await {
|
||||
Ok(()) => "sent".to_string(),
|
||||
Ok(_) => "sent".to_string(),
|
||||
Err(e) => format!("send failed: {e}"),
|
||||
};
|
||||
let _ = tx.send(note);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ use std::time::Duration;
|
|||
use rand::RngCore;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
|
|
@ -23,7 +24,7 @@ struct Endpoint {
|
|||
port: u16,
|
||||
path: String,
|
||||
user: String,
|
||||
pass: String,
|
||||
pass: Zeroizing<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Endpoint {
|
||||
|
|
@ -59,12 +60,15 @@ impl Wallet {
|
|||
|
||||
pub fn from_env() -> Self {
|
||||
match std::env::var("ONIONWIRE_WALLET_RPC") {
|
||||
// The URL can carry `user:pass@` in its userinfo: keep it in a
|
||||
// wiping buffer, not a bare `String`.
|
||||
Ok(s) if !s.trim().is_empty() => {
|
||||
let url = Zeroizing::new(s);
|
||||
let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN")
|
||||
.ok()
|
||||
.map(|v| v.trim().to_string())
|
||||
.map(|v| Zeroizing::new(v.trim().to_string()))
|
||||
.filter(|v| !v.is_empty());
|
||||
match parse_http_url(s.trim(), login.as_deref()) {
|
||||
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
||||
Ok(endpoint) => Self {
|
||||
endpoint: Some(endpoint),
|
||||
},
|
||||
|
|
@ -185,12 +189,12 @@ fn credentials_required() -> Error {
|
|||
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
|
||||
}
|
||||
|
||||
fn parse_login(login: &str) -> Result<(String, String)> {
|
||||
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
|
||||
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
|
||||
if user.is_empty() || pass.is_empty() {
|
||||
return Err(credentials_required());
|
||||
}
|
||||
Ok((user.to_string(), pass.to_string()))
|
||||
Ok((user.to_string(), Zeroizing::new(pass.to_string())))
|
||||
}
|
||||
|
||||
fn parse_http_url(url: &str, extra_login: Option<&str>) -> Result<Endpoint> {
|
||||
|
|
@ -405,7 +409,9 @@ fn digest_authorization(ep: &Endpoint, challenge: &str) -> Result<String> {
|
|||
let nonce = digest_param(challenge, "nonce")
|
||||
.ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?;
|
||||
let qop = digest_param(challenge, "qop");
|
||||
let ha1 = md5_hex(&format!("{}:{realm}:{}", ep.user, ep.pass));
|
||||
// `user:realm:password` never leaves a bare `String` behind.
|
||||
let pw_input = Zeroizing::new(format!("{}:{realm}:{}", ep.user, ep.pass.as_str()));
|
||||
let ha1 = md5_hex(pw_input.as_str());
|
||||
let ha2 = md5_hex(&format!("POST:{}", ep.path));
|
||||
let (qop_part, resp) = if qop
|
||||
.as_deref()
|
||||
|
|
|
|||
|
|
@ -72,9 +72,9 @@ fn restore_overwrites_self_keys_friends_stay() {
|
|||
)
|
||||
.unwrap();
|
||||
let me = store.self_identity().unwrap();
|
||||
assert_eq!(me.identity_sk, incoming.identity_sk);
|
||||
assert_eq!(me.identity_sk[..], incoming.identity_sk[..]);
|
||||
assert_eq!(me.identity_pk, incoming.identity_pk);
|
||||
assert_eq!(me.prekey_sk, incoming.prekey_sk);
|
||||
assert_eq!(me.prekey_sk[..], incoming.prekey_sk[..]);
|
||||
assert_eq!(me.prekey_pk, incoming.prekey_pk);
|
||||
assert_eq!(me.onion, old.onion, "onion is locator, not restored");
|
||||
assert_eq!(store.friend_count().unwrap(), 1);
|
||||
|
|
|
|||
95
tests/hs.rs
95
tests/hs.rs
|
|
@ -69,6 +69,101 @@ fn broken_or_shutdown_never_ready() {
|
|||
assert!(!hs::hs_is_ready(State::Shutdown, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_state_maps_every_arti_status() {
|
||||
// The four states the Android UI branches on, derived from the same status
|
||||
// union `hs_is_ready` reads.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Running, false, false),
|
||||
hs::TorState::Published
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::DegradedReachable, false, false),
|
||||
hs::TorState::DegradedReachable
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Bootstrapping, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::DegradedUnreachable, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
// A freshly launched service reports Shutdown before its publish reactor
|
||||
// starts. Mapping that to Stopped would make a live node look dead for the
|
||||
// first seconds after unlock — caught on a real Tor network.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Shutdown, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
// Arti reads `Broken` while the HsDir retry loop is still going; a dead
|
||||
// service surfaces as an error from `wait_until_published`, not as a state
|
||||
// the UI has to poll for.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Broken, false, false),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reachable_statuses_report_published_while_arti_says_bootstrapping() {
|
||||
// `wait_until_published` returns on a successful probe while Arti's
|
||||
// combined status is still Bootstrapping (see `hs_is_ready`). Reporting
|
||||
// Bootstrapping there would keep the UI saying "starting" for minutes after
|
||||
// friends can actually reach us.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Bootstrapping, false, true),
|
||||
hs::TorState::Published
|
||||
);
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::DegradedUnreachable, false, true),
|
||||
hs::TorState::Published
|
||||
);
|
||||
// Broken stays Broken, reachable or not: `hs_is_ready` refuses it too.
|
||||
assert_eq!(
|
||||
hs::tor_state_of(State::Broken, false, true),
|
||||
hs::TorState::Bootstrapping
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopped_outranks_whatever_arti_reports() {
|
||||
// A node that has been told to stop is Stopped even if Arti's status cache
|
||||
// still says Running, and even if it was reachable a moment ago: the flag
|
||||
// is set before the service is dropped.
|
||||
for state in [
|
||||
State::Running,
|
||||
State::DegradedReachable,
|
||||
State::DegradedUnreachable,
|
||||
State::Bootstrapping,
|
||||
State::Broken,
|
||||
State::Shutdown,
|
||||
] {
|
||||
for reachable in [false, true] {
|
||||
assert_eq!(
|
||||
hs::tor_state_of(state, true, reachable),
|
||||
hs::TorState::Stopped,
|
||||
"wrong state for {state:?} (reachable={reachable}) on a stopped node"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ready_states_are_the_published_ones() {
|
||||
// Published/degraded must not drift from the readiness bar: anything
|
||||
// `hs_is_ready` accepts without a probe is a state the UI calls up.
|
||||
let ready = [State::Running, State::DegradedReachable];
|
||||
for state in ready {
|
||||
assert!(hs::hs_is_ready(state, false), "{state:?} must be ready");
|
||||
assert_ne!(
|
||||
hs::tor_state_of(state, false, false),
|
||||
hs::TorState::Bootstrapping,
|
||||
"{state:?} is ready but reported as still coming up"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hs_log_label_is_not_the_full_v3_onion() {
|
||||
// Public v3 address; checksum is valid so HsId::from_str works.
|
||||
|
|
|
|||
312
tests/outbox.rs
Normal file
312
tests/outbox.rs
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
//! Local outbox: queue a chat send when the peer's onion is unreachable, retry
|
||||
//! with exponential backoff, expose a terminal status. All offline — the
|
||||
//! transport is a fake deliverer, so these run without Tor.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use onionwire::outbox::{
|
||||
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
|
||||
is_permanent_send_error,
|
||||
};
|
||||
use onionwire::Store;
|
||||
|
||||
const PASS: &str = "outbox-pass";
|
||||
|
||||
fn pk(tag: u8) -> [u8; 32] {
|
||||
let mut k = [0u8; 32];
|
||||
k[0] = tag;
|
||||
k
|
||||
}
|
||||
|
||||
/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext.
|
||||
struct Flaky {
|
||||
fail_times: AtomicUsize,
|
||||
err: String,
|
||||
calls: AtomicUsize,
|
||||
delivered: Mutex<Vec<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Flaky {
|
||||
fn new(fail_times: usize, err: &str) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
fail_times: AtomicUsize::new(fail_times),
|
||||
err: err.into(),
|
||||
calls: AtomicUsize::new(0),
|
||||
delivered: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
fn calls(&self) -> usize {
|
||||
self.calls.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn delivered(&self) -> Vec<Vec<u8>> {
|
||||
self.delivered.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Deliverer for Flaky {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
_onion: &'a str,
|
||||
_pinned_id: &'a [u8],
|
||||
_prekey: &'a [u8],
|
||||
plaintext: &'a [u8],
|
||||
) -> BoxFut<'a, Result<(), String>> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let left = self.fail_times.load(Ordering::SeqCst);
|
||||
if left > 0 {
|
||||
self.fail_times.fetch_sub(1, Ordering::SeqCst);
|
||||
let err = self.err.clone();
|
||||
return Box::pin(async move { Err(err) });
|
||||
}
|
||||
self.delivered.lock().unwrap().push(plaintext.to_vec());
|
||||
Box::pin(async move { Ok(()) })
|
||||
}
|
||||
}
|
||||
|
||||
fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc<Mutex<Store>> {
|
||||
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
|
||||
store.upsert_friend(&pk(1), onion, None).unwrap();
|
||||
store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap();
|
||||
Arc::new(Mutex::new(store))
|
||||
}
|
||||
|
||||
fn outbox(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>, max_attempts: u32) -> Outbox {
|
||||
Outbox::new(store, deliverer).with_max_attempts(max_attempts)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
|
||||
assert_eq!(BACKOFF_START_SECS, 30);
|
||||
assert_eq!(BACKOFF_CAP_SECS, 1800);
|
||||
let got: Vec<i64> = (0..9).map(backoff_secs).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800],
|
||||
"exponential backoff, capped"
|
||||
);
|
||||
assert_eq!(
|
||||
backoff_secs(u32::MAX),
|
||||
BACKOFF_CAP_SECS,
|
||||
"no overflow at silly attempt counts"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transport_errors_are_retryable_protocol_errors_are_not() {
|
||||
assert!(!is_permanent_send_error(
|
||||
"connect abc.onion:80: timed out"
|
||||
));
|
||||
assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
|
||||
assert!(is_permanent_send_error("fingerprint mismatch"));
|
||||
assert!(is_permanent_send_error("frame too large"));
|
||||
assert!(is_permanent_send_error("bad version"));
|
||||
assert!(is_permanent_send_error("bad identity proof"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_to_dead_onion_is_queued_and_row_persists() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "dead.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
|
||||
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap();
|
||||
assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err");
|
||||
assert!(!status.is_terminal());
|
||||
|
||||
let pending = ob.pending(&pk(1)).unwrap();
|
||||
assert_eq!(pending.len(), 1, "one outbox row");
|
||||
assert_eq!(pending[0].status, OutboxStatus::Queued);
|
||||
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
|
||||
assert!(
|
||||
ob.status_of_message(pending[0].message_id).unwrap().is_some(),
|
||||
"status is addressable by chat row id"
|
||||
);
|
||||
|
||||
// The chat line is already in local history while it waits.
|
||||
let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap();
|
||||
assert_eq!(msgs.len(), 1);
|
||||
assert_eq!(msgs[0].dir, "out");
|
||||
assert_eq!(msgs[0].plaintext, b"hello dead peer");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flaky_peer_is_flushed_by_the_worker_on_schedule() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "flaky.onion");
|
||||
// First dial fails (the immediate one), the rest succeed: "peer came up".
|
||||
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||
|
||||
let status = ob.send(&pk(1), b"late hello").await.unwrap();
|
||||
assert_eq!(status, OutboxStatus::Queued);
|
||||
let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
||||
assert_eq!(
|
||||
next - ob.pending(&pk(1)).unwrap()[0].created_at,
|
||||
BACKOFF_START_SECS,
|
||||
"first retry waits the start of the schedule"
|
||||
);
|
||||
|
||||
// Too early: the worker must not dial out of schedule.
|
||||
let t0 = next - BACKOFF_START_SECS;
|
||||
let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap();
|
||||
assert!(fired.is_empty(), "not due yet");
|
||||
|
||||
let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap();
|
||||
assert_eq!(fired.len(), 1);
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]);
|
||||
assert!(
|
||||
ob.pending(&pk(1)).unwrap().is_empty(),
|
||||
"delivered rows leave the pending set"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn max_attempts_reaches_failed_and_stops_retrying() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "gone.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead.clone(), 3);
|
||||
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"never lands").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
assert_eq!(dead.calls(), 1, "immediate attempt");
|
||||
|
||||
// Walk the schedule forward; each tick is one more attempt.
|
||||
let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
||||
let mut last = OutboxStatus::Queued;
|
||||
for _ in 0..6 {
|
||||
let fired = ob.tick(now).await.unwrap();
|
||||
if let Some((_, st)) = fired.first() {
|
||||
last = st.clone();
|
||||
}
|
||||
if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) {
|
||||
break;
|
||||
}
|
||||
now += BACKOFF_CAP_SECS;
|
||||
}
|
||||
assert_eq!(
|
||||
last,
|
||||
OutboxStatus::Failed("connect gone.onion:80: timed out".into()),
|
||||
"gives up after max_attempts"
|
||||
);
|
||||
assert_eq!(dead.calls(), 3, "attempts stop at the cap");
|
||||
|
||||
let calls_at_cap = dead.calls();
|
||||
for _ in 0..3 {
|
||||
now += BACKOFF_CAP_SECS;
|
||||
assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries");
|
||||
}
|
||||
assert_eq!(dead.calls(), calls_at_cap);
|
||||
|
||||
let pending = ob.pending(&pk(1)).unwrap();
|
||||
assert_eq!(pending.len(), 1);
|
||||
assert!(matches!(pending[0].status, OutboxStatus::Failed(_)));
|
||||
assert!(pending[0].status.is_terminal());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_message_survives_reopen_and_flushes_after_unlock() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pk1 = pk(1);
|
||||
let next_attempt_at = {
|
||||
let store = store_and_friend(dir.path(), "later.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
assert_eq!(
|
||||
ob.send(&pk1, b"survives restart").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
ob.pending(&pk1).unwrap()[0].next_attempt_at
|
||||
};
|
||||
|
||||
// Process exit: everything above is dropped and the store is reopened.
|
||||
let store = Arc::new(Mutex::new(
|
||||
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
|
||||
));
|
||||
let up = Flaky::new(0, "");
|
||||
let ob = outbox(Arc::clone(&store), up.clone(), 8);
|
||||
let fired = ob.flush_all(next_attempt_at).await.unwrap();
|
||||
assert_eq!(fired.len(), 1);
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]);
|
||||
assert!(ob.pending(&pk1).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn protocol_error_fails_immediately_and_is_not_queued() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "liar.onion");
|
||||
let liar = Flaky::new(usize::MAX, "fingerprint mismatch");
|
||||
let ob = outbox(Arc::clone(&store), liar, 8);
|
||||
|
||||
let err = ob.send(&pk(1), b"hello liar").await.unwrap_err();
|
||||
assert!(err.contains("fingerprint mismatch"), "got {err}");
|
||||
assert!(
|
||||
ob.pending(&pk(1)).unwrap().is_empty(),
|
||||
"protocol errors are never queued"
|
||||
);
|
||||
assert!(
|
||||
store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(),
|
||||
"a failed protocol send is not written to history"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "seen.onion");
|
||||
let flaky = Flaky::new(1, "connect seen.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"you are back").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
let now = ob.pending(&pk(1)).unwrap()[0].created_at;
|
||||
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
|
||||
assert_eq!(fired.len(), 1, "a live handshake flushes without waiting");
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wipe_clears_outbox_rows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "dead.onion");
|
||||
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), dead, 8);
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"wipe me").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1);
|
||||
|
||||
store.lock().unwrap().wipe_messages().unwrap();
|
||||
|
||||
assert!(
|
||||
ob.pending(&pk(1)).unwrap().is_empty(),
|
||||
"wipe must drop queued sends, not only chat"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_prekey_is_fatal_not_queued() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Arc::new(Mutex::new(
|
||||
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
|
||||
));
|
||||
{
|
||||
let s = store.lock().unwrap();
|
||||
s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap();
|
||||
}
|
||||
let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8);
|
||||
let err = ob.send(&pk(2), b"hi").await.unwrap_err();
|
||||
assert!(err.contains("prekey"), "got {err}");
|
||||
assert!(ob.pending(&pk(2)).unwrap().is_empty());
|
||||
}
|
||||
123
tests/store.rs
123
tests/store.rs
|
|
@ -67,7 +67,7 @@ fn first_run_creates_0700_dirs_and_self_row() {
|
|||
let me = store.self_identity().expect("self");
|
||||
assert_eq!(me.identity_pk.len(), 32);
|
||||
assert_eq!(me.identity_sk.len(), 32);
|
||||
assert_ne!(me.identity_pk, me.identity_sk);
|
||||
assert_ne!(me.identity_pk, me.identity_sk.to_vec());
|
||||
assert_eq!(me.onion, "");
|
||||
assert_eq!(store.friend_count().unwrap(), 0);
|
||||
|
||||
|
|
@ -152,7 +152,7 @@ fn self_has_x25519_prekey_and_set_onion() {
|
|||
let me = store.self_identity().unwrap();
|
||||
assert_eq!(me.prekey_pk.len(), 32);
|
||||
assert_eq!(me.prekey_sk.len(), 32);
|
||||
assert_ne!(me.prekey_pk, me.prekey_sk);
|
||||
assert_ne!(me.prekey_pk, me.prekey_sk.to_vec());
|
||||
store.set_onion("abc.onion").unwrap();
|
||||
assert_eq!(store.self_identity().unwrap().onion, "abc.onion");
|
||||
}
|
||||
|
|
@ -233,6 +233,121 @@ fn append_message_db_file_does_not_contain_plaintext() {
|
|||
);
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn db_files(home: &Path) -> Vec<(String, Vec<u8>)> {
|
||||
let mut out = Vec::new();
|
||||
for ent in fs::read_dir(home).expect("read_dir").flatten() {
|
||||
let name = ent.file_name().to_string_lossy().to_string();
|
||||
if !name.starts_with("onionwire.db") {
|
||||
continue;
|
||||
}
|
||||
out.push((name, fs::read(ent.path()).expect("read db file")));
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn store_contains(home: &Path, needle: &[u8]) -> bool {
|
||||
db_files(home)
|
||||
.iter()
|
||||
.any(|(_, bytes)| bytes.windows(needle.len()).any(|w| w == needle))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_store_file_is_encrypted_at_rest() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open");
|
||||
let me = store.self_identity().unwrap();
|
||||
store
|
||||
.upsert_friend(&pk(7), "friend.onion", Some("alice"))
|
||||
.unwrap();
|
||||
store
|
||||
.append_message(&pk(7), "out", b"body-at-rest-xyz")
|
||||
.unwrap();
|
||||
store
|
||||
.append_message(&pk(7), "in", b"reply-at-rest-xyz")
|
||||
.unwrap();
|
||||
drop(store);
|
||||
|
||||
for (needle, what) in [
|
||||
(b"body-at-rest-xyz".to_vec(), "chat body"),
|
||||
(b"reply-at-rest-xyz".to_vec(), "inbound chat body"),
|
||||
(hex(&pk(7)).into_bytes(), "friend pubkey hex"),
|
||||
(b"friend.onion".to_vec(), "friend locator"),
|
||||
(me.identity_sk.to_vec(), "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");
|
||||
|
|
@ -279,7 +394,7 @@ fn env_passphrase_skips_prompt() {
|
|||
unsafe {
|
||||
std::env::remove_var("ONIONWIRE_STORE_PASSPHRASE");
|
||||
}
|
||||
assert_eq!(got.unwrap(), "from-env");
|
||||
assert_eq!(got.unwrap().as_str(), "from-env");
|
||||
assert!(!prompted);
|
||||
}
|
||||
|
||||
|
|
@ -313,7 +428,7 @@ fn missing_env_reads_secret_and_strips_newline() {
|
|||
Ok("secret-from-tty\n".into())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(got, "secret-from-tty");
|
||||
assert_eq!(got.as_str(), "secret-from-tty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
96
tests/tor_lifecycle.rs
Normal file
96
tests/tor_lifecycle.rs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
//! Lifecycle: a node stops when told to, says so, and refuses further work
|
||||
//! with an error instead of panicking.
|
||||
//!
|
||||
//! Needs a live Tor network to publish the onion service, so `cargo test` skips
|
||||
//! it. Run it on a networked machine with:
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo test --test tor_lifecycle -- --ignored --nocapture
|
||||
//! ```
|
||||
//!
|
||||
//! The offline half of this contract — the Arti-status projection, the WAL
|
||||
//! checkpoint, and the SDK's typed error after shutdown — runs in the normal
|
||||
//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`).
|
||||
|
||||
use onionwire::node::{FlushOutcome, Node};
|
||||
use onionwire::hs::TorState;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "needs live Tor network"]
|
||||
async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() {
|
||||
let _ = tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
|
||||
)
|
||||
.with_test_writer()
|
||||
.try_init();
|
||||
|
||||
let root = tempfile::tempdir().expect("tempdir");
|
||||
let home = root.path().join("alice");
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_STORE_PASSPHRASE", "onionwire-test");
|
||||
}
|
||||
|
||||
let node = Node::start(home.clone()).await.expect("start");
|
||||
|
||||
// `start` returns only after `wait_until_published`, so the node is
|
||||
// reachable by the time a caller can call this — which must not read as
|
||||
// `Stopped` or `Bootstrapping`. `DegradedReachable` is the honest answer
|
||||
// when Arti says the service is degraded.
|
||||
//
|
||||
// This caught a real bug: `tor_state()` originally projected Arti's raw
|
||||
// combined status, which is still `Bootstrapping` after a *successful*
|
||||
// probe (that mismatch is what the 360s publish wait exists for), and which
|
||||
// reads `Shutdown` on a service that has not started its reactor yet — so a
|
||||
// live node reported `Stopped`. See `onion_reachable` in `src/node.rs`.
|
||||
let started_state = node.tor_state();
|
||||
assert!(
|
||||
matches!(
|
||||
started_state,
|
||||
TorState::Published | TorState::DegradedReachable
|
||||
),
|
||||
"start returned Ok but tor_state() is {started_state:?}"
|
||||
);
|
||||
|
||||
// A flush with nothing queued is a no-op that reports it, not an error.
|
||||
let drained: FlushOutcome = node.flush().await.expect("flush on a live node");
|
||||
assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}");
|
||||
|
||||
node.shutdown().await.expect("shutdown");
|
||||
|
||||
assert_eq!(
|
||||
node.tor_state(),
|
||||
TorState::Stopped,
|
||||
"tor_state must report Stopped after shutdown"
|
||||
);
|
||||
|
||||
// Second shutdown: idempotent at the node level — no panic, no repeat work.
|
||||
node.shutdown().await.expect("shutdown is idempotent");
|
||||
|
||||
let err = node
|
||||
.flush()
|
||||
.await
|
||||
.expect_err("flush after shutdown must be an error");
|
||||
assert!(err.contains("stopped"), "flush error was {err:?}");
|
||||
|
||||
let err = node
|
||||
.send(&[0u8; 32], b"after shutdown")
|
||||
.await
|
||||
.expect_err("send after shutdown must be an error");
|
||||
assert!(err.contains("stopped"), "send error was {err:?}");
|
||||
|
||||
// `RotateResult` is not `Debug`, so match on the error instead of
|
||||
// `expect_err`.
|
||||
let err = node
|
||||
.rotate()
|
||||
.await
|
||||
.err()
|
||||
.expect("rotate after shutdown must be an error");
|
||||
assert!(err.contains("stopped"), "rotate error was {err:?}");
|
||||
|
||||
// The store file survives the checkpoint: stopping is not wiping.
|
||||
assert!(
|
||||
home.join("onionwire.db").exists(),
|
||||
"shutdown must not delete the store"
|
||||
);
|
||||
}
|
||||
118
tests/zeroize.rs
Normal file
118
tests/zeroize.rs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
//! Wipe in-memory secrets on drop — keys, not just the file at rest.
|
||||
//!
|
||||
//! Not covered here (see the PR body): allocator copies, swap/hibernation,
|
||||
//! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the
|
||||
//! Noise handshake/transport state that lives inside `snow`.
|
||||
|
||||
use onionwire::backup::BackupKeys;
|
||||
use onionwire::session::Keys;
|
||||
use onionwire::wallet::Wallet;
|
||||
use onionwire::Store;
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
|
||||
|
||||
/// Type-level: the wrapper is applied to the type, not just mentioned in a
|
||||
/// comment. Removing the derive breaks the build here.
|
||||
fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
|
||||
|
||||
#[test]
|
||||
fn session_and_backup_key_types_are_zeroize_on_drop() {
|
||||
assert_zeroize_on_drop::<Keys>();
|
||||
assert_zeroize_on_drop::<BackupKeys>();
|
||||
}
|
||||
|
||||
/// Behavioural: the derived impl must wipe the secret halves and leave the
|
||||
/// public halves alone. A `Zeroize` that only touched the publics would still
|
||||
/// satisfy a bare drop assertion and leak anyway.
|
||||
#[test]
|
||||
fn session_keys_zeroize_wipes_secrets_and_keeps_publics() {
|
||||
let mut k = Keys::generate();
|
||||
let (id_pk, prekey_pk) = (k.identity_pk, k.prekey_pk);
|
||||
assert_ne!(k.identity_sk, [0u8; 32]);
|
||||
assert_ne!(k.prekey_sk, [0u8; 32]);
|
||||
|
||||
k.zeroize();
|
||||
|
||||
assert_eq!(k.identity_sk, [0u8; 32], "identity secret not wiped");
|
||||
assert_eq!(k.prekey_sk, [0u8; 32], "prekey secret not wiped");
|
||||
assert_eq!(k.identity_pk, id_pk, "identity public key was wiped");
|
||||
assert_eq!(k.prekey_pk, prekey_pk, "prekey public key was wiped");
|
||||
}
|
||||
|
||||
/// Drops `v` in place and reads its secret field back, so a drop test cannot
|
||||
/// pass on a copy that the caller still holds.
|
||||
///
|
||||
/// SAFETY: only for `ManuallyDrop<Keys>` locals — the value is dropped exactly
|
||||
/// once, at its own address, and its storage is still alive when it is read.
|
||||
unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
|
||||
let p = std::ptr::addr_of!(v.identity_sk);
|
||||
// SAFETY: the caller guarantees `v` is a `ManuallyDrop<Keys>` dropped once.
|
||||
unsafe {
|
||||
std::ptr::drop_in_place(v as *mut Keys);
|
||||
std::ptr::read_volatile(p)
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop behaviour, not a comment: after the value drops, the local secret key
|
||||
/// material that feeds the Noise IK handshake is gone from its memory.
|
||||
#[test]
|
||||
fn dropped_session_keys_leave_no_secret_behind() {
|
||||
let mut k = std::mem::ManuallyDrop::new(Keys::generate());
|
||||
// SAFETY: `k` is a live local; the pointer targets its own field.
|
||||
assert_ne!(unsafe { *std::ptr::addr_of!(k.identity_sk) }, [0u8; 32]);
|
||||
|
||||
let after = unsafe { drop_in_place_and_peek_identity_sk(&mut k) };
|
||||
|
||||
assert_eq!(after, [0u8; 32], "identity secret survived drop");
|
||||
}
|
||||
|
||||
/// `Keys` is `Clone`, so a cloned copy is itself live secret material. It must
|
||||
/// wipe on *its* drop, and dropping it must not wipe the original it came from.
|
||||
#[test]
|
||||
fn cloned_session_keys_wipe_their_own_copy_only() {
|
||||
let original = std::mem::ManuallyDrop::new(Keys::generate());
|
||||
let mut copy = std::mem::ManuallyDrop::new((*original).clone());
|
||||
|
||||
let after = unsafe { drop_in_place_and_peek_identity_sk(&mut copy) };
|
||||
assert_eq!(after, [0u8; 32], "cloned secret survived its drop");
|
||||
|
||||
// SAFETY: `original` is a live local; the pointer targets its own field.
|
||||
assert_ne!(
|
||||
unsafe { *std::ptr::addr_of!(original.identity_sk) },
|
||||
[0u8; 32],
|
||||
"dropping the clone wiped the original's key"
|
||||
);
|
||||
}
|
||||
|
||||
/// The identity secret handed out by the store is a `Zeroizing`, not a bare
|
||||
/// `Vec<u8>` that outlives every caller.
|
||||
#[test]
|
||||
fn self_identity_secrets_are_zeroizing_and_wipe() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").expect("open");
|
||||
let mut me = store.self_identity().expect("self");
|
||||
|
||||
let _: &Zeroizing<Vec<u8>> = &me.identity_sk;
|
||||
let _: &Zeroizing<Vec<u8>> = &me.prekey_sk;
|
||||
|
||||
assert_eq!(me.identity_sk.len(), 32);
|
||||
assert!(me.identity_sk.iter().any(|b| *b != 0));
|
||||
|
||||
me.identity_sk.zeroize();
|
||||
me.prekey_sk.zeroize();
|
||||
|
||||
assert!(me.identity_sk.iter().all(|b| *b == 0));
|
||||
assert!(me.prekey_sk.iter().all(|b| *b == 0));
|
||||
}
|
||||
|
||||
/// The wallet RPC password is a secret, so it is `Zeroizing` and its `Debug`
|
||||
/// redacts it instead of printing it.
|
||||
#[test]
|
||||
fn wallet_endpoint_debug_redacts_the_rpc_password() {
|
||||
let w = Wallet::from_url("http://monero:[email protected]:18083/json_rpc").expect("url");
|
||||
let dbg = format!("{w:?}");
|
||||
assert!(
|
||||
!dbg.contains("hunter2"),
|
||||
"wallet RPC password leaked into Debug: {dbg}"
|
||||
);
|
||||
assert!(dbg.contains("<redacted>"), "{dbg}");
|
||||
}
|
||||
Loading…
Reference in a new issue