Compare commits

..
Author SHA1 Message Date
rust-dev
2cbe7d41e5
feat(tui): join outbox rows to chat rows by message id
All checks were successful
ci / test (pull_request) Successful in 4m12s
`chat_with_delivery` matched pending outbox rows to chat rows by body
because `store::Message` carried no id, so an older send that was still
queued showed a delivered mark whenever a newer send of the same text had
already crossed the circuit.

`store::Message` now carries its `messages.id`, and the TUI joins
`OutboxEntry::message_id` == `Message::id`. The body match and its
newest-first fallback are gone.

`list_messages()` keeps its signature; callers that do not need the id
are untouched.
2026-09-12 17:12:30 -04:00
02b531625f Merge pull request 'feat(sdk): explicit Tor lifecycle — Wire.shutdown / flush / torState + observable state' (#49) from feat/tor-lifecycle into main
All checks were successful
ci / test (push) Successful in 4m17s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m55s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 11s
Reviewed-on: #49
2026-09-12 20:58:31 +00:00
cecad2b364 Merge pull request 'feat(tui): per-message outbox delivery state (queued/sending/sent/failed) + N queued footer' (#48) from feat/tui-outbox-state into main
All checks were successful
release / x86_64 (push) Successful in 1m52s
release / aarch64 (push) Successful in 2m25s
release / publish (push) Successful in 12s
ci / test (push) Successful in 6m1s
release / version (push) Successful in 2s
Reviewed-on: #48
2026-09-12 20:32:39 +00:00
a50df7ee43 Merge pull request 'feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer' (#47) from feat/zeroize-tui-profile into main
Some checks failed
release / version (push) Waiting to run
release / aarch64 (push) Blocked by required conditions
release / x86_64 (push) Blocked by required conditions
release / publish (push) Blocked by required conditions
ci / test (push) Has been cancelled
Reviewed-on: #47
2026-09-12 20:31:46 +00:00
beb523bdde Merge pull request 'wallet: no-spend (view-only) mode + RPC view-only detection + docs/WALLET.md' (#41) from feat/wallet-no-spend-view-only into main
All checks were successful
ci / test (push) Successful in 4m2s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 1m51s
release / aarch64 (push) Successful in 2m28s
release / publish (push) Successful in 10s
Reviewed-on: #41
2026-09-12 20:08:08 +00:00
t
e3be8ffdd0
feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer
All checks were successful
ci / test (pull_request) Successful in 4m14s
The Ed25519 identity secret was still copied into a bare [u8; 32] on the
stack in two signers (profile::sign, loc::sign), and the TUI kept the
typed backup/restore passphrase in a plain String for the life of the
screen. Both now go through Zeroizing:

- profile::signing_key_bytes() builds the 32-byte copy into a
  Zeroizing<[u8; 32]> (same pattern as pay::sign_bytes / qr::encode,
  but with copy_from_slice so no Copy temporary is left behind);
  loc::sign shares the helper instead of making its own copy.
- Screen::Passphrase now owns a PassphraseEntry whose buffers are
  Zeroizing<String>. Every exit path (Enter, mismatch, Esc) calls
  close(), which wipes both buffers eagerly; a drop — including Ctrl-Q
  and a panic — is the backstop.

Evidence: tests/zeroize.rs gains a drop probe (ManuallyDrop +
drop_in_place + read_volatile) on the Zeroizing signing buffer and a
length-rejection test; src/tui.rs gains unit tests asserting the buffer
types and that close() leaves every byte of the passphrase's heap
capacity zeroed.
2026-09-12 15:41:54 -04:00
Sirius DevOps
323100b162
wallet: no-spend mode + view-only detection over RPC
All checks were successful
ci / test (pull_request) Successful in 4m11s
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do.
With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer`
refuses locally, before any RPC dial, and /pay + receipt verification are
unchanged.

When a transfer does fail, ask the documented signal before surfacing the raw
wallet error: `query_key` key_type=spend_key answers
WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet
(wallet_rpc_server.cpp on_query_key). Both paths return one sentence —
"wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt
verification still work". Fail closed: if the probe cannot answer, the wallet's
own error stands; no fabricated detection.

New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only
setup, --rpc-login Digest, why loopback still needs auth, the local
spend-authority warning, and the detection trade-off (a spend-capable wallet
answers the probe with its spend key, which is discarded). Linked from
docs/THREAT_MODEL.md.
2026-09-12 15:41:33 -04:00
agent
48c06df2cf
docs(sdk): Wire::shutdown doc said the second call returns Ok; it returns Stopped
All checks were successful
ci / test (pull_request) Successful in 4m22s
The handle-level call takes the node out on the first shutdown, so a second
call reports the typed `WireError::Stopped` (covered by
`calls_after_shutdown_are_typed_errors_not_panics`). Only the node-level
`Node::shutdown()` is Ok-idempotent. The rustdoc claimed otherwise.
2026-09-12 15:26:17 -04:00
apk-dev
c068e292a0
feat(android): stop the node when the UI goes away
`WireViewModel.lock()` set `wire = null` and `onCleared()` did not exist at all,
so neither the user pressing Lock nor the Activity finishing stopped anything:
Arti kept its client and the hosted onion service, the outbox worker kept
dialing, and the sqlite connection stayed open behind the JNI handle.

Both paths now go through `stopNode(Wire)`:

1. `flush()` — one last bounded drain, so a queued message gets its chance
   before the process may lose its socket.
2. `shutdown()` — drain again with a shorter budget, stop the onion service,
   abort the retry worker, checkpoint the WAL, and take the node handle out of
   the `Wire` (which is what releases the last Arc to the Tor client and the
   store).

Both run on a process-scoped `TEARDOWN` scope (`SupervisorJob` + `Dispatchers.IO`)
because `onCleared()` runs *after* `viewModelScope` is already cancelled. Errors
are deliberately swallowed there: the UI is gone, and the SDK reports a second
teardown as the typed `WireException.Stopped` rather than a panic.

`unlock()` joins any in-flight teardown before opening again. The old node holds
the sqlite file and Arti's state lock until its teardown returns, and racing it
makes the next `openWire` fail.

A process killed outright (Doze, background-process killer, force-stop) still
never runs any of this — that is what the sqlite outbox and the new `flush()`
are for. The foreground-service card (`t_5bf32cd3`) moves this ownership from
the ViewModel to the service.
2026-09-12 15:10:29 -04:00
apk-dev
38fde75d40
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state
A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the
Kotlin reference left Arti's client, the hosted v3 onion service, the outbox
retry worker and the sqlite connection alive, and there was no way to ask where
the onion service was. On Android the process is killed without warning by Doze
and the background-process killer, so "drop everything when the process dies" is
not a lifecycle.

Core (`src/node.rs`, `src/hs.rs`):

* `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the
  rendezvous task is aborted and the RunningOnionService dropped), abort the
  retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is
  swapped first, so a racing second call is a no-op.
* `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one
  delivery attempt for every queued outbox row, ignoring backoff, then a WAL
  checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s
  and the caller is a UI thread. A timeout leaves rows in `sending`;
  `Outbox::reset_stale` requeues them on the next unlock, same as a process that
  died mid-attempt.
* `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` /
  `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped,
  reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving
  readiness.
* Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`,
  `flush`) fails with a typed error after the node stops, rather than dialing a
  dead client.
* `checkpoint_wal` reaches the database through a short-lived second connection:
  `Store` owns the write connection and does not lend it out, and a checkpoint is
  a property of the database, not of one connection. Best effort — WAL replay on
  open recovers anything committed.

The `WorkerHandle` moved into a `Mutex<Option<...>>` so the teardown can *abort*
the retry worker instead of only dropping it when the whole `Node` dies.

SDK (`crates/onionwire-sdk/src/lib.rs`):

* `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`.
  `Wire` now holds `Mutex<Option<Arc<Node>>>`, so teardown drops the last
  reference to the Tor client and the store instead of keeping them alive behind
  a JNI handle.
* `WireError::Stopped` — a second flat variant, so "you must unlock again" is a
  typed `WireException.Stopped` in Kotlin, not a string match on `Failed`.
* No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports
  `Stopped`, which is the correct recovery (unlock again).
* Fixes the crate not compiling on this base at all: `Node::send` has returned
  `Result<OutboxStatus, String>` since the outbox landed, and the SDK still
  mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes
  `crates/**` from the Rust job, which is why it stayed green.

The live Tor test found a real bug in the first version of `tor_state`: Arti's
combined status is still `Bootstrapping` after a *successful* probe of our own
onion (that mismatch is what the 360s publish wait exists for), and a freshly
launched service reports `Shutdown` before its publish reactor starts — so a
node that was live and reachable reported `Bootstrapping`, and briefly
`Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set
when the publish bar is crossed and cleared when `rotate` hard-cuts the service,
and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather
than terminal.
2026-09-12 15:10:29 -04:00
c39259b919 Merge pull request 'feat(core): zeroize in-memory secret material (Noise/Ed25519/X25519/store key)' (#46) from feat/zeroize-secrets into main
All checks were successful
ci / test (push) Successful in 3m54s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m53s
release / aarch64 (push) Successful in 2m27s
release / publish (push) Successful in 11s
Reviewed-on: #46
2026-09-12 19:06:58 +00:00
8eb0820df0 Merge branch 'main' into feat/zeroize-secrets
All checks were successful
ci / test (pull_request) Successful in 6m33s
2026-09-12 19:06:50 +00:00
2a53bc2b89 Merge pull request 'feat(outbox): local chat retry queue — queue sends and retry with backoff' (#45) from feat/local-outbox into main
Some checks failed
release / version (push) Waiting to run
release / aarch64 (push) Blocked by required conditions
release / publish (push) Blocked by required conditions
release / x86_64 (push) Blocked by required conditions
ci / test (push) Has been cancelled
Reviewed-on: #45
2026-09-12 19:06:14 +00:00
t
b79f1fd6f3
feat(tui): per-message outbox delivery state + N queued footer
All checks were successful
ci / test (pull_request) Successful in 4m9s
Chat rows now carry the state the local outbox actually holds: `✓` delivered,
`◷ queued (try n/8, retry 45s)` while the retry worker still has it, `» sending`
mid-attempt and `✗ failed: <short reason>` once attempts are exhausted. The
footer replaces the flat `sent` / `send failed` copy with the live count
(`2 queued`), and keeps a fail-closed `send failed: …` statement as long as any
row is terminally failed.

States come from the outbox API (`Node::outbox_pending` → `Queued` / `Sending` /
`Failed`; a delivered row is deleted, so absence is `Sent`). No parallel state
model, no new wire prefix. Every new glyph has an ASCII fallback (`ok` plus the
state word) exercised by a test.

- `chat_with_delivery()` / `delivery_tag()` / `retry_in_text()` /
  `short_send_reason()` / `OutboxSummary::note()` are pure and unit-tested.
- `draw_chat()` is now the real chat-pane renderer (extracted from
  `App::draw_main`) so width/wrap is testable without a `Node`.
- docs/TUI.md: delivery markers, copy, and the 80x24 floor / 120x40 target.

Verified: cargo test 26/26 suites ok (tui_spec 20/20, incl. a real Store +
Outbox::send -> pending() -> render path); clippy --all-targets -D warnings clean.
2026-09-12 14:44:35 -04:00
Sirius DevOps
d6d157765a
feat(outbox): local retry queue for chat sends
All checks were successful
ci / test (pull_request) Successful in 4m8s
Queue a chat send locally when the peer's v3 onion is unreachable and retry
it with exponential backoff (30s doubling, capped at 30 min, 8 attempts then
terminal Failed). Still peer-to-peer: no server, no store-and-forward relay,
no new frame prefix — every attempt is a fresh Noise IK handshake.

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

src/tui.rs gets one forced arm change (Ok(()) -> Ok(_)); UI surfacing is
child card t_d9a5b065.
2026-09-12 14:39:14 -04:00
acb6c7dd65 Merge pull request 'feat(android): wrap the store passphrase in the Android Keystore' (#44) from feat/android-keystore-store-passphrase into main
Reviewed-on: #44
2026-09-12 18:29:19 +00:00
bf9900f9dc Merge branch 'main' into feat/android-keystore-store-passphrase 2026-09-12 18:29:10 +00:00
1582f7d450 Merge pull request 'feat(store): encrypt the whole sqlite store with SQLCipher' (#43) from feat/sqlcipher-store into main
All checks were successful
ci / test (push) Successful in 3m28s
release / version (push) Successful in 3s
release / x86_64 (push) Successful in 5m41s
release / aarch64 (push) Successful in 7m34s
release / publish (push) Successful in 12s
Reviewed-on: #43
2026-09-12 18:28:44 +00:00
70e70cfe8d Merge branch 'main' into feat/sqlcipher-store
All checks were successful
ci / test (pull_request) Successful in 3m31s
2026-09-12 18:28:09 +00:00
27e49b4ea6 Merge pull request 'ci: watch upstream Arti/tor-* releases daily and file an upgrade issue' (#42) from wt/t_731235d4 into main
Reviewed-on: #42
2026-09-12 18:27:21 +00:00
Sirius DevOps
fc7378596d
feat(core): zeroize in-memory secret material (Noise/Ed25519/X25519/store key)
All checks were successful
ci / test (pull_request) Successful in 3m50s
Wrap every secret this crate holds in zeroize: the local identity and
prekey secrets (Keys), the backup bundle and its derived Argon2id wrap
key, the store data key and the SQLCipher key material, the identity
secret handed out by Store::self_identity, the raw identity-secret
copies in pay/qr signing, and the wallet RPC password plus the
user:realm:password digest input.
2026-09-12 13:55:07 -04:00
Sirius DevOps
2fd640e230
feat(android): wrap the store passphrase in the Android Keystore
Typing the passphrase on every launch was the v1 posture. It stays the
fallback, but it is no longer required: on first unlock the passphrase can be
remembered (checkbox, on by default) and is stored as an AES-256-GCM blob
wrapped by a key that never leaves the Android Keystore.

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

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

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

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

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

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

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

Both artefacts state what this does not cover: Tor Project security
announcements, a yanked crate, and a vulnerability with no version bump.
2026-09-12 13:55:07 -04:00
38 changed files with 4141 additions and 175 deletions

View file

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

12
Cargo.lock generated
View file

@ -2295,6 +2295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15"
dependencies = [
"cc",
"openssl-sys",
"pkg-config",
"vcpkg",
]
@ -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",
]

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -3,10 +3,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() {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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
View file

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

View file

@ -16,11 +16,41 @@ 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
@ -30,7 +60,7 @@ Peer onion down → a **chat** send is queued locally and retried (see “Local
A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted:
- **Device seizure.** A pending (never-delivered) message sits in the same db as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure with the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase.
- **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.
@ -43,6 +73,18 @@ A signed `prf` frame is shown to people who already have a session with you. App
OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy.
Run it **view-only** (recommended). `/pay` and receipt verification need only
`create_address`/`get_transfers`, which a wallet without a spend key serves
fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC
dial, and a view-only wallet is detected over RPC (`query_key`
`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says
so plainly instead of failing with a raw wallet error. The trade-off is
explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local
spend authority — any process that can read the RPC credentials can move the
balance, and `/tip` gives a chat peer a supported way to ask for a transfer.
Loopback binding is not an authorization boundary. Full setup, view-only wallet
creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md).
## Backup file is the identity
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.
@ -75,6 +117,6 @@ the peer already knows the plaintext they sent.
## Out of v1
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
relay, multi-device, DHT / name server, sqlcipher, A/V. The local retry queue of
the previous section is not an outbox in the XMPP sense: it never leaves the
device.
relay, multi-device, DHT / name server, A/V. The local retry queue of the
previous section is not an outbox in the XMPP sense: it never leaves the device.

184
docs/WALLET.md Normal file
View file

@ -0,0 +1,184 @@
# OnionWire + monero-wallet-rpc
OnionWire is not a wallet. It never holds a seed, a spend key, or a view key.
It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on
loopback, only to:
- hand out a receive subaddress for `/pay` invoices (`create_address`),
- read incoming transfers to verify a peer's receipt (`get_transfers`),
- and — only if you let it — spend for `/tip` (`transfer`).
**Run it view-only, and switch `/tip` off explicitly.** Everything else in this
document explains why, and what breaks when you do.
## Env vars
| Variable | Meaning |
|---|---|
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
`README.md` carries the operator summary; this file is the long form.
## Recommended topology
```
wallet host (this machine)
┌──────────────────────────────────────────────────────────────┐
│ monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-login u:p │
│ ▲ HTTP Digest, loopback only │
│ │ │
│ OnionWire (ONIONWIRE_WALLET_NO_SPEND=1) ── /pay, receipts │
│ └── /tip refused locally │
└──────────────────────────────────────────────────────────────┘
```
Loopback is the only address OnionWire will dial. `.onion` RPC URLs are
rejected: there is no Arti dial for the wallet, and a remote wallet would move
your key material off the box.
## Create a view-only wallet
Either path produces a wallet file with the view key only. Keep the seed /
spend key on a machine that is **not** running OnionWire.
With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard*
address the view key belongs to, then the secret view key):
```bash
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
# Standard address: 4...
# Secret view key: <hex>
```
Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys`
without `spendkey` writes a watch-only wallet):
```bash
curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{
"filename":"viewonly","password":"walletpass",
"address":"4...","viewkey":"<hex>","restore_height":<height>}}'
# → "Watch-only wallet has been generated successfully."
```
Then serve it:
```bash
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret \
--daemon-address "$YOUR_MONEROD:18089"
export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083
export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
export ONIONWIRE_WALLET_NO_SPEND=1
```
Restore the wallet from a height *at or before* its first incoming transaction
— a view-only wallet cannot rescan cheaply from height 0.
## What works, what does not
| Feature | View-only | Spend-capable |
|---|---|---|
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
| Receipt verification (`get_transfers`) | works | works |
| Profile `xmr_addr` fallback when RPC is down | works | works |
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
| OnionWire learns your spend key | never | never (it stays in the wallet) |
With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is
contacted, with:
```
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
```
Without the flag, `/tip` against a view-only wallet fails at the wallet and
OnionWire then asks the wallet directly whether it can spend (see below), so you
get the same sentence instead of a raw RPC error.
## How OnionWire detects view-only over RPC
The signal people usually reach for is `query_key` with `key_type=mnemonic`. It
works, but it is the wrong key to ask for: on a spend-capable wallet it hands
over the whole seed (full spend ability) over loopback HTTP, and it answers
`-43` for wallets that have no mnemonic at all. The spend key is narrower and
just as unambiguous:
```
query_key {"key_type":"spend_key"}
spend-capable → result.key = <hex secret spend key>
view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key."
```
(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the
two agree — OnionWire asks for the spend key because it is the smaller secret.)
- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key)
- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in
[`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h)
- The view-only branch is `on_query_key` in
[`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp)
OnionWire only calls this **after** a `transfer` has already failed — it never
probes a healthy wallet — and it discards `result.key` immediately. There is no
RPC method that reports "view-only" as a plain field; `query_key` is the
documented signal and this is its only cost: a spend-capable wallet answers with
its spend key over loopback HTTP, which is one more reason to run view-only.
Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc`
answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error
unchanged. It never guesses "view-only" from an unrelated failure.
## Why loopback still needs authentication
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it
away from other users or processes on the same machine. Any local process can
`connect(127.0.0.1:18083)`.
- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
refuses URLs without credentials. Unset the credentials and the wallet is open
to every local process — with a spend-capable wallet file, that is a
one-curl drain of your balance.
- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext,
but Digest gives no confidentiality: a local attacker who can sniff loopback
can replay it. Treat loopback as trusted-ish, not safe.
- Do not log the password, and do not put it in a shell history you share.
Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL.
## The spend-authority warning
An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a
local spend authority: any process that can read the RPC credentials (env var,
`/proc/<pid>/environ`, shell history, a stored URL) can spend the wallet's
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
default:
- the wallet file holds no spend key, so a stolen wallet file cannot be used to
move funds;
- the RPC credentials grant only receive-address and history reads;
- `/tip` fails locally with a plain message, so nothing in the UI pretends the
spend path exists.
If you want tips to work, understand that you are deliberately making the
OnionWire process able to spend. Give it a **separate hot wallet with a small
balance**, not your savings wallet.
## References
- Monero Wallet RPC reference:
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
- `on_query_key` (view-only → `-29`):
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp>
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`:
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h>
- `--generate-from-view-key` (incoming-only wallet):
<https://github.com/monero-project/monero/blob/master/src/simplewallet/simplewallet.cpp>
- `generate_from_keys` (watch-only when `spendkey` is omitted):
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#generate_from_keys>

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

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

View file

@ -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}");
}
}

View file

@ -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,

View file

@ -23,9 +23,10 @@ pub struct Loc {
const PREFIX: &[u8] = b"loc ";
pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> {
let sk_bytes: [u8; 32] = identity_sk
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
// Same one-shot raw identity-secret copy as `profile::sign`; shared so
// `Zeroize` covers it here too.
let sk_bytes =
crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec();
Ok(Loc {

View file

@ -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,11 +9,12 @@ 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;
@ -29,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<()>,
}
@ -60,17 +81,29 @@ pub struct Node {
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
_outbox_worker: WorkerHandle,
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(
@ -110,7 +143,9 @@ impl Node {
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
_outbox_worker: WorkerHandle(outbox.spawn_worker()),
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.
@ -119,10 +154,14 @@ impl Node {
// 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())?
@ -131,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()
}
@ -431,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 {
@ -444,6 +619,7 @@ impl Node {
/// 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)),
@ -463,6 +639,7 @@ impl Node {
}
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
self.ensure_running()?;
let old_nick = self
.store
.lock()
@ -479,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())?;
@ -546,6 +727,7 @@ impl Node {
/// 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
}
@ -854,6 +1036,49 @@ fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
});
}
/// 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")
@ -896,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");
}
}

View file

@ -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())
}

View file

@ -1,4 +1,5 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
check_fields(display_name, bio, xmr_addr)
}
/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to
/// build a `SigningKey`.
///
/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature);
/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather
/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes`
/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it
/// used to make.
pub fn signing_key_bytes(identity_sk: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
if identity_sk.len() != 32 {
return Err(Error("identity secret key must be 32 bytes".into()));
}
let mut bytes = Zeroizing::new([0u8; 32]);
bytes[..].copy_from_slice(identity_sk);
Ok(bytes)
}
pub fn sign(
identity_sk: &[u8],
display_name: &str,
@ -38,9 +56,7 @@ pub fn sign(
ts: i64,
) -> Result<Profile> {
check_fields(display_name, bio, xmr_addr)?;
let sk_bytes: [u8; 32] = identity_sk
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
let sk_bytes = signing_key_bytes(identity_sk)?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk
.sign(&sign_msg_v2(display_name, bio, xmr_addr, ts))

View file

@ -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);

View file

@ -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;
@ -61,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],
}
@ -131,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)?;
@ -200,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
@ -254,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()))?;

View file

@ -1,4 +1,5 @@
use std::fs;
use std::io::Read;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@ -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>;
@ -51,14 +53,15 @@ impl From<Error> for String {
pub struct Store {
conn: Connection,
msg_key: [u8; 32],
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>,
}
@ -178,7 +181,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> {
@ -189,7 +193,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}")));
@ -280,7 +284,7 @@ impl Store {
}
let mut store = Self {
conn,
msg_key: [0u8; 32],
msg_key: Zeroizing::new([0u8; 32]),
};
store.migrate()?;
store.ensure_self()?;
@ -356,8 +360,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()));
}
@ -366,12 +373,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],
@ -465,13 +472,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(
@ -483,7 +490,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],
)?;
}
}
@ -497,10 +504,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)?,
})
},
@ -1105,10 +1112,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> {
@ -1119,29 +1310,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))
}
}
}
@ -1186,6 +1377,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() {
@ -1329,6 +1535,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();

View file

@ -9,6 +9,7 @@ use ratatui::style::{Color, Modifier, Style};
use ratatui::symbols::border;
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{DefaultTerminal, Frame};
use zeroize::{Zeroize, Zeroizing};
use crate::node::Node;
use crate::outbox::DEFAULT_MAX_ATTEMPTS;
@ -957,6 +958,78 @@ impl BackupPrompt {
}
}
/// The in-progress passphrase on the backup/restore screen: the hidden buffer
/// plus the first entry, kept across the second prompt of the backup flow.
///
/// Both are `Zeroizing<String>`, so the passphrase does not sit in a plain
/// heap `String` for the life of the screen; `close()` wipes eagerly on every
/// exit path (submit, mismatch, cancel) instead of waiting for the screen
/// value to be dropped, and the wrapper covers the paths that cannot call it
/// (Ctrl-Q, a panic).
pub struct PassphraseEntry {
first: Option<Zeroizing<String>>,
buf: Zeroizing<String>,
}
impl Default for PassphraseEntry {
fn default() -> Self {
Self {
first: None,
buf: Zeroizing::new(String::new()),
}
}
}
impl PassphraseEntry {
pub fn new() -> Self {
Self::default()
}
/// Second prompt of the backup flow: the first passphrase was already typed.
pub fn with_first(first: &str) -> Self {
Self {
first: Some(Zeroizing::new(first.to_string())),
..Self::default()
}
}
pub fn push(&mut self, c: char) {
self.buf.push(c);
}
pub fn backspace(&mut self) {
self.buf.pop();
}
/// What the screen echoes back — the passphrase itself is not drawn.
pub fn buf(&self) -> &str {
self.buf.as_str()
}
pub fn first(&self) -> Option<&str> {
self.first.as_deref().map(String::as_str)
}
/// Take the typed passphrase for submission, leaving this entry empty.
pub fn take_buf(&mut self) -> Zeroizing<String> {
std::mem::replace(&mut self.buf, Zeroizing::new(String::new()))
}
/// Take the first-passphrase copy for the confirm comparison.
pub fn take_first(&mut self) -> Option<Zeroizing<String>> {
self.first.take()
}
/// Wipe both buffers: the screen is done with them.
pub fn close(&mut self) {
self.buf.zeroize();
if let Some(first) = self.first.as_mut() {
first.zeroize();
}
self.first = None;
}
}
pub fn backup_screen_text() -> &'static str {
"Write encrypted identity backup?\n\
This file is your identity secret. Treat it like the database.\n\
@ -1036,8 +1109,7 @@ enum Screen {
Passphrase {
kind: BackupKind,
path: String,
first: Option<String>,
buf: String,
entry: PassphraseEntry,
},
Quit {
prompt: QuitPrompt,
@ -1125,6 +1197,7 @@ impl App {
let mut tip_cmd = None;
let mut file_cmd = None;
let mut chat_send = None;
let mut pass_submit = None;
match &mut self.screen {
Screen::Main => match key.code {
KeyCode::Tab => self.focus = self.focus.next(),
@ -1286,8 +1359,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.clone(),
first: None,
buf: String::new(),
entry: PassphraseEntry::new(),
};
}
}
@ -1297,25 +1369,17 @@ impl App {
_ => {}
}
}
Screen::Passphrase {
kind,
path,
first,
buf,
} => match key.code {
KeyCode::Esc => self.screen = Screen::Main,
KeyCode::Backspace => {
buf.pop();
Screen::Passphrase { kind, path, entry } => match key.code {
KeyCode::Esc => {
entry.close();
self.screen = Screen::Main;
}
KeyCode::Backspace => entry.backspace(),
KeyCode::Enter => {
let kind = *kind;
let path = path.clone();
let first = first.clone();
let pass = buf.clone();
self.submit_passphrase(kind, &path, first.as_deref(), &pass)?;
pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf()));
}
KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
buf.push(c);
entry.push(c);
}
_ => {}
},
@ -1362,6 +1426,9 @@ impl App {
if let Some(text) = chat_send {
self.send_chat(&text)?;
}
if let Some((kind, path, first, pass)) = pass_submit {
self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?;
}
Ok(None)
}
@ -1475,8 +1542,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.to_string(),
first: Some(pass.to_string()),
buf: String::new(),
entry: PassphraseEntry::with_first(pass),
};
}
}
@ -1685,9 +1751,9 @@ impl App {
Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()),
Screen::Profile { editor } => draw_profile(f, editor),
Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()),
Screen::Passphrase {
kind, first, buf, ..
} => draw_passphrase(f, *kind, first.is_some(), buf),
Screen::Passphrase { kind, entry, .. } => {
draw_passphrase(f, *kind, entry.first().is_some(), entry.buf())
}
Screen::Quit { prompt } => draw_quit(f, prompt.typed()),
}
if self.help_open {
@ -2245,3 +2311,66 @@ fn to_hex(bytes: &[u8]) -> String {
fn io_err(e: io::Error) -> String {
e.to_string()
}
#[cfg(test)]
mod passphrase_buffer_tests {
use super::*;
fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
/// The typed passphrase lives in `Zeroizing` buffers, not in bare
/// `String`s that sit in the heap for the life of the screen.
#[test]
fn passphrase_buffers_are_zeroizing() {
let mut entry = PassphraseEntry::new();
entry.push('x');
let _: &Zeroizing<String> = &entry.buf;
let _: &Option<Zeroizing<String>> = &entry.first;
assert_zeroize_on_drop::<Zeroizing<String>>();
}
/// Closing the screen (submit, mismatch or cancel) must leave nothing of
/// the typed passphrase behind in its heap buffer.
#[test]
fn closing_the_passphrase_screen_wipes_the_typed_secret() {
let mut entry = PassphraseEntry::new();
for c in "hunter2-secret".chars() {
entry.push(c);
}
assert_eq!(entry.buf(), "hunter2-secret");
let ptr = entry.buf.as_ptr();
let cap = entry.buf.capacity();
assert!(cap >= 14, "expected a heap buffer, capacity {cap}");
entry.close();
assert!(entry.buf().is_empty(), "buffer not cleared");
// SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole
// capacity and *keeps* the allocation (`Vec::zeroize`: zero the
// elements, clear the length, zero the spare capacity). `entry` still
// owns that buffer, so these `cap` bytes are live memory.
let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) };
assert!(
bytes.iter().all(|b| *b == 0),
"typed passphrase survived close(): {bytes:?}"
);
}
/// The first entry of the two-step backup flow is a secret too, and the
/// screen holds it across the second prompt.
#[test]
fn closing_the_passphrase_screen_drops_the_first_entry_copy() {
let mut entry = PassphraseEntry::with_first("first-typed");
assert_eq!(entry.first(), Some("first-typed"));
entry.close();
assert_eq!(
entry.first(),
None,
"first passphrase copy survived close()"
);
}
}

View file

@ -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 {
@ -41,8 +42,18 @@ impl std::fmt::Debug for Endpoint {
#[derive(Debug, Clone)]
pub struct Wallet {
endpoint: Option<Endpoint>,
no_spend: bool,
}
/// What /tip says when the wallet cannot spend. Same text for the explicit
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
/// RPC, so the operator never has to guess which one it was.
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
/// `src/wallet/wallet_rpc_server_error_codes.h`.
const WATCH_ONLY_CODE: i64 = -29;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRow {
pub txid: String,
@ -54,36 +65,64 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5);
impl Wallet {
pub fn disabled() -> Self {
Self { endpoint: None }
Self {
endpoint: None,
no_spend: false,
}
}
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
/// refused locally, before any RPC dial. `/pay` and receipt verification
/// keep working.
pub fn from_env() -> Self {
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
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),
no_spend,
},
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self::disabled()
Self {
endpoint: None,
no_spend,
}
}
}
}
_ => Self::disabled(),
_ => Self {
endpoint: None,
no_spend,
},
}
}
pub fn from_url(url: &str) -> Result<Self> {
Ok(Self {
endpoint: Some(parse_http_url(url, None)?),
no_spend: false,
})
}
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
pub fn with_no_spend(mut self, on: bool) -> Self {
self.no_spend = on;
self
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
pub fn configured(&self) -> bool {
self.endpoint.is_some()
}
@ -103,7 +142,10 @@ impl Wallet {
}
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
let v = self
if self.no_spend {
return Err(Error(VIEW_ONLY_MSG.into()));
}
let sent = self
.rpc(
"transfer",
serde_json::json!({
@ -111,10 +153,36 @@ impl Wallet {
"account_index": 0
}),
)
.await?;
.await;
let v = match sent {
Ok(v) => v,
// The wallet's own refusal is opaque, so ask the documented
// pre-transfer signal before surfacing it. Fail closed: if the
// probe cannot answer, the original error stands.
Err(e) => {
if self.view_only().await {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(e);
}
};
json_str(&v, "tx_hash")
}
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
/// the signal monero actually exposes for a wallet with no spend key.
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
/// which this discards.
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
async fn view_only(&self) -> bool {
matches!(
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
.await,
Err(e) if e.to_string() == VIEW_ONLY_MSG
)
}
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
let v = self
.rpc(
@ -185,12 +253,23 @@ 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)> {
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
/// unset) means off.
fn env_flag(name: &str) -> bool {
matches!(
std::env::var(name)
.map(|v| v.trim().to_ascii_lowercase())
.as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
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 +484,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()
@ -449,6 +530,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("rpc error");
// The one RPC-level error we translate: a view-only wallet has no
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
return Err(Error(VIEW_ONLY_MSG.into()));
}
return Err(Error(msg.into()));
}
json.get("result")

View file

@ -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);

View file

@ -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.

View file

@ -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
View 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"
);
}

View file

@ -1,5 +1,7 @@
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
use std::sync::{Arc, Mutex};
use ed25519_dalek::SigningKey;
use onionwire::pay;
use onionwire::wallet::{self, TransferRow, Wallet};
@ -8,6 +10,10 @@ use rand::rngs::OsRng;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
TransferRow {
txid: txid.into(),
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() {
);
}
/// Records every request the client sends, answers the Digest challenge and
/// then replies per RPC method. Lets a test assert on the *request log*.
async fn serve_recording(
listener: TcpListener,
log: Arc<Mutex<Vec<String>>>,
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
) {
loop {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let n = sock.read(&mut buf).await.unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]).to_string();
log.lock().expect("log").push(req.clone());
if req.contains("Authorization:") {
let body = reply(&rpc_method(&req));
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
} else {
let _ = sock.write_all(digest_401().as_bytes()).await;
}
}
}
fn rpc_method(req: &str) -> String {
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
serde_json::from_str::<serde_json::Value>(body.trim())
.ok()
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
.unwrap_or_default()
}
fn http_200_body(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
}
fn rpc_error(code: i64, message: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
}
/// JSON-RPC body only (the server wraps it in an HTTP 200).
fn rpc_result(result: &str) -> String {
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
}
fn recording_wallet(port: u16) -> Wallet {
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
}
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
/// local `transfer` before any socket is opened.
#[tokio::test]
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
));
let w = recording_wallet(port).with_no_spend(true);
assert!(w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(
err.to_ascii_lowercase().contains("view-only"),
"got {err}"
);
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
let seen = log.lock().expect("log").clone();
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
// Positive control: the recorder is live, so the emptiness above is real.
let _ = w.get_address().await;
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
}
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
/// with the no-spend flag on — only `transfer` is refused.
#[tokio::test]
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|method| match method {
"create_address" => rpc_result(
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
),
"get_transfers" => rpc_result(
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
),
_ => rpc_result(r#"{}"#),
}),
));
let w = recording_wallet(port).with_no_spend(true);
let created = w.create_address().await.expect("create_address");
assert!(created.starts_with('8'), "got {created}");
let rows = w.get_transfers().await.expect("get_transfers");
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
let seen = log.lock().expect("log").clone();
assert!(
seen.iter()
.any(|r| r.contains("\"method\":\"create_address\"")),
"recorder must have seen the invoice path: {seen:?}"
);
assert!(
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
"transfer must never be dialed in no-spend mode"
);
}
/// A view-only wallet refuses `transfer` with its own opaque error. The
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
#[tokio::test]
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let log = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(serve_recording(
listener,
Arc::clone(&log),
Arc::new(|method| match method {
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
_ => rpc_error(-18, "No transaction created"),
}),
));
let w = recording_wallet(port);
assert!(!w.no_spend());
let err = w
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
let seen = log.lock().expect("log").clone();
assert!(
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
"must ask the RPC-side signal: {seen:?}"
);
}
/// A spend-capable wallet must keep its real error: no fabricated detection.
#[tokio::test]
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(serve_recording(
listener,
Arc::new(Mutex::new(Vec::new())),
Arc::new(|method| match method {
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
_ => rpc_error(-18, "No transaction created"),
}),
));
let err = recording_wallet(port)
.transfer(
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
1,
)
.await
.unwrap_err()
.to_string();
assert!(err.contains("No transaction created"), "got {err}");
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
}
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
#[tokio::test]
async fn open_rpc_without_digest_challenge_is_still_refused() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let canned = http_200_body(
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
);
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.expect("accept");
let mut buf = vec![0u8; 4096];
let _ = sock.read(&mut buf).await;
let _ = sock.write_all(canned.as_bytes()).await;
});
let err = recording_wallet(port)
.get_address()
.await
.unwrap_err()
.to_string();
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
}
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
#[test]
fn from_env_reads_no_spend_flag() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
}
let on = Wallet::from_env();
assert!(on.no_spend(), "flag 1 must mean no-spend");
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
for off in ["0", "no", "off"] {
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
}
unsafe {
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
std::env::remove_var("ONIONWIRE_WALLET_RPC");
}
assert!(!Wallet::from_env().no_spend(), "unset must be off");
}
fn digest_401() -> String {
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
}

157
tests/zeroize.rs Normal file
View file

@ -0,0 +1,157 @@
//! 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::profile;
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)
}
}
/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back.
///
/// SAFETY: only for `ManuallyDrop<Zeroizing<[u8; 32]>>` locals — same contract
/// as `drop_in_place_and_peek_identity_sk`.
unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] {
let p: *const [u8; 32] = &**v;
// SAFETY: the caller guarantees `v` is dropped exactly once and is still
// alive at its own address when read back.
unsafe {
std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>);
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}");
}
/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the
/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that
/// stays on the stack until the function returns.
#[test]
fn profile_signing_key_bytes_are_zeroizing_and_wipe() {
let secret = [0x5au8; 32];
let bytes = profile::signing_key_bytes(&secret).expect("32 bytes");
let _: &Zeroizing<[u8; 32]> = &bytes;
assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret");
let mut probe = std::mem::ManuallyDrop::new(bytes);
let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) };
assert_eq!(after, [0u8; 32], "identity secret survived its drop");
}
/// A length-mismatched secret is an error, not a truncated/padded key.
#[test]
fn profile_signing_key_bytes_rejects_a_short_secret() {
assert!(profile::signing_key_bytes(&[7u8; 31]).is_err());
assert!(profile::signing_key_bytes(&[7u8; 33]).is_err());
}