Merge branch 'main' into wt/t_95e0d607

This commit is contained in:
sirius 2026-09-12 22:29:07 +00:00
commit 70ae597abc
41 changed files with 4433 additions and 309 deletions

1
Cargo.lock generated
View file

@ -2654,6 +2654,7 @@ dependencies = [
"tor-rtcompat",
"tracing-subscriber",
"x25519-dalek",
"zeroize",
]
[[package]]

View file

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

@ -3,7 +3,7 @@
Lean Tor messenger: one Rust process (ratatui + Noise IK + sqlite + in-process Arti).
No hosted server. Identity is a public key; the onion is only a locator.
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. Chat bodies are encrypted at rest; identity keys in sqlite are still plaintext.
**v0.2** — Linux TUI. Two people add each other with an `onionwire:v1:…` invite string (`F2` share / `F3` paste). There is no QR graphic. Chat is Noise IK over your own v3 onion. Optional Monero invoices if you point at a local `monero-wallet-rpc`. Fail closed: peer down → send fails. Arti onion services are still experimental. The whole store is encrypted at rest with SQLCipher; message bodies add a row-bound AEAD layer on top.
You do **not** install a `tor` daemon, `torrc`, Prosody, or XMPP. OnionWire embeds Arti and publishes its own v3 onion.
@ -222,14 +222,11 @@ If you set `ONIONWIRE_HOME`, delete that directory instead.
## Seized laptop
Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in `messages.plaintext`) with AAD bound to `friend_id`, `dir`, and row id, wrapped by a passphrase-derived Argon2id key. A disk grep of `onionwire.db` must not yield the message log. Empty-AAD v0.2 blobs are rewrapped once on unlock.
The whole sqlite file is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). A 32-byte key is derived from the store passphrase with Argon2id over a per-install 16-byte salt in `store_salt` (mode 0600, in `ONIONWIRE_HOME`) and handed to SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) as the first statement after open. The file header, schema, `self.identity_sk`, friend public keys, locators, profiles and payment rows are all ciphertext on disk, so a disk grep of `onionwire.db` must not yield the message log, your identity key or your roster. A wrong or empty passphrase fails closed before any write; an encrypted store whose `store_salt` is missing refuses to open instead of guessing. v0.2.1 plaintext installs upgrade in place on the first open with the right passphrase; a wrong one leaves the plaintext file untouched.
Still plaintext on disk (unless you add OS/FDE):
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 in `store_meta` wrapped with Argon2id from the same passphrase. Whole-file encryption does not stop someone who can write the file from moving one row's ciphertext into another row; the row-bound AAD does, and it stays. Empty-AAD v0.2 blobs are rewrapped once on unlock.
- your identity secret key (`self.identity_sk`)
- friend public keys and current locators
The message key is **not** wrapped with `identity_sk` (that key is in the same file). sqlcipher is out of v1. `/wipe` deletes chat and payments history; it is not a forensic erase. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
At-rest encryption is not a defense against a live compromise: while OnionWire runs, the passphrase, the db key and decrypted rows 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; it is not a forensic erase — SSD wear-levelling can keep copies. Roster and identity stay. `/wipe-all` deletes the data dir (new identity). Ctrl-Q can clear history on the way out (`CLEAR`) without becoming a new person.
Threat model: [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
@ -330,7 +327,7 @@ Do not run `cargo publish`; `publish = false`. CI needs the repo secret
## Not in v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, sqlcipher, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, QR codes, A/V. Protocol lock: [docs/PROTOCOL.md](docs/PROTOCOL.md).
## License

View file

@ -4,10 +4,33 @@
<!--
INTERNET is the only permission requested at first launch.
No camera (invites are typed/pasted, not scanned), no contacts, no
storage. Tor runs in-process; there is no foreground service and no
keep-alive notification in v1, so the node only lives while the app does.
storage.
Tor runs in-process, and the node is kept published across Doze and
backgrounding by KeepAliveService: a foreground service with an ongoing
notification, started on unlock, stopped by Lock or by the notification's
Stop action. Its anchors and the node's lifetime are arbitrated in
NodeHost/NodeLifetime; the service never owns the node itself.
-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!--
specialUse, not dataSync. dataSync is documented as "data transfer
operations" (upload/download, backup/restore, import/export) and the
official alternatives guide points at WorkManager or a user-initiated
transfer job — all of which assume a transfer with an end. A node holding
an inbound onion service open and draining a retry queue has no end and no
progress to report, so specialUse ("valid foreground service use cases
that aren't covered by the other types") is the honest declaration. It
costs a Play Console justification; dataSync would cost a lie.
-->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<!-- API 33+. Without it the keep-alive still runs, but its notification is
hidden from the drawer (the user sees the service in the Task Manager
instead). Denial is handled, not fatal: see WireViewModel.keepAliveNote. -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="false"
@ -30,6 +53,21 @@
</intent-filter>
</activity>
<!--
Not exported: only this app starts it, from a user-visible unlock.
stopWithTask is left at its default (false) on purpose — swiping the
task away must not take the onion offline; the activity is destroyed,
NodeHost flushes the outbox, and the onion stays published.
-->
<service
android:name=".keepalive.KeepAliveService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="peer-to-peer messaging node: keeps an inbound onion service published and an outbox retry queue running so peers can deliver messages while the app is backgrounded; there is no user-initiated transfer to bound the work" />
</service>
</application>
</manifest>

View file

@ -1,13 +1,18 @@
package com.siriusdevops.onionwire
import android.Manifest
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
@ -48,9 +53,27 @@ class MainActivity : ComponentActivity() {
private fun AppRoot(vm: WireViewModel = viewModel()) {
val phase by vm.phase.collectAsStateWithLifecycle()
val unlock by vm.unlock.collectAsStateWithLifecycle()
val keepAliveNote by vm.keepAliveNote.collectAsStateWithLifecycle()
// Asked in context: the notification is the keep-alive's only visible
// trace, so the prompt lands when the node becomes reachable rather than at
// first launch. Denial is not fatal — the service runs either way and the
// roster says the notice is hidden.
val askNotifications = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) { vm.onNotificationPermissionChanged() }
LaunchedEffect(phase) {
if (phase is Phase.Ready &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
!vm.notificationsAllowed()
) {
askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
when (val p = phase) {
is Phase.Ready -> ReadyGraph(vm, p)
is Phase.Ready -> ReadyGraph(vm, p, keepAliveNote)
else -> UnlockScreen(
phase = p,
unlock = unlock,
@ -62,7 +85,7 @@ private fun AppRoot(vm: WireViewModel = viewModel()) {
}
@Composable
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready, keepAliveNote: String?) {
val nav = rememberNavController()
val friends by vm.friends.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope()
@ -74,6 +97,7 @@ private fun ReadyGraph(vm: WireViewModel, ready: Phase.Ready) {
onion = ready.onion,
sdkVersion = ready.sdkVersion,
friends = friends,
keepAliveNote = keepAliveNote,
onOpenChat = { nav.navigate("chat/${it.pubkeyHex}") },
onShare = { nav.navigate("share") },
onPaste = { nav.navigate("paste") },

View file

@ -1,12 +1,16 @@
package com.siriusdevops.onionwire
import android.app.Application
import androidx.core.app.NotificationManagerCompat
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 com.siriusdevops.onionwire.keepalive.KeepAliveService
import com.siriusdevops.onionwire.keepalive.KeepAliveStatus
import com.siriusdevops.onionwire.keepalive.NodeHost
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@ -19,7 +23,6 @@ import uniffi.onionwire_sdk.InviteInfo
import uniffi.onionwire_sdk.RotateOutcome
import uniffi.onionwire_sdk.Wire
import uniffi.onionwire_sdk.decodeInvite
import uniffi.onionwire_sdk.openWire
import java.io.File
sealed interface Phase {
@ -56,10 +59,13 @@ sealed interface Unlock {
}
/**
* Owns the single Wire node for the process.
* Owns the UI side of the process's single node.
*
* The node lives in the ViewModel because a configuration change must not
* drop a published onion service and re-bootstrap Tor.
* The node itself lives in [NodeHost], not here, because it now has two
* possible owners: this ViewModel while the UI is up, and [KeepAliveService]
* while the screen is off. A configuration change still must not drop a
* published onion, and neither must the activity being destroyed — that part
* is unchanged.
*/
class WireViewModel(app: Application) : AndroidViewModel(app) {
@ -85,13 +91,28 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
private val _friends = MutableStateFlow<List<FriendInfo>>(emptyList())
val friends: StateFlow<List<FriendInfo>> = _friends.asStateFlow()
private var wire: Wire? = null
/**
* One line of battery honesty for the roster: what is still running once
* the screen is off, or why it is not. Null while locked.
*/
private val _keepAliveNote = MutableStateFlow<String?>(null)
val keepAliveNote: StateFlow<String?> = _keepAliveNote.asStateFlow()
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()
// A node the foreground service kept alive is still open. Adopt it and
// go straight to the roster: showing an unlock screen for a store that
// is already open would be theatre, and unlocking again would race the
// live node for the sqlite file.
val existing = NodeHost.current()
if (existing != null) {
viewModelScope.launch { adopt(existing) }
} else {
refreshUnlockState()
}
viewModelScope.launch {
NodeHost.keepAlive.collect { renderKeepAliveNote(it) }
}
}
/**
@ -143,14 +164,158 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
}
}
/** Drops our handle. The onion service stops; nothing is sent after this. */
/**
* Explicit Lock: stops the node and the keep-alive with it.
*
* Order matters. The service goes first — a still-running keep-alive would
* re-anchor the node and leave a notification pointing at a dead onion —
* then the policy tears the node down, flush before `shutdown()` so the
* outbox survives.
*/
fun lock() {
wire = null
if (NodeHost.current() == null) return
KeepAliveService.stop(getApplication())
NodeHost.lock()
_friends.value = emptyList()
_phase.value = Phase.Locked
refreshUnlockState()
}
/**
* The UI is going away: a normal finish, a task swipe, or the process being
* killed. This deliberately does **not** shut the node down — [NodeHost]
* decides between "flush and stay published" (a keep-alive is holding it)
* and "flush and stop" (nothing is). A ViewModel that shut down a node the
* foreground service owns is the bug this card exists to avoid.
*/
override fun onCleared() {
NodeHost.onUiDetached()
super.onCleared()
}
/** Re-reads the notification state after the runtime prompt resolves. */
fun onNotificationPermissionChanged() {
renderKeepAliveNote(NodeHost.keepAlive.value)
// Android does not retroactively post a foreground notification that was
// suppressed while POST_NOTIFICATIONS was denied — the service started,
// the user then granted, and the shade stayed empty. Re-announce, so the
// grant actually produces the one honest signal the user has.
if (NodeHost.keepAlive.value is KeepAliveStatus.On) {
viewModelScope.launch {
NodeHost.current()?.let { KeepAliveService.start(getApplication(), it.onion()) }
}
}
}
/** Whether the keep-alive's notification can actually be posted. */
fun notificationsAllowed(): Boolean =
NotificationManagerCompat.from(getApplication()).areNotificationsEnabled()
private fun renderKeepAliveNote(status: KeepAliveStatus) {
val text = getApplication<Application>()
_keepAliveNote.value = when (status) {
// Not a null note: "off" is a real state the user should be able to
// read, right after the notification's Stop action.
KeepAliveStatus.Off -> text.getString(R.string.keep_alive_note_off)
KeepAliveStatus.On -> text.getString(
if (notificationsAllowed()) {
R.string.keep_alive_note_on
} else {
// Denial is not fatal: the service runs either way and
// Android lists it in the Task Manager. Say that instead of
// pretending the notification is there.
R.string.keep_alive_note_hidden
},
)
is KeepAliveStatus.Unavailable ->
text.getString(R.string.keep_alive_note_unavailable, status.reason)
}
}
/**
* The one path that opens 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 PR #49 for the follow-up SDK
* signature this card cannot make itself.
*/
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
if (secret.isEmpty() || _phase.value is Phase.Opening) {
StoreSecret.wipe(secret)
return
}
val existing = NodeHost.current()
if (existing != null) {
// Already open, kept alive while the UI was gone: adopt, never
// re-open. The live node holds the sqlite file and Arti's state
// lock, so a second open would fail — or worse, half-succeed.
StoreSecret.wipe(secret)
viewModelScope.launch { adopt(existing) }
return
}
_phase.value = Phase.Opening
viewModelScope.launch {
try {
// The SDK open is dispatched to Dispatchers.IO inside NodeHost:
// cold start is minutes of Tor bootstrap, which the main thread
// does not survive.
val w = NodeHost.open(home, secret.concatToString())
if (storeAfterwards) store(secret)
adopt(w)
startKeepAlive(w)
} catch (t: Throwable) {
_phase.value = Phase.Failed(t.message ?: t.toString())
} finally {
StoreSecret.wipe(secret)
}
}
}
/**
* Points the UI at a node that is already running. The SDK getters are
* `suspend`, hence the coroutine call sites.
*/
private suspend fun adopt(w: Wire) {
_phase.value = Phase.Ready(
fingerprint = w.fingerprint(),
onion = w.onion(),
sdkVersion = w.version(),
)
runCatching { refreshFriends() }
}
/**
* Starts the foreground keep-alive. Always reached from a user-visible
* unlock, so the API 31+ background-start restriction does not apply; if
* the system refuses anyway, [NodeHost] records why and the roster says so.
*/
private suspend fun startKeepAlive(w: Wire) {
if (NodeHost.keepAlive.value is KeepAliveStatus.On) return
KeepAliveService.start(getApplication(), w.onion())
}
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 refreshUnlockState() {
viewModelScope.launch {
val state = withContext(Dispatchers.IO) {
@ -171,62 +336,10 @@ class WireViewModel(app: Application) : AndroidViewModel(app) {
}
}
/**
* The one path that calls the SDK.
*
* [secret] is wiped in `finally`, including when the Keystore write or the
* SDK call throws. The SDK's UniFFI signature takes a `String`, so one
* immutable copy is unavoidable here — see the PR description for the
* follow-up SDK signature this card cannot make itself.
*/
private fun openWith(secret: CharArray, storeAfterwards: Boolean) {
if (secret.isEmpty() || _phase.value is Phase.Opening) {
StoreSecret.wipe(secret)
return
}
_phase.value = Phase.Opening
viewModelScope.launch {
try {
val w = openWire(home.absolutePath, secret.concatToString())
wire = w
if (storeAfterwards) store(secret)
_phase.value = Phase.Ready(
fingerprint = w.fingerprint(),
onion = w.onion(),
sdkVersion = w.version(),
)
refreshFriends()
} catch (t: Throwable) {
_phase.value = Phase.Failed(t.message ?: t.toString())
} finally {
StoreSecret.wipe(secret)
}
}
}
private suspend fun store(secret: CharArray) {
val outcome: Result<KeyBacking> = withContext(Dispatchers.IO) {
try {
secrets.save(secret)
Result.success(secrets.backing())
} catch (t: Throwable) {
Result.failure(t)
}
}
_unlock.value = outcome.fold(
onSuccess = { Unlock.OneTap(it) },
onFailure = {
// Unlock succeeded, so this is not fatal — say so plainly
// instead of pretending the passphrase was stored.
Unlock.TypeIt("Could not store the passphrase: ${it.message ?: it}.")
},
)
}
private fun unavailableNotice(reason: String): String =
"The stored passphrase could not be read — $reason. Type it once to store it again."
private fun requireWire(): Wire = wire ?: error("locked")
private fun requireWire(): Wire = NodeHost.requireOpen()
suspend fun refreshFriends() {
_friends.value = requireWire().friends()

View file

@ -0,0 +1,181 @@
package com.siriusdevops.onionwire.keepalive
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.siriusdevops.onionwire.MainActivity
import com.siriusdevops.onionwire.R
/**
* Holds the process (and therefore the in-process Arti node) in the foreground
* so the onion stays published after the screen goes off.
*
* The service does *not* own the node — [NodeHost] does. This reports its
* anchor and lets the policy decide: starting the keep-alive keeps the node
* alive, and losing it (user tapped Stop, or the system killed us) shuts the
* node down only if nothing else is holding it.
*
* Returns `START_NOT_STICKY` deliberately. A sticky restart would bring the
* service back with no node behind it — the passphrase is not held in memory
* after unlock — and a notification claiming "OnionWire is reachable" over a
* dead onion is worse than no service at all.
*/
class KeepAliveService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_STOP) {
// The user ended the keep-alive from the notification. `onDestroy()`
// reports the lost anchor: the node stops if nothing else holds it,
// and stays up while the app is still open in front of them (the UI
// anchor). The action is labelled "Stop keep-alive", not "Lock", so
// that is the behaviour it promises.
stopSelf()
return START_NOT_STICKY
}
if (NodeHost.current() == null) {
// Nothing to keep alive. A notification here would be a lie.
stopSelf()
return START_NOT_STICKY
}
if (!startInForeground(intent?.getStringExtra(EXTRA_ONION).orEmpty())) {
stopSelf()
return START_NOT_STICKY
}
NodeHost.onKeepAliveStarted()
return START_NOT_STICKY
}
override fun onDestroy() {
NodeHost.onKeepAliveStopped()
super.onDestroy()
}
/**
* @return false when the system refused the foreground start, in which case
* the anchor was never taken and the node stays foreground-only.
*/
private fun startInForeground(onion: String): Boolean {
return try {
createChannel()
val notification = buildNotification(onion)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,
)
} else {
// API 26-33: the manifest-declared type is what the platform
// records; the three-arg overload only exists from 29.
startForeground(NOTIFICATION_ID, notification)
}
true
} catch (t: Throwable) {
// API 31+: a start from the background throws
// ForegroundServiceStartNotAllowedException. Degrade to "the node
// lives only while the app does" instead of taking the process
// down; the roster says so on screen.
Log.w(TAG, "foreground start refused; node stays foreground-only", t)
NodeHost.onKeepAliveRefused(t.message ?: t.toString())
false
}
}
private fun createChannel() {
val manager = getSystemService(NotificationManager::class.java) ?: return
val channel = NotificationChannel(
CHANNEL_ID,
getString(R.string.keep_alive_channel_name),
// LOW: present in the shade, never a sound or a heads-up. This is a
// status light, not an alert.
NotificationManager.IMPORTANCE_LOW,
).apply {
description = getString(R.string.keep_alive_channel_description)
setShowBadge(false)
}
manager.createNotificationChannel(channel)
}
private fun buildNotification(onion: String): Notification {
val open = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val stop = PendingIntent.getService(
this,
1,
Intent(this, KeepAliveService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
// Never the full v3 locator: a notification body is lock-screen public.
val short = onion.take(ONION_PREFIX)
val text = if (short.isEmpty()) {
getString(R.string.keep_alive_text)
} else {
getString(R.string.keep_alive_text_onion, short)
}
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_onion)
.setContentTitle(getString(R.string.keep_alive_title))
.setContentText(text)
.setContentIntent(open)
.addAction(0, getString(R.string.keep_alive_stop), stop)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.build()
}
companion object {
private const val TAG = "OnionWireKeepAlive"
const val ACTION_STOP = "com.siriusdevops.onionwire.keepalive.STOP"
const val EXTRA_ONION = "onion"
private const val CHANNEL_ID = "keep-alive"
private const val NOTIFICATION_ID = 1
/** Characters of the onion address shown, prefix only. */
private const val ONION_PREFIX = 10
/**
* Brings up the keep-alive. Must be called while the app is visible —
* an unlock is, and that is the only caller — so the API 31+
* background-start restriction does not apply.
*/
fun start(context: Context, onion: String) {
val intent = Intent(context, KeepAliveService::class.java)
.putExtra(EXTRA_ONION, onion)
try {
context.startForegroundService(intent)
} catch (t: Throwable) {
// Same refusal as in the service, just one call earlier.
Log.w(TAG, "startForegroundService refused", t)
NodeHost.onKeepAliveRefused(t.message ?: t.toString())
}
}
/** Ends the keep-alive; `onDestroy()` reports the lost anchor. */
fun stop(context: Context) {
context.stopService(Intent(context, KeepAliveService::class.java))
}
}
}

View file

@ -0,0 +1,153 @@
package com.siriusdevops.onionwire.keepalive
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.Wire
import uniffi.onionwire_sdk.openWire
import java.io.File
/**
* How visible the keep-alive currently is, for the one line of battery honesty
* the roster shows.
*/
sealed interface KeepAliveStatus {
/** No foreground service. The node lives only while the app does. */
data object Off : KeepAliveStatus
/** A foreground service is holding the node, notification and all. */
data object On : KeepAliveStatus
/**
* The system refused the foreground start (API 31+ background-start rules,
* an OEM battery policy). The node is still up, but it dies with the app.
*/
data class Unavailable(val reason: String) : KeepAliveStatus
}
/**
* Process-wide owner of the single `Wire` node.
*
* Ownership rule: whoever opens the node hands the handle here, and **only this
* object ever calls `shutdown()` or `flush()` on it**. The ViewModel and
* [KeepAliveService] report lifecycle transitions; [NodeLifetime] decides
* whether the node survives, and this object executes that decision.
*
* That indirection is the point. `WireViewModel.onCleared()` used to shut the
* node down unconditionally, so a foreground service holding the same node
* would have been torn down by the first configuration change — or worse, the
* service would have kept a notification up for a node the UI had already
* killed. Neither side owns the node now; the policy does.
*
* Threading: every mutation runs on the main thread except the SDK call inside
* [open], which is dispatched to [Dispatchers.IO] and hops back.
*/
object NodeHost {
/**
* Teardown must outlive the object graph that asked for it: `onCleared()`
* runs *after* `viewModelScope` is already cancelled, and stopping the node
* means draining the outbox and stopping Arti, not dropping a reference.
* One process-wide scope is enough — there is one node per process.
*/
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val lifetime = NodeLifetime()
private var wire: Wire? = null
/**
* The in-flight teardown, if any. Re-opening 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.
*/
private var stopping: Job? = null
private val _keepAlive = MutableStateFlow<KeepAliveStatus>(KeepAliveStatus.Off)
val keepAlive: StateFlow<KeepAliveStatus> = _keepAlive.asStateFlow()
/** The live node, or null when locked. */
fun current(): Wire? = wire
/** The live node, or a hard error. Callers are UI paths that require unlock. */
fun requireOpen(): Wire = wire ?: error("locked")
/**
* Opens the node and anchors it to the UI.
*
* Suspends inside Arti's bootstrap — minutes on a cold start — so this must
* never run on the main thread. Callers are `viewModelScope` coroutines.
*/
suspend fun open(home: File, passphrase: String): Wire {
stopping?.join()
val opened = withContext(Dispatchers.IO) { openWire(home.absolutePath, passphrase) }
wire = opened
_keepAlive.value = KeepAliveStatus.Off
lifetime.onOpened()
return opened
}
/** The UI is going away: finish, task swipe, or process death. */
fun onUiDetached(): NodeAction = apply(lifetime.onUnanchored(NodeAnchor.UI))
/** The keep-alive reached the foreground with its notification. */
fun onKeepAliveStarted(): NodeAction {
_keepAlive.value = KeepAliveStatus.On
return apply(lifetime.onAnchored(NodeAnchor.KEEP_ALIVE))
}
/** The keep-alive stopped, or the system destroyed it. */
fun onKeepAliveStopped(): NodeAction {
if (_keepAlive.value is KeepAliveStatus.On) _keepAlive.value = KeepAliveStatus.Off
return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
/**
* `startForeground()` was refused. Nothing is anchoring the node at the OS
* level, so fail over to the honest pre-existing behaviour: the node lives
* as long as the app does, and the roster says why.
*/
fun onKeepAliveRefused(reason: String): NodeAction {
_keepAlive.value = KeepAliveStatus.Unavailable(reason)
return apply(lifetime.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
/**
* Explicit Lock, from the UI or the notification's Stop action. The caller
* stops the keep-alive first — a service that is still running would
* re-anchor a node that no longer exists.
*/
fun lock(): NodeAction = apply(lifetime.onLocked())
private fun apply(action: NodeAction): NodeAction {
when (action) {
NodeAction.Keep -> Unit
NodeAction.Flush -> scope.launch { runCatching { wire?.flush() } }
NodeAction.Stop -> stopNode()
}
return action
}
private fun stopNode() {
val dying = wire ?: return
wire = null
lifetime.onClosed()
// 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.
stopping = scope.launch {
runCatching { dying.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 { dying.shutdown() }
}
}
}

View file

@ -0,0 +1,99 @@
package com.siriusdevops.onionwire.keepalive
/**
* Who currently requires the in-process Tor node to stay alive.
*
* [UI] is a live `WireViewModel`; [KEEP_ALIVE] is a running [KeepAliveService].
* Both can be present at the same time — that is the interesting case: the
* screen can go away while the keep-alive stays up, and the node must survive
* it. This enum exists so "who owns the node" is a value, not a convention.
*/
enum class NodeAnchor {
UI,
KEEP_ALIVE,
}
/** What the caller must do to the node after reporting a transition. */
sealed interface NodeAction {
/** Nothing to do; the node's fate is unchanged. */
data object Keep : NodeAction
/** Drain the outbox, leave the node published. */
data object Flush : NodeAction
/** Drain the outbox, then `shutdown()`. The node is gone. */
data object Stop : NodeAction
}
/**
* Pure policy for the single node's lifetime: no Android, no coroutines, no
* SDK. The ViewModel and the foreground service both report transitions here
* and execute the returned [NodeAction].
*
* The rule the whole card turns on: **the UI going away does not stop the node
* while a keep-alive anchor is held.** Before this, `WireViewModel.onCleared()`
* called `shutdown()` unconditionally, which is exactly the bug a foreground
* service would have walked into.
*
* Threading: state is mutated only from the main thread — [NodeHost] is the
* only caller, and it hops back to the main thread after the SDK's blocking
* open. There is no lock here on purpose.
*/
class NodeLifetime {
private var open = false
private val anchors = LinkedHashSet<NodeAnchor>()
/** True between [onOpened] and [onClosed]/[onLocked]. */
val isOpen: Boolean get() = open
fun anchoredBy(anchor: NodeAnchor): Boolean = anchor in anchors
/**
* The unlock path opened a node. The UI is by definition present — the user
* typed the passphrase into it.
*/
fun onOpened(): NodeAction {
open = true
anchors.add(NodeAnchor.UI)
return NodeAction.Keep
}
/** Teardown finished; the node no longer exists. */
fun onClosed(): NodeAction {
open = false
anchors.clear()
return NodeAction.Keep
}
/** A keep-alive reached the foreground. */
fun onAnchored(anchor: NodeAnchor): NodeAction {
anchors.add(anchor)
return NodeAction.Keep
}
/**
* An anchor went away: the UI was destroyed, or the keep-alive stopped or
* was killed. Removing the anchor first means a repeat report (the service
* action and `onDestroy()` both fire) cannot double-count.
*/
fun onUnanchored(anchor: NodeAnchor): NodeAction {
anchors.remove(anchor)
if (!open) return NodeAction.Keep
// Flush rather than Keep when another anchor remains: the process may
// be killed at any moment once the screen is gone, and the outbox is
// the whole point of surviving that.
return if (anchors.isEmpty()) NodeAction.Stop else NodeAction.Flush
}
/**
* The user pressed Lock. Every anchor is dropped: a keep-alive that outlived
* an explicit lock would leave a notification pointing at a dead onion.
*/
fun onLocked(): NodeAction {
val wasOpen = open
open = false
anchors.clear()
return if (wasOpen) NodeAction.Stop else NodeAction.Keep
}
}

View file

@ -40,6 +40,7 @@ fun RosterScreen(
onion: String,
sdkVersion: String,
friends: List<FriendInfo>,
keepAliveNote: String?,
onOpenChat: (FriendInfo) -> Unit,
onShare: () -> Unit,
onPaste: () -> Unit,
@ -82,6 +83,14 @@ fun RosterScreen(
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (keepAliveNote != null) {
Spacer(Modifier.height(10.dp))
Text(
keepAliveNote,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
)
}
}
}

View file

@ -223,7 +223,9 @@ fun UnlockScreen(
Spacer(Modifier.height(24.dp))
Text(
"INTERNET is the only permission this app requests.",
"Permissions: internet, plus a foreground service and its notification so " +
"the onion stays reachable while the screen is off. No camera, contacts " +
"or storage.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)

View file

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Status-bar icon for the keep-alive notification. Notification icons are
alpha masks, so this is a flat white silhouette: an onion bulb with a sprout.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,2.6c-0.7,1.2 -1.1,2.3 -1.1,3.2 0,0.5 0.5,0.9 1.1,0.9s1.1,-0.4 1.1,-0.9c0,-0.9 -0.4,-2 -1.1,-3.2z" />
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,6.4c-2.2,2 -3.6,4.6 -3.6,7.3 0,3.9 1.6,7.3 3.6,7.3s3.6,-3.4 3.6,-7.3c0,-2.7 -1.4,-5.3 -3.6,-7.3zM12,8.2c1.1,1.3 2.1,3 2.1,5.5 0,1.5 -0.5,2.9 -1,3.3 -0.6,-0.4 -1.1,-1.8 -1.1,-3.3 0,-2.5 1,-4.2 2.1,-5.5z" />
</vector>

View file

@ -1,4 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">OnionWire</string>
<!--
Foreground keep-alive. The notification text is the only place the user
can see what is still running once the screen is off, so it names the
moving parts instead of saying "running in the background".
-->
<string name="keep_alive_channel_name">Node keep-alive</string>
<string name="keep_alive_channel_description">Shown while OnionWire keeps your onion address reachable in the background.</string>
<string name="keep_alive_title">OnionWire is reachable</string>
<string name="keep_alive_text">Tor and the outbox are running so peers can deliver messages.</string>
<string name="keep_alive_text_onion">Tor and the outbox are running so peers can reach %1$s…</string>
<string name="keep_alive_stop">Stop keep-alive</string>
<string name="keep_alive_note_off">Reachable only while this app is open.</string>
<string name="keep_alive_note_on">Kept alive — Tor and the outbox run until you tap Lock.</string>
<string name="keep_alive_note_hidden">Kept alive, but notifications are blocked, so the status notice is hidden. Android still lists the service in the Task Manager.</string>
<string name="keep_alive_note_unavailable">Not kept alive (%1$s). The node stops when the app does.</string>
</resources>

View file

@ -0,0 +1,130 @@
package com.siriusdevops.onionwire.keepalive
import com.siriusdevops.onionwire.keepalive.NodeAction.Flush
import com.siriusdevops.onionwire.keepalive.NodeAction.Keep
import com.siriusdevops.onionwire.keepalive.NodeAction.Stop
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The service-lifetime state machine, no device required: [NodeLifetime] is
* pure. Every case here is a transition the app actually produces — unlock,
* background, task swipe, notification Stop, explicit Lock, re-unlock.
*/
class NodeLifetimeTest {
@Test
fun ui_detach_with_no_keep_alive_stops_the_node() {
val l = NodeLifetime()
l.onOpened()
assertEquals(Stop, l.onUnanchored(NodeAnchor.UI))
assertTrue(l.isOpen) // the caller still has to run flush+shutdown
}
@Test
fun keep_alive_anchor_survives_ui_detach_and_only_flushes() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
// Task swiped: the activity is gone, the service is not.
assertEquals(Flush, l.onUnanchored(NodeAnchor.UI))
assertFalse(l.anchoredBy(NodeAnchor.UI))
assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
}
@Test
fun losing_the_last_anchor_stops_the_node() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onUnanchored(NodeAnchor.UI)
// Notification Stop, or the system killing the service.
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
@Test
fun service_stopping_while_the_ui_is_up_keeps_the_node() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
assertEquals(Flush, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
assertTrue(l.anchoredBy(NodeAnchor.UI))
assertTrue(l.isOpen)
}
@Test
fun repeated_anchor_loss_is_idempotent() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onUnanchored(NodeAnchor.UI)
// The Stop action and onDestroy both report the same loss.
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
l.onClosed()
assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
@Test
fun lock_drops_every_anchor() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
assertEquals(Stop, l.onLocked())
assertFalse(l.isOpen)
assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
assertFalse(l.anchoredBy(NodeAnchor.UI))
l.onClosed()
}
@Test
fun re_unlock_after_lock_starts_from_a_clean_slate() {
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onLocked()
l.onClosed()
// Second unlock: only the UI anchors, so backgrounding really stops.
assertEquals(Keep, l.onOpened())
assertFalse(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
assertEquals(Stop, l.onUnanchored(NodeAnchor.UI))
}
@Test
fun re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it() {
// Process relaunch with the service still up: the ViewModel adopts the
// live node and never calls onOpened(), so the KEEP_ALIVE anchor (and
// the node) is untouched by the new UI attaching.
val l = NodeLifetime()
l.onOpened()
l.onAnchored(NodeAnchor.KEEP_ALIVE)
l.onUnanchored(NodeAnchor.UI)
assertTrue(l.isOpen)
assertTrue(l.anchoredBy(NodeAnchor.KEEP_ALIVE))
assertFalse(l.anchoredBy(NodeAnchor.UI))
// The adopted UI leaves again: still flush, still alive.
assertEquals(Flush, l.onUnanchored(NodeAnchor.UI))
assertTrue(l.isOpen)
assertEquals(Stop, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
}
@Test
fun transitions_on_a_closed_node_do_nothing() {
val l = NodeLifetime()
assertEquals(Keep, l.onUnanchored(NodeAnchor.UI))
assertEquals(Keep, l.onUnanchored(NodeAnchor.KEEP_ALIVE))
assertEquals(Keep, l.onLocked())
assertEquals(Keep, l.onAnchored(NodeAnchor.KEEP_ALIVE)) // service up, still locked
}
}

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

View file

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

View file

@ -24,7 +24,7 @@ Original pass: rust-dev, no live hidden service / live wallet. Ignored tests
## Still true / not a “finding we forgot”
- Identity secret key and roster (pubkeys + locators) are **plaintext** in sqlite. Chat bodies are not. Seized laptop without FDE yields who you are and who you talk to.
- At rest the whole store is SQLCipher (Argon2id key over a 16-byte `store_salt`), so the identity secret key, roster (pubkeys + locators) and chat bodies are ciphertext on disk; chat bodies add a row-bound AEAD layer on top. That is not a defense against a live compromise or an attacker who has the passphrase — see [THREAT_MODEL.md](THREAT_MODEL.md).
- Arti onion services are experimental. Fail closed; no C-tor fallback.
- No public third-party audit, no `cargo-audit` gate in CI as of the original pass.
- Invite decode still accepts the legacy concat signature (compatibility).

View file

@ -54,7 +54,16 @@ dir (new identity); same disk caveat.
## Fail closed
Peer onion down → send fails. Fingerprint mismatch vs the pinned key → hard fail, no send. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
Peer onion down → a **chat** send is queued locally and retried (see “Local outbox (chat retry queue)”); file transfer and payment frames still fail immediately. Fingerprint mismatch vs the pinned key → hard fail, no send, never queued. Arti HS experimental: if it cannot publish, OnionWire stops; it does not fall back to C-tor.
## Local outbox (chat retry queue) is local, and it re-dials on a schedule
A chat send to an unreachable onion is written to an `outbox` row next to its `messages` row and retried in the background. There is no server-side queue: a queued message is never handed to a third party, and it dies with the device. Two consequences are real and are accepted:
- **Device seizure.** A pending (never-delivered) message sits in the same SQLCipher store as the rest of the history, under the same per-row AEAD and the same passphrase-derived key — no weaker, but also no shorter-lived. Seizure *with* the passphrase reveals messages that were never actually sent, including ones the sender may have moved on from; seizure without it reveals nothing in this store. `/wipe` clears outbox rows with the rest of chat history; `/wipe-all` removes them with the data dir. Neither is a forensic erase.
- **Retry cadence is a local traffic-analysis surface.** A queued send re-dials the peer's onion on a backoff schedule while the app runs. An observer of your Tor client (or the network in front of it) sees a repeating connection attempt to one onion on a predictable cadence — it does not learn the plaintext or the recipient identity, but it can infer that you have an undelivered message for someone, and roughly when you composed it. The backoff is per-row, capped at one attempt per 30 min per message, and stops after 8 attempts or on a terminal failure.
The queue is bounded in scope: chat only. File transfer and `rcp` frames are one-shot, so a failed payment claim does not sit in the store being retried forever.
## Profile is friend-visible, not a directory
@ -64,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.
@ -95,5 +116,7 @@ the peer already knows the plaintext they sent.
## Out of v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,
A/V.
Prosody, XMPP, s2s, MAM, carbons, a **server-side** outbox / store-and-forward
relay, multi-device, DHT / name server, A/V. The local retry queue of the
previous section is not an outbox in the XMPP sense: it never leaves the device.

View file

@ -351,6 +351,16 @@ Else RGB as today.
| box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` |
| alert prefix | `! ` | `! ` |
| stale | word `stale` | `stale` |
| delivery: delivered | `✓` | `ok` |
| delivery: queued | `◷` | (word) `queued` |
| delivery: sending | `»` | (word) `sending` |
| delivery: failed | `✗` | (word) `failed` |
`queued` / `sending` / `failed` always carry their state word, so the ASCII
fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it
falls back to `ok`. `delivery_glyph()` /
`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the
fallback path.
No emoji. `onion_glyph()` stays for callers that already use it; do not put it
on the main header.
@ -401,6 +411,9 @@ Do not soften fail-closed into a loader.
| sending | `sending` (keep, no spinner) |
| sent | `sent` |
| peer down / send err | `send failed: {e}` (visible) |
| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding |
| queued + terminal failure | `{n} queued, send failed: {short}` |
| terminal failure | `send failed: {short}` (`{f} failed` when more than one) |
| already sending | `already sending` (keep) |
| stale friend | `stale` suffix (keep) |
| empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` |
@ -570,3 +583,41 @@ cargo test --locked --test tui_spec -- --nocapture dump_spec_frames
Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is
`no messages` / `type below, Enter sends`; paste error is `{err}` then
`Enter resubmits Esc back`; alerts truncate to the frame width.
## Delivery state (outbox) — implemented
Per-message state, read from the local outbox. The states are the store's own
(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire
prefix, no server.
| Row | Marker |
|---|---|
| delivered | `you: ping ✓` |
| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` |
| sending | `you: pong » sending` |
| failed | `you: pong ✗ failed: connection timed out` |
| inbound | `them: pong` (no marker) |
- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` /
`retry now` comes from the stored absolute `next_attempt_at`.
- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and
capped at 24 cells (`short_send_reason`).
- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a
fail-closed `send failed: {short}` statement (with `! ` when colour is off).
- The tag trails the body and wraps with it, so it is never clipped away.
Correlation: a delivered row is deleted from the outbox, so an outbound message
with no row is `Sent`; pending rows are joined to messages on the row id —
`store::Message::id` equals `OutboxEntry::message_id` (`chat_with_delivery`).
Two identical bodies are distinct rows with distinct ids, so the marker always
lands on the row that actually owns the outbox entry.
### Size floor / target
- **Floor: 80x24.** Everything above must render there.
- **Target: 120x40.**
- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping`
draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat
and footer row is `<=` the terminal width, that the markers render, and that
an over-long message wraps instead of being clipped.
- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`.

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>

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

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

View file

@ -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,12 +9,14 @@ use futures::StreamExt;
use futures::io::{AsyncRead, AsyncWrite};
use tor_cell::relaycell::msg::Connected;
use tor_hsservice::{RunningOnionService, handle_rend_requests};
use zeroize::Zeroizing;
use crate::dispatch::{self, Kind};
use crate::file;
use crate::frame;
use crate::hs::{self, Client, HS_PORT};
use crate::hs::{self, Client, HS_PORT, TorState};
use crate::loc;
use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus};
use crate::pay;
use crate::profile;
use crate::qr;
@ -28,8 +31,27 @@ pub struct RotateResult {
pub friends: usize,
}
/// What a `flush` actually managed to do, for UI surfacing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlushOutcome {
/// Outbox rows we tried to deliver in this pass.
pub attempted: usize,
/// Rows delivered now — their outbox rows are gone.
pub delivered: usize,
/// Rows still queued or terminally failed after the pass.
pub remaining: usize,
}
/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead
/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and
/// the retry worker picks it up on its normal schedule.
pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30);
/// The drain inside `shutdown` gets a shorter budget: teardown must not hang
/// the caller behind a Tor dial. Undelivered rows survive in sqlite.
pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10);
struct HsHandle {
_svc: Arc<RunningOnionService>,
svc: Arc<RunningOnionService>,
rend: tokio::task::JoinHandle<()>,
}
@ -39,9 +61,18 @@ impl Drop for HsHandle {
}
}
/// Abort the outbox worker when the node goes away.
struct WorkerHandle(tokio::task::JoinHandle<()>);
impl Drop for WorkerHandle {
fn drop(&mut self) {
self.0.abort();
}
}
pub struct Node {
home: PathBuf,
store: Mutex<Store>,
store: Arc<Mutex<Store>>,
client: Client,
hs: Mutex<Option<HsHandle>>,
onion: Mutex<String>,
@ -49,16 +80,30 @@ pub struct Node {
wallet: Wallet,
incoming_limit: Mutex<TokenBucket>,
inbox: Mutex<file::Inbox>,
outbox: Arc<Outbox>,
worker: Mutex<Option<WorkerHandle>>,
/// Set by `shutdown`. Checked before any operation that would touch Tor or
/// the store, so a stopped node fails cleanly instead of dialing.
stopped: AtomicBool,
/// Has this node's onion service ever crossed the reachability bar (status
/// `Running`/`DegradedReachable`, or a successful probe of our own onion)?
/// Arti's combined status can stay `Bootstrapping` for minutes *after* the
/// descriptor is downloadable, so without this the UI would keep saying
/// "starting" long past the point where friends can reach us. Cleared when
/// `rotate` hard-cuts the service.
onion_reachable: AtomicBool,
}
impl Node {
pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> {
let pass = std::env::var("ONIONWIRE_STORE_PASSPHRASE")
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?;
let pass = Zeroizing::new(
std::env::var("ONIONWIRE_STORE_PASSPHRASE")
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?,
);
if pass.is_empty() {
return Err("empty passphrase".into());
}
Self::start_with_passphrase(home, &pass).await
Self::start_with_passphrase(home, pass.as_str()).await
}
pub async fn start_with_passphrase(
@ -79,9 +124,17 @@ impl Node {
let (svc, rend) = launched;
let onion = hs::onion_string(&svc)?;
let inbox = file::Inbox::new(home.join("inbox"));
let store = Arc::new(Mutex::new(store));
let outbox = Arc::new(Outbox::new(
Arc::clone(&store),
Arc::new(ArtiDeliverer::new(client.clone(), keys.clone())),
));
if let Err(e) = outbox.reset_stale() {
eprintln!("outbox: {e}");
}
let node = Arc::new(Self {
home,
store: Mutex::new(store),
store,
client,
hs: Mutex::new(None),
onion: Mutex::new(onion.clone()),
@ -89,15 +142,26 @@ impl Node {
wallet: Wallet::from_env(),
incoming_limit: Mutex::new(TokenBucket::default()),
inbox: Mutex::new(inbox),
outbox: Arc::clone(&outbox),
worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))),
stopped: AtomicBool::new(false),
onion_reachable: AtomicBool::new(false),
});
// Unlock trigger: flush anything queued by a previous run now, in the
// background, rather than waiting out its backoff.
spawn_flush_all(Arc::clone(&node.outbox));
// Accept rens before waiting so a reachability probe can succeed
// while combined status is still Bootstrapping.
let rend = spawn_rend(Arc::clone(&node), rend);
*node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
_svc: Arc::clone(&svc),
svc: Arc::clone(&svc),
rend,
});
hs::wait_until_published(&node.client, &svc, &onion).await?;
// Published by the same bar `wait_until_published` uses — a probe
// success counts, which is the whole reason `tor_state` tracks it
// separately from Arti's (slower, flappier) combined status.
node.onion_reachable.store(true, Ordering::SeqCst);
node.store
.lock()
.map_err(|e| e.to_string())?
@ -106,6 +170,148 @@ 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) {
let store = match self.store.lock() {
Ok(s) => s,
Err(e) => {
eprintln!("wal checkpoint: store lock poisoned: {e}");
return;
}
};
if let Err(e) = store.checkpoint_wal() {
eprintln!("wal checkpoint: {e}");
}
}
fn ensure_running(&self) -> Result<(), String> {
if self.stopped.load(Ordering::SeqCst) {
return Err("node is stopped — open the identity again".to_string());
}
Ok(())
}
pub fn onion(&self) -> String {
self.onion.lock().map(|g| g.clone()).unwrap_or_default()
}
@ -406,6 +612,7 @@ impl Node {
}
async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
self.ensure_running()?;
let (onion, prekey) = {
let f = self.friend(friend_pk)?;
if f.prekey.len() != 32 {
@ -416,7 +623,10 @@ impl Node {
self.try_send(&onion, friend_pk, &prekey, plaintext).await
}
/// Dial a peer's onion. Success is evidence the peer is up, which is one of
/// the outbox retry triggers.
pub async fn connect_onion(&self, onion: &str) -> Result<(), String> {
self.ensure_running()?;
tokio::time::timeout(
Duration::from_secs(20),
self.client.connect((onion, HS_PORT)),
@ -424,10 +634,19 @@ impl Node {
.await
.map_err(|_| format!("connect {onion}:{HS_PORT} timed out"))?
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
if let Ok(Some(friend)) = self
.store
.lock()
.map_err(|e| e.to_string())
.and_then(|s| s.friend_by_onion(onion).map_err(|e| e.to_string()))
{
spawn_flush_friend(Arc::clone(&self.outbox), friend.pubkey);
}
Ok(())
}
pub async fn rotate(self: &Arc<Self>) -> Result<RotateResult, String> {
self.ensure_running()?;
let old_nick = self
.store
.lock()
@ -444,12 +663,16 @@ impl Node {
let onion = hs::onion_string(&svc)?;
// ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping.
*self.hs.lock().map_err(|e| e.to_string())? = None;
// The new service is not reachable until it publishes: the locator in
// flight is dead until then, so do not carry the old verdict over.
self.onion_reachable.store(false, Ordering::SeqCst);
let rend = spawn_rend(Arc::clone(self), rend);
*self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle {
_svc: Arc::clone(&svc),
svc: Arc::clone(&svc),
rend,
});
hs::wait_until_published(&self.client, &svc, &onion).await?;
self.onion_reachable.store(true, Ordering::SeqCst);
{
let store = self.store.lock().map_err(|e| e.to_string())?;
store.set_onion(&onion).map_err(|e| e.to_string())?;
@ -506,36 +729,31 @@ impl Node {
Ok(name)
}
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> {
let (onion, prekey) = {
let store = self.store.lock().map_err(|e| e.to_string())?;
let f = store
.get_friend(friend_pk)
.map_err(|e| e.to_string())?
.ok_or_else(|| "unknown friend".to_string())?;
if f.prekey.len() != 32 {
return Err("friend missing prekey".into());
}
(f.onion, f.prekey)
};
let deadline = Instant::now() + Duration::from_secs(180);
let mut last = None::<String>;
while Instant::now() < deadline {
match self.try_send(&onion, friend_pk, &prekey, plaintext).await {
Ok(()) => {
self.store
.lock()
.map_err(|e| e.to_string())?
.append_message(friend_pk, "out", plaintext)
.map_err(|e| e.to_string())?;
return Ok(());
}
Err(e) if e.contains("fingerprint mismatch") => return Err(e),
Err(e) => last = Some(e),
}
tokio::time::sleep(Duration::from_secs(3)).await;
}
Err(last.unwrap_or_else(|| "send timed out".into()))
/// Send one chat message. Returns `Sent` when it went out now and `Queued`
/// when the peer's onion is unreachable — the outbox worker then retries with
/// backoff. A real protocol error (signature mismatch, unknown/short/oversize
/// frame) still fails immediately and is never retried.
pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<OutboxStatus, String> {
self.ensure_running()?;
self.outbox.send(friend_pk, plaintext).await
}
/// Pending and failed outbox rows for a friend, for UI surfacing.
/// Delivered rows are dropped, so a message absent here was sent.
pub fn outbox_pending(&self, friend_pk: &[u8]) -> Result<Vec<crate::store::OutboxEntry>, String> {
self.outbox.pending(friend_pk)
}
pub fn outbox_status_of_message(
&self,
message_id: i64,
) -> Result<Option<OutboxStatus>, String> {
self.outbox.status_of_message(message_id)
}
/// Foreground/unlock trigger: try every outstanding queued send now.
pub fn flush_outbox(&self) {
spawn_flush_all(Arc::clone(&self.outbox));
}
async fn push_loc(
@ -568,20 +786,10 @@ impl Node {
remote_prekey: &[u8],
plaintext: &[u8],
) -> Result<(), String> {
let mut stream = self
.client
.connect((onion, HS_PORT))
self.outbox
.deliverer()
.deliver(onion, pinned_id, remote_prekey, plaintext)
.await
.map_err(|e| format!("connect {onion}:{HS_PORT}: {e}"))?;
let keys = self.keys()?;
let mut sess = session::handshake_initiator(&mut stream, &keys, pinned_id, remote_prekey)
.await
.map_err(session_err)?;
let ct = sess.encrypt(plaintext).map_err(session_err)?;
frame::write_frame(&mut stream, &ct)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
async fn handle_incoming<S>(&self, stream: &mut S) -> Result<(), String>
@ -598,6 +806,9 @@ impl Node {
})
.await
.map_err(session_err)?;
// Trigger (c): the peer just proved they are online. Try their queued
// sends now instead of waiting out the backoff, off this stream's path.
spawn_flush_friend(Arc::clone(&self.outbox), sess.peer_identity.clone());
let ct = frame::read_frame(stream).await.map_err(|e| e.to_string())?;
let pt = sess.decrypt(&ct).map_err(session_err)?;
match dispatch::classify(&pt) {
@ -814,6 +1025,24 @@ fn spawn_rend(
})
}
/// Foreground/unlock flush: every outstanding queued send gets one attempt now.
fn spawn_flush_all(outbox: Arc<Outbox>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_all(unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
/// We just saw this peer (handshake or successful dial): try their queue now.
fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
tokio::spawn(async move {
if let Err(e) = outbox.flush_friend(&friend_pk, unix_now()).await {
eprintln!("outbox: {e}");
}
});
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")
@ -856,3 +1085,4 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
}
false
}

308
src/outbox.rs Normal file
View file

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

View file

@ -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;
@ -35,6 +36,16 @@ impl Error {
pub fn is_fingerprint_mismatch(&self) -> bool {
self.mismatch
}
/// String for the UI: a pinned-identity mismatch gets the documented banner,
/// everything else is the underlying snow/framing message.
pub fn into_message(self) -> String {
if self.mismatch {
crate::tui::fingerprint_mismatch_banner().to_string()
} else {
self.msg
}
}
}
impl std::fmt::Display for Error {
@ -51,11 +62,15 @@ impl From<snow::Error> for Error {
}
}
#[derive(Clone)]
/// Local secret keys. `Clone` copies the secrets, but the copy is itself
/// `ZeroizeOnDrop`, so no clone outlives its owner un-wiped.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct Keys {
pub identity_sk: [u8; 32],
#[zeroize(skip)]
pub identity_pk: [u8; 32],
pub prekey_sk: [u8; 32],
#[zeroize(skip)]
pub prekey_pk: [u8; 32],
}
@ -121,7 +136,7 @@ pub fn handshake_pinned(init: &Keys, resp: &Keys, pinned: &[u8; 32]) -> Result<(
.prologue(PROLOGUE)?
.build_responder()?;
let mut buf = vec![0u8; MSG_BUF];
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let n = initiator.write_message(&[], &mut buf)?;
let msg1 = buf[..n].to_vec();
let n = responder.read_message(&msg1, &mut buf)?;
@ -190,7 +205,7 @@ where
.prologue(PROLOGUE)?
.build_initiator()?;
let mut buf = vec![0u8; MSG_BUF];
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let n = hs.write_message(&[], &mut buf)?;
crate::frame::write_frame(stream, &buf[..n])
.await
@ -244,7 +259,7 @@ where
.prologue(PROLOGUE)?
.build_responder()?;
let mut buf = vec![0u8; MSG_BUF];
let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let msg1 = crate::frame::read_frame(stream)
.await
.map_err(|e| Error::new(e.to_string()))?;

View file

@ -9,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>;
@ -41,16 +42,26 @@ impl From<String> for Error {
}
}
pub struct Store {
conn: Connection,
msg_key: [u8; 32],
/// The store error is a message and nothing else, and the rest of the crate
/// (transport, UI) already speaks `String`. Lossless, so `?` is enough at the
/// outbox boundary — no per-call `map_err`.
impl From<Error> for String {
fn from(e: Error) -> Self {
e.0
}
}
pub struct Store {
conn: Connection,
msg_key: Zeroizing<[u8; 32]>,
}
/// The identity row. Secret halves wipe when this is dropped.
pub struct SelfIdentity {
pub identity_sk: Vec<u8>,
pub identity_sk: Zeroizing<Vec<u8>>,
pub identity_pk: Vec<u8>,
pub onion: String,
pub prekey_sk: Vec<u8>,
pub prekey_sk: Zeroizing<Vec<u8>>,
pub prekey_pk: Vec<u8>,
}
@ -72,6 +83,9 @@ pub struct FriendProfile {
#[derive(Debug)]
pub struct Message {
/// `messages.id` row id. The outbox row for a send carries the same
/// `message_id`, so the UI can join exactly instead of matching bodies.
pub id: i64,
pub dir: String,
pub plaintext: Vec<u8>,
}
@ -89,6 +103,64 @@ pub struct Payment {
pub created_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutboxStatus {
Queued,
Sending,
Sent,
/// Terminal: transport or protocol failure that will not be retried.
Failed(String),
}
impl OutboxStatus {
pub fn is_terminal(&self) -> bool {
matches!(self, OutboxStatus::Sent | OutboxStatus::Failed(_))
}
/// Column encoding for the `outbox.status` CHECK constraint.
pub fn as_db_str(&self) -> &'static str {
match self {
OutboxStatus::Queued => "queued",
OutboxStatus::Sending => "sending",
OutboxStatus::Sent => "sent",
OutboxStatus::Failed(_) => "failed",
}
}
pub fn from_db(status: &str, last_error: Option<&str>) -> Self {
match status {
"sending" => OutboxStatus::Sending,
"sent" => OutboxStatus::Sent,
"failed" => OutboxStatus::Failed(last_error.unwrap_or("failed").to_string()),
_ => OutboxStatus::Queued,
}
}
}
impl std::fmt::Display for OutboxStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OutboxStatus::Failed(why) => write!(f, "failed: {why}"),
other => f.write_str(other.as_db_str()),
}
}
}
/// One queued chat send. The body is not copied: it lives in the `messages`
/// row the outbox row points at, under that row's own AEAD.
#[derive(Debug, Clone)]
pub struct OutboxEntry {
pub id: i64,
pub friend_pk: Vec<u8>,
pub message_id: i64,
pub body: Vec<u8>,
pub attempts: u32,
pub next_attempt_at: i64,
pub created_at: i64,
pub status: OutboxStatus,
pub last_error: Option<String>,
}
pub struct PaymentWrite<'a> {
pub dir: &'a str,
pub kind: &'a str,
@ -109,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> {
@ -190,6 +263,18 @@ impl Store {
verified INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY,
friend_id INTEGER NOT NULL REFERENCES friends(id),
message_id INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
next_attempt_at INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')),
last_error TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
",
)?;
@ -199,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()?;
@ -275,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()));
}
@ -285,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],
@ -384,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(
@ -402,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],
)?;
}
}
@ -416,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)?,
})
},
@ -476,6 +564,20 @@ impl Store {
.map_err(Into::into)
}
/// Locator → friend. Onions are not unique in the schema (a stale row can
/// hold a rotated address), so the first match wins; the outbox uses this
/// only to pick which queue to flush early.
pub fn friend_by_onion(&self, onion: &str) -> Result<Option<Friend>> {
self.conn
.query_row(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends WHERE onion = ?1 ORDER BY id LIMIT 1",
params![onion],
friend_from_row,
)
.optional()
.map_err(Into::into)
}
pub fn list_friends(&self) -> Result<Vec<Friend>> {
let mut stmt = self.conn.prepare(
"SELECT pubkey, fingerprint, petname, onion, last_connect_ok, prekey FROM friends
@ -700,6 +802,17 @@ impl Store {
}
pub fn append_message(&self, friend_pk: &[u8], dir: &str, plaintext: &[u8]) -> Result<()> {
self.append_message_id(friend_pk, dir, plaintext).map(|_| ())
}
/// Same as `append_message`, returning the row id so an outbox row can
/// point at the body instead of storing a second copy.
pub fn append_message_id(
&self,
friend_pk: &[u8],
dir: &str,
plaintext: &[u8],
) -> Result<i64> {
if dir != "in" && dir != "out" {
return Err(Error("dir must be in or out".into()));
}
@ -724,7 +837,7 @@ impl Store {
params![blob, row_id],
)?;
tx.commit()?;
Ok(())
Ok(row_id)
}
pub fn list_messages(&self, friend_pk: &[u8]) -> Result<Vec<Message>> {
@ -748,14 +861,228 @@ impl Store {
let aad = message_aad(friend_id, &dir, id);
let plaintext = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("message decrypt failed".into()))?;
out.push(Message { dir, plaintext });
out.push(Message {
id,
dir,
plaintext,
});
}
Ok(out)
}
/// Queue one already-stored chat message for retry. `next_attempt_at` is an
/// absolute unix second; `now` is used for created_at/updated_at so the
/// caller and the row agree on the clock.
pub fn enqueue_outbox(
&self,
friend_pk: &[u8],
message_id: i64,
attempts: u32,
next_attempt_at: i64,
last_error: &str,
now: i64,
) -> Result<i64> {
let friend_id: i64 = self
.conn
.query_row(
"SELECT id FROM friends WHERE pubkey = ?1",
params![friend_pk],
|row| row.get(0),
)
.map_err(|_| Error("friend not found".into()))?;
self.conn.execute(
"INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 'queued', ?5, ?6, ?6)",
params![friend_id, message_id, attempts, next_attempt_at, last_error, now],
)?;
Ok(self.conn.last_insert_rowid())
}
/// Rows whose backoff has elapsed: the timer trigger for the worker.
pub fn due_outbox(&self, now: i64, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status = 'queued' AND o.next_attempt_at <= ?1
ORDER BY o.next_attempt_at, o.id LIMIT ?2"
),
params![now, limit],
)
}
/// Unscheduleable rows for one friend (queued or mid-attempt): the
/// "we just heard from this peer" trigger, which ignores the backoff.
pub fn outbox_for_friend(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending')
ORDER BY o.id"
),
params![friend_pk],
)
}
/// Every row the worker may still try: the unlock/foreground trigger.
pub fn all_pending_outbox(&self, limit: i64) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE o.status IN ('queued','sending')
ORDER BY o.next_attempt_at, o.id LIMIT ?1"
),
params![limit],
)
}
/// Pending and failed rows for one friend — what a UI shows as not-yet-sent.
/// Delivered rows are deleted, so absence means "sent".
pub fn pending_outbox(&self, friend_pk: &[u8]) -> Result<Vec<OutboxEntry>> {
self.outbox_query(
&format!(
"{OUTBOX_SELECT} WHERE f.pubkey = ?1 AND o.status IN ('queued','sending','failed')
ORDER BY o.id"
),
params![friend_pk],
)
}
pub fn outbox_status_of_message(&self, message_id: i64) -> Result<Option<OutboxStatus>> {
let row: Option<(String, Option<String>)> = self
.conn
.query_row(
"SELECT status, last_error FROM outbox WHERE message_id = ?1 ORDER BY id DESC LIMIT 1",
params![message_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
Ok(row.map(|(s, e)| OutboxStatus::from_db(&s, e.as_deref())))
}
pub fn mark_outbox_sending(&self, id: i64, now: i64) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'sending', updated_at = ?1 WHERE id = ?2",
params![now, id],
)?;
Ok(())
}
/// Delivered. The row is dropped — the chat history is the record, and a
/// per-message status table would grow without bound.
pub fn mark_outbox_sent(&self, id: i64) -> Result<()> {
self.conn
.execute("DELETE FROM outbox WHERE id = ?1", params![id])?;
Ok(())
}
pub fn mark_outbox_failed(&self, id: i64, now: i64, why: &str) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'failed', last_error = ?1, updated_at = ?2 WHERE id = ?3",
params![why, now, id],
)?;
Ok(())
}
pub fn mark_outbox_retry(
&self,
id: i64,
attempts: u32,
next_attempt_at: i64,
now: i64,
why: &str,
) -> Result<()> {
self.conn.execute(
"UPDATE outbox SET status = 'queued', attempts = ?1, next_attempt_at = ?2, last_error = ?3, updated_at = ?4 WHERE id = ?5",
params![attempts, next_attempt_at, why, now, id],
)?;
Ok(())
}
/// A row left in 'sending' means we died mid-attempt. Requeue on unlock.
pub fn reset_sending_outbox(&self) -> Result<usize> {
let n = self.conn.execute(
"UPDATE outbox SET status = 'queued' WHERE status = 'sending'",
[],
)?;
Ok(n)
}
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(args, |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, Vec<u8>>(1)?,
row.get::<_, i64>(2)?,
row.get::<_, i64>(3)?,
row.get::<_, i64>(4)?,
row.get::<_, String>(5)?,
row.get::<_, Option<String>>(6)?,
row.get::<_, i64>(7)?,
row.get::<_, i64>(8)?,
row.get::<_, String>(9)?,
row.get::<_, Vec<u8>>(10)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (
id,
friend_pk,
message_id,
attempts,
next_attempt_at,
status,
last_error,
created_at,
m_friend_id,
dir,
blob,
) = row?;
let aad = message_aad(m_friend_id, &dir, message_id);
let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad)
.map_err(|_| Error("outbox body decrypt failed".into()))?;
out.push(OutboxEntry {
id,
friend_pk,
message_id,
body,
attempts: attempts as u32,
next_attempt_at,
created_at,
status: OutboxStatus::from_db(&status, last_error.as_deref()),
last_error,
});
}
Ok(out)
}
/// Fold the WAL into the main db file and truncate it.
///
/// Runs on this store's own keyed connection: a second, unkeyed connection
/// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint
/// has to happen here, not from `node.rs`.
///
/// 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.
pub fn checkpoint_wal(&self) -> Result<()> {
let (busy, log, checkpointed): (i64, i64, i64) =
self.conn
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})?;
if busy != 0 {
// Another connection is reading/writing: pages are still safe in the
// WAL, they just were not moved this time.
return Err(Error(format!(
"busy ({checkpointed}/{log} pages moved, another connection active)"
)));
}
Ok(())
}
/// Drop chat + payments history. Identity + friends stay.
/// Not a forensic erase: SSD wear-leveling can keep copies.
pub fn wipe_messages(&self) -> Result<()> {
self.conn.execute("DELETE FROM outbox", [])?;
self.conn.execute(
"UPDATE messages SET plaintext = zeroblob(length(plaintext))",
[],
@ -763,7 +1090,7 @@ impl Store {
self.conn.execute("DELETE FROM messages", [])?;
self.conn.execute("DELETE FROM payments", [])?;
self.conn.execute_batch("VACUUM")?;
self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
self.checkpoint_wal()?;
Ok(())
}
@ -810,10 +1137,10 @@ 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
@ -913,7 +1240,7 @@ fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connec
/// 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))?;
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");
@ -925,8 +1252,10 @@ fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
Ok(conn)
}
fn pragma_key(key: &[u8; 32]) -> String {
format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key))
/// 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
@ -961,10 +1290,11 @@ fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &s
let conn = Connection::open(db_path)?;
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
let target = tmp.to_string_lossy().replace('\'', "''");
conn.execute_batch(&format!(
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;")?;
}
@ -1005,29 +1335,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))
}
}
}
@ -1041,6 +1371,12 @@ fn mkdir_700(path: &Path) -> Result<()> {
Ok(())
}
/// Base projection for outbox rows: the body comes from the `messages` row the
/// outbox row points at, so it stays under that row's AEAD + AAD.
const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \
o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \
FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id";
/// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64
fn message_aad(friend_id: i64, dir: &str, row_id: i64) -> Vec<u8> {
let mut aad = Vec::with_capacity(6 + 8 + dir.len() + 1 + 8);
@ -1066,6 +1402,48 @@ fn fingerprint(pubkey: &[u8]) -> String {
#[cfg(test)]
mod at_rest {
use super::*;
use zeroize::Zeroize;
/// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has
/// to run on the store's own keyed connection: a second, unkeyed one cannot
/// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently
/// never happened.
#[test]
fn checkpoint_wal_truncates_an_encrypted_store_wal() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap();
let pk = [3u8; 32];
store.upsert_friend(&pk, "peer.onion", None).unwrap();
for _ in 0..64 {
store.append_message(&pk, "out", &[7u8; 512]).unwrap();
}
let wal = dir.path().join("onionwire.db-wal");
let before = std::fs::metadata(&wal).expect("wal file").len();
assert!(before > 0, "expected pending WAL frames, got {before}");
store.checkpoint_wal().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)");
// A checkpoint moves pages into the db; it never drops committed data.
assert_eq!(store.list_messages(&pk).unwrap().len(), 64);
}
#[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() {
@ -1303,10 +1681,10 @@ mod at_rest {
.unwrap();
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
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 wrap = crate::backup::kdf(passphrase, &salt).unwrap();
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key, b"").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],
@ -1356,7 +1734,10 @@ mod at_rest {
);
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);
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");

View file

@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::io::{self, IsTerminal};
use std::sync::{Arc, mpsc};
use std::time::Duration;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout, Rect};
@ -8,11 +9,13 @@ 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;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile};
use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
const C_TEXT: Color = Color::Rgb(196, 214, 176);
@ -116,6 +119,200 @@ pub fn empty_friend_chat_text() -> &'static str {
"no messages\ntype below, Enter sends"
}
// ---------------------------------------------------------------------------
// Delivery state (outbox)
//
// The outbox is the only source of per-message state: `Queued` / `Sending` /
// `Failed` rows are what `Node::outbox_pending` still holds, and a row is
// deleted the moment the send crosses the circuit — so an outbound message with
// no row is `Sent`. No parallel state model, no new wire prefix.
// ---------------------------------------------------------------------------
/// Longest short-form failure reason shown in a chat row.
pub const FAIL_REASON_BUDGET: usize = 24;
/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the
/// wordless delivered state; `queued` / `sending` / `failed` already carry their
/// word, so their glyph is dropped rather than invented.
pub fn delivery_glyph(status: &OutboxStatus) -> &'static str {
let ascii = ascii_chrome();
match status {
OutboxStatus::Sent => {
if ascii {
"ok"
} else {
"✓"
}
}
OutboxStatus::Queued => {
if ascii {
""
} else {
"◷"
}
}
OutboxStatus::Sending => {
if ascii {
""
} else {
"»"
}
}
OutboxStatus::Failed(_) => {
if ascii {
""
} else {
"✗"
}
}
}
}
/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the
/// outbox stores.
pub fn retry_in_text(next_in_secs: i64) -> String {
if next_in_secs <= 0 {
"retry now".to_string()
} else if next_in_secs < 60 {
format!("retry {next_in_secs}s")
} else {
format!("retry {}m", (next_in_secs + 59) / 60)
}
}
/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain,
/// capped at `budget` cells so one peer's error cannot blow out the row.
pub fn short_send_reason(why: &str, budget: usize) -> String {
let clean = sanitize::display_text(why.as_bytes());
let tail = clean.rsplit(": ").next().unwrap_or("").trim();
let text = if tail.is_empty() { clean.trim() } else { tail };
truncate_chars(text, budget)
}
/// One row's delivery marker, straight from the outbox state.
pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String {
let glyph = delivery_glyph(status);
let body = match status {
OutboxStatus::Sent => String::new(),
OutboxStatus::Queued => format!(
"queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})",
retry_in_text(next_in_secs)
),
OutboxStatus::Sending => "sending".to_string(),
OutboxStatus::Failed(why) => {
format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET))
}
};
match (glyph.is_empty(), body.is_empty()) {
(_, true) => glyph.to_string(),
(true, false) => body,
(false, false) => format!("{glyph} {body}"),
}
}
/// Footer summary derived from the outbox rows of the selected friend.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct OutboxSummary {
/// `Queued` + `Sending`: rows the worker may still deliver.
pub queued: usize,
/// Terminal failures — these never retry.
pub failed: usize,
/// First terminal failure, for the fail-closed footer copy.
pub first_error: Option<String>,
}
impl OutboxSummary {
/// Footer note, or `None` when nothing is outstanding. Any terminal failure
/// keeps a `send failed` statement so the fail-closed copy stays visible.
pub fn note(&self) -> Option<String> {
let reason = || {
short_send_reason(
self.first_error.as_deref().unwrap_or("unknown"),
FAIL_REASON_BUDGET,
)
};
match (self.queued, self.failed) {
(0, 0) => None,
(queued, 0) => Some(format!("{queued} queued")),
(0, 1) => Some(format!("send failed: {}", reason())),
(0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())),
(queued, _) => Some(format!("{queued} queued, send failed: {}", reason())),
}
}
}
/// Chat transcript with per-message delivery state, plus the footer summary.
///
/// Pending rows are joined to messages on `Message::id` /
/// `OutboxEntry::message_id` — never on the body. Two identical bodies are
/// distinct rows with distinct ids, so the marker always lands on the row that
/// actually owns the outbox entry.
pub fn chat_with_delivery(
msgs: &[Message],
pending: &[OutboxEntry],
now: i64,
) -> (Vec<String>, OutboxSummary) {
let mut summary = OutboxSummary::default();
for entry in pending {
match &entry.status {
OutboxStatus::Failed(why) => {
summary.failed += 1;
summary.first_error.get_or_insert_with(|| why.clone());
}
_ => summary.queued += 1,
}
}
if msgs.is_empty() {
return (
empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
summary,
);
}
// One row per message in practice (a retry updates its row, not inserts a
// second), and `pending` is ordered by row id, so a hypothetical duplicate
// resolves to the newest — the same rule the store's own
// `outbox_status_of_message` uses.
let by_id: HashMap<i64, &OutboxEntry> =
pending.iter().map(|entry| (entry.message_id, entry)).collect();
let mut tags: Vec<Option<String>> = vec![None; msgs.len()];
for (i, msg) in msgs.iter().enumerate() {
if msg.dir != "out" {
continue;
}
if let Some(entry) = by_id.get(&msg.id) {
tags[i] = Some(delivery_tag(
&entry.status,
entry.attempts,
entry.next_attempt_at - now,
));
}
}
let lines = msgs
.iter()
.enumerate()
.map(|(i, msg)| {
let side = if msg.dir == "out" { "you" } else { "them" };
let body = sanitize::display_text(&msg.plaintext);
let tag = match tags[i].clone() {
Some(tag) => tag,
None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0),
None => String::new(),
};
if tag.is_empty() {
format!("{side}: {body}")
} else {
format!("{side}: {body} {tag}")
}
})
.collect();
(lines, summary)
}
/// Paste overlay copy. Error keeps the resubmit hint.
pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String {
let hint = match err {
@ -761,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\
@ -840,8 +1109,7 @@ enum Screen {
Passphrase {
kind: BackupKind,
path: String,
first: Option<String>,
buf: String,
entry: PassphraseEntry,
},
Quit {
prompt: QuitPrompt,
@ -929,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(),
@ -1090,8 +1359,7 @@ impl App {
self.screen = Screen::Passphrase {
kind,
path: path.clone(),
first: None,
buf: String::new(),
entry: PassphraseEntry::new(),
};
}
}
@ -1101,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);
}
_ => {}
},
@ -1166,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)
}
@ -1279,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),
};
}
}
@ -1449,9 +1711,13 @@ impl App {
let (tx, rx) = mpsc::channel();
self.status_note = Some("sending".into());
std::mem::drop(self.rt.spawn(async move {
// `send()` reports `Sent` when the circuit took it and `Queued` when
// the peer's onion is unreachable. The footer then reads the real
// row count from the outbox, so this note is only the first word.
let note = match node.send(&pk, &body).await {
Ok(()) => "sent".to_string(),
Err(e) => format!("send failed: {e}"),
Ok(OutboxStatus::Sent) => "sent".to_string(),
Ok(_) => "queued".to_string(),
Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)),
};
let _ = tx.send(note);
}));
@ -1485,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 {
@ -1561,38 +1827,22 @@ impl App {
}
f.render_stateful_widget(roster, panes[0], &mut roster_state);
let chat_lines = self.chat_lines();
let inner_h = panes[1].height.saturating_sub(2);
let nlines = chat_lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = self.chat_scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let chat_title = {
let name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
let mut t = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if self.focus == Pane::Chat { "> " } else { " " };
format!("{mark}{t}")
};
let chat_text = chat_lines.join("\n");
let chat = Paragraph::new(chat_text)
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(self.pane_block(&chat_title, Pane::Chat));
f.render_widget(chat, panes[1]);
let (chat_lines, summary) = self.chat_view();
let chat_name = self.friends.get(self.selected).map(|friend| {
friend
.petname
.as_deref()
.unwrap_or(&friend.fingerprint)
.to_string()
});
draw_chat(
f,
panes[1],
&chat_lines,
chat_name.as_deref(),
self.focus == Pane::Chat,
self.chat_scroll,
);
let mark = if self.focus == Pane::Composer {
"> "
@ -1616,62 +1866,108 @@ impl App {
cols[3],
);
let footer = self.footer_line(area.width);
let footer = self.footer_line(area.width, &summary);
f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]);
}
fn footer_line(&self, width: u16) -> String {
fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String {
// The outbox is the source of truth while anything is outstanding; the
// transient note still covers "sending", "sent file x", "invoice sent".
let note = summary.note().or_else(|| self.status_note.clone());
status_footer(
width,
&self.me_fp,
&self.me_onion,
self.status_note.as_deref(),
note.as_deref(),
footer_hints(&self.screen),
)
}
fn chat_lines(&self) -> Vec<String> {
fn chat_view(&self) -> (Vec<String>, OutboxSummary) {
let Some(friend) = self.friends.get(self.selected) else {
return vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
];
return (
vec![
"no friends yet".into(),
"F3 paste an invite to add one".into(),
],
OutboxSummary::default(),
);
};
match self.node.list_messages(&friend.pubkey) {
Ok(msgs) if msgs.is_empty() => empty_friend_chat_text()
.lines()
.map(str::to_string)
.collect(),
Ok(msgs) => msgs
.iter()
.map(|m| {
let side = if m.dir == "out" { "you" } else { "them" };
format!("{side}: {}", sanitize::display_text(&m.plaintext))
})
.collect(),
Err(e) => vec![e],
Ok(msgs) => {
let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default();
chat_with_delivery(&msgs, &pending, unix_now_secs())
}
Err(e) => (vec![e], OutboxSummary::default()),
}
}
fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> {
let focused = self.focus == pane;
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
pane_block_for(title, self.focus == pane)
}
}
/// Pane chrome without an `App`: focus is accent border + bold title, never
/// color alone (the `> ` marks come from the callers).
fn pane_block_for(title: &str, focused: bool) -> Block<'_> {
let border = if focused {
style_accent()
} else {
style_border()
};
let title_style = if focused {
style_accent().add_modifier(Modifier::BOLD)
} else {
style_dim()
};
apply_chrome_borders(Block::default())
.border_style(border)
.title(title)
.title_style(title_style)
}
fn unix_now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and
/// delivery-marker behaviour are testable without constructing a `Node`.
pub fn draw_chat(
f: &mut Frame,
area: Rect,
lines: &[String],
name: Option<&str>,
focused: bool,
scroll: u16,
) {
let inner_h = area.height.saturating_sub(2);
let nlines = lines.len();
let max_scroll = nlines.saturating_sub(inner_h as usize) as u16;
let scroll = scroll.min(max_scroll);
let overflow = nlines > inner_h as usize && inner_h > 0;
let mut title = match name {
Some(n) => format!("chat {n}"),
None => "chat".to_string(),
};
if overflow {
let end = (scroll as usize + inner_h as usize).min(nlines);
title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1));
}
let mark = if focused { "> " } else { " " };
let title = format!("{mark}{title}");
f.render_widget(
Paragraph::new(lines.join("\n"))
.style(style_text())
.wrap(Wrap { trim: false })
.scroll((scroll, 0))
.block(pane_block_for(&title, focused)),
area,
);
}
/// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`.
pub fn status_footer(
width: u16,
@ -1687,7 +1983,7 @@ pub fn status_footer(
let mut note = status_note.unwrap_or("").trim().to_string();
if !note.is_empty()
&& color_mode() == ColorMode::None
&& (note.starts_with("send failed") || note == "fingerprint mismatch")
&& (note.contains("send failed") || note == "fingerprint mismatch")
&& !note.starts_with("! ")
{
note = format!("! {note}");
@ -2015,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.

312
tests/outbox.rs Normal file
View file

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

View file

@ -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");
}
@ -277,7 +277,7 @@ fn whole_store_file_is_encrypted_at_rest() {
(b"reply-at-rest-xyz".to_vec(), "inbound chat body"),
(hex(&pk(7)).into_bytes(), "friend pubkey hex"),
(b"friend.onion".to_vec(), "friend locator"),
(me.identity_sk.clone(), "identity secret key"),
(me.identity_sk.to_vec(), "identity secret key"),
] {
assert!(
!store_contains(dir.path(), &needle),
@ -394,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);
}
@ -428,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]

111
tests/tor_lifecycle.rs Normal file
View file

@ -0,0 +1,111 @@
//! 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/store.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:?}"
);
// Rows written by `start` (self row, current onion) are still in the WAL at
// this point: no checkpoint has run, and the connection that wrote them is
// still open.
let wal = home.join("onionwire.db-wal");
let before = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
assert!(
before > 0,
"expected pending WAL frames before flush, got {before}"
);
// 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:?}");
// `flush` promises a truncated WAL, and on an encrypted store that only
// works through the store's own keyed connection.
let left = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
assert_eq!(left, 0, "flush left {left} bytes of WAL to replay");
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,10 +1,13 @@
//! Spec implementation tests for docs/TUI.md (this card).
//! Does not own `tests/tui_frames.rs` (PR #23).
use onionwire::Message;
use onionwire::outbox::{OutboxEntry, OutboxStatus};
use onionwire::qr;
use onionwire::tui::{
alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text,
help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width,
OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat,
draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints,
main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason,
status_footer, wrap_invite,
};
use ratatui::Frame;
@ -376,3 +379,420 @@ fn ascii_switch_80x24_frame_is_pure_ascii() {
println!("===== AFTER ascii share 80x24 =====\n{screen}");
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
// ---------------------------------------------------------------------------
// Outbox delivery state (card t_d9a5b065)
//
// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` /
// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire
// prefix, no parallel state model.
// ---------------------------------------------------------------------------
fn out_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "out".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn in_msg(id: i64, body: &str) -> Message {
Message {
id,
dir: "in".into(),
plaintext: body.as_bytes().to_vec(),
}
}
fn pending_row(
message_id: i64,
body: &str,
status: OutboxStatus,
attempts: u32,
next_in: i64,
now: i64,
) -> OutboxEntry {
OutboxEntry {
id: 1,
friend_pk: vec![9u8; 32],
message_id,
body: body.as_bytes().to_vec(),
attempts,
next_attempt_at: now + next_in,
created_at: now,
status,
last_error: None,
}
}
fn queued_row(message_id: i64, body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Queued, attempts, next_in, now)
}
fn sending_row(message_id: i64, body: &str, now: i64) -> OutboxEntry {
pending_row(message_id, body, OutboxStatus::Sending, 1, 0, now)
}
fn failed_row(message_id: i64, body: &str, why: &str, now: i64) -> OutboxEntry {
pending_row(
message_id,
body,
OutboxStatus::Failed(why.into()),
8,
0,
now,
)
}
/// Marker is everything after the two-space separator the render helper uses.
fn marker_of(line: &str) -> &str {
line.rsplit(" ").next().unwrap_or("")
}
/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`.
fn force_unicode_mode() {
unsafe {
std::env::remove_var("ONIONWIRE_ASCII");
std::env::remove_var("NO_COLOR");
}
}
#[test]
fn queued_and_delivered_messages_render_different_markers() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(1, "ping"), out_msg(2, "pong")];
let pending = vec![queued_row(2, "pong", 2, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('✓'),
"delivered row lost its mark: {:?}",
lines[0]
);
assert!(!lines[0].contains("queued"), "{:?}", lines[0]);
assert!(
lines[1].contains('◷'),
"queued row lost its glyph: {:?}",
lines[1]
);
assert!(lines[1].contains("queued"), "{:?}", lines[1]);
assert!(
lines[1].contains("try 2/8"),
"attempt count missing: {:?}",
lines[1]
);
assert!(
lines[1].contains("retry 45s"),
"retry age missing: {:?}",
lines[1]
);
assert_ne!(
marker_of(&lines[0]),
marker_of(&lines[1]),
"queued and delivered must not share a marker"
);
assert_eq!(summary.queued, 1);
assert_eq!(summary.failed, 0);
}
/// The case the body match got wrong: the same text sent twice, only the
/// *older* send still queued. Joined by body, the (single) pending row lands on
/// the newest send and the actually-queued row shows `✓` — which is exactly
/// false delivery. The join is on `Message::id` / `OutboxEntry::message_id`.
#[test]
fn identical_bodies_join_by_message_id_not_body() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let msgs = vec![out_msg(7, "same text"), out_msg(8, "same text")];
let pending = vec![queued_row(7, "same text", 1, 30, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert!(
lines[0].contains('◷') && lines[0].contains("queued"),
"queued marker must land on the queued row (id 7): {:?}",
lines[0]
);
assert!(
!lines[0].contains('✓'),
"queued row must not claim delivery: {:?}",
lines[0]
);
assert_eq!(
marker_of(&lines[1]),
"✓",
"delivered row (id 8) must keep its mark: {:?}",
lines[1]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
}
#[test]
fn delivery_markers_have_exercised_ascii_fallbacks() {
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe {
std::env::set_var("ONIONWIRE_ASCII", "1");
std::env::remove_var("NO_COLOR");
}
let now = 500;
let msgs = vec![
out_msg(1, "alpha"),
out_msg(2, "beta"),
out_msg(3, "gamma"),
out_msg(4, "delta"),
in_msg(5, "epsilon"),
];
let pending = vec![
failed_row(1, "alpha", "connect peer.onion:80: connection timed out", now),
queued_row(2, "beta", 1, 30, now),
sending_row(3, "gamma", now),
];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in &lines {
assert!(
line.is_ascii(),
"ASCII fallback missing, non-ASCII in {line:?}"
);
}
assert_eq!(marker_of(&lines[0]), "failed: connection timed out");
assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)");
assert_eq!(marker_of(&lines[2]), "sending");
assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`");
assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state");
assert_eq!(summary.queued, 2, "queued + sending are both outstanding");
assert_eq!(summary.failed, 1);
unsafe { std::env::remove_var("ONIONWIRE_ASCII") };
}
#[test]
fn retry_age_and_failure_reason_are_short_forms() {
assert_eq!(retry_in_text(45), "retry 45s");
assert_eq!(retry_in_text(59), "retry 59s");
assert_eq!(retry_in_text(60), "retry 1m");
assert_eq!(retry_in_text(720), "retry 12m");
assert_eq!(retry_in_text(0), "retry now");
assert_eq!(retry_in_text(-30), "retry now");
assert_eq!(
short_send_reason("connect abcdef.onion:80: connection timed out", 24),
"connection timed out"
);
let long = short_send_reason("a-really-long-failure-description-here", 12);
assert!(long.chars().count() <= 12, "{long:?}");
assert!(
long.contains('…') || long.contains("..."),
"truncation marker missing: {long:?}"
);
assert_eq!(short_send_reason("nope", 24), "nope");
}
#[test]
fn delivery_tag_reads_the_outbox_status_enum() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓");
assert_eq!(
delivery_tag(&OutboxStatus::Queued, 3, 120),
"◷ queued (try 3/8, retry 2m)"
);
assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending");
assert_eq!(
delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0),
"✗ failed: nope"
);
}
#[test]
fn footer_summary_counts_queued_and_keeps_fail_closed() {
let none = OutboxSummary::default();
assert_eq!(none.note(), None);
let queued = OutboxSummary {
queued: 2,
failed: 0,
first_error: None,
};
assert_eq!(queued.note().as_deref(), Some("2 queued"));
let failed = OutboxSummary {
queued: 0,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let note = failed.note().expect("failed rows must produce a note");
assert!(note.starts_with("send failed:"), "{note:?}");
assert!(note.contains("connection timed out"), "{note:?}");
let mixed = OutboxSummary {
queued: 3,
failed: 1,
first_error: Some("connect peer.onion:80: connection timed out".into()),
};
let mixed_note = mixed.note().expect("mixed rows must produce a note");
assert!(mixed_note.contains("3 queued"), "{mixed_note:?}");
assert!(mixed_note.contains("send failed"), "{mixed_note:?}");
// Fail-closed copy stays visible in the real footer at the 80-col floor.
let line = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(
line.chars().count() <= 80,
"{} {line:?}",
line.chars().count()
);
assert!(line.contains("send failed"), "footer dropped it: {line:?}");
assert!(line.contains("TOR") && line.contains("? help"), "{line:?}");
let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints());
assert!(queued_line.contains("2 queued"), "{queued_line:?}");
assert!(queued_line.chars().count() <= 80);
// `! ` ornament (colour off) still lands on the derived failing note.
let _guard = ASCII_ENV.lock().expect("ascii env lock");
unsafe { std::env::set_var("NO_COLOR", "1") };
let no_color = status_footer(80, FP, ONION, Some(&note), main_footer_hints());
assert!(no_color.contains("! send failed"), "{no_color:?}");
unsafe { std::env::remove_var("NO_COLOR") };
}
/// The card's width criterion: draw the real helpers at the documented floor
/// (80x24) and prove nothing in the chat/footer region exceeds the width, and
/// that an over-long row wraps in the pane instead of being clipped.
#[test]
fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() {
let guard = ASCII_ENV.lock().expect("ascii env lock");
force_unicode_mode();
let _guard = guard;
let now = 1_700_000_000;
let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border";
let msgs = vec![out_msg(1, "ok"), in_msg(2, "pong"), out_msg(3, long)];
let pending = vec![queued_row(3, long, 3, 45, now)];
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
for line in lines.iter().take(2) {
assert!(
line.chars().count() <= 80,
"short row wider than 80: {} {line:?}",
line.chars().count()
);
}
let footer = status_footer(
80,
FP,
ONION,
summary.note().as_deref(),
main_footer_hints(),
);
assert!(footer.chars().count() <= 80, "{footer:?}");
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("terminal");
terminal
.draw(|f| {
let area = f.area();
let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area);
draw_chat(f, cols[0], &lines, Some("alice"), true, 0);
f.render_widget(Paragraph::new(footer.clone()), cols[1]);
})
.expect("draw");
let buf = terminal.backend().buffer();
let mut screen = String::new();
for y in 0..24u16 {
for x in 0..80u16 {
screen.push_str(buf[(x, y)].symbol());
}
screen.push('\n');
}
for (y, row) in screen.lines().enumerate() {
assert!(
row.chars().count() <= 80,
"80x24 chat/footer row {y} wider than the terminal: {} {row:?}",
row.chars().count()
);
}
assert!(
screen.contains('◷'),
"queued glyph missing from frame:\n{screen}"
);
assert!(screen.contains("queued"), "queued word missing:\n{screen}");
assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}");
assert!(
screen.contains("with the roster border"),
"long row was clipped, not wrapped:\n{screen}"
);
assert!(
screen.contains("1 queued"),
"footer summary missing:\n{screen}"
);
println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}");
}
/// The renderer consumes the real outbox API, not a hand-written fixture: a
/// genuine unreachable-onion send leaves a `Queued` row, and that row is what
/// the chat line and the footer note are built from.
#[tokio::test]
async fn renders_a_queued_row_from_a_real_outbox_send() {
use onionwire::Store;
use onionwire::outbox::{BoxFut, Deliverer, Outbox};
use std::sync::Arc;
struct Dead;
impl Deliverer for Dead {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
_plaintext: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) })
}
}
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store");
let pk = [1u8; 32];
store
.upsert_friend(&pk, "dead.onion", None)
.expect("friend");
store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey");
let store = Arc::new(std::sync::Mutex::new(store));
let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead));
assert_eq!(
outbox.send(&pk, b"queued for a dead peer").await,
Ok(OutboxStatus::Queued)
);
let pending = outbox.pending(&pk).expect("pending rows");
assert_eq!(pending.len(), 1, "one queued row");
let msgs = store
.lock()
.expect("store lock")
.list_messages(&pk)
.expect("messages");
let now = pending[0].next_attempt_at - 45;
let (lines, summary) = chat_with_delivery(&msgs, &pending, now);
assert_eq!(lines.len(), 1);
assert!(
lines[0].contains("queued (try 1/8, retry 45s)"),
"real outbox row did not render: {:?}",
lines[0]
);
assert_eq!(summary.note().as_deref(), Some("1 queued"));
// And once a send crosses the circuit the row is gone, so the same message
// renders as delivered.
let (delivered, summary) = chat_with_delivery(&msgs, &[], now);
assert!(delivered[0].contains('✓'), "{:?}", delivered[0]);
assert_eq!(summary.note(), None);
}

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