onionwire/tests/hs.rs

192 lines
6.6 KiB
Rust
Raw Permalink Normal View History

//! HS publish wait and CBT floor — 180s fail-closed cuts a working HsDir upload.
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
use onionwire::hs;
use tor_hsservice::status::State;
#[test]
fn publish_wait_covers_hsdir_retries() {
assert!(
hs::PUBLISH_WAIT >= Duration::from_secs(360),
"180s cuts a working HsDir publish while status is still Bootstrapping"
);
}
#[test]
fn cbt_min_timeout_floor_is_at_least_10s() {
// Drive the comparison through a runtime value: asserting on the constant
// directly is folded away by the compiler and clippy rejects it under
// -D warnings (clippy::assertions_on_constants).
let floor_ms = hs::CBT_MIN_TIMEOUT_MS;
assert!(floor_ms >= 10_000, "learned CBT ~1s kills HsDir circuits");
}
#[test]
fn cbt_initial_timeout_matches_the_floor() {
// Consensus cbtinitialtimeout can be ~2s; 4-hop vanguard HS circuits
// need the same floor as cbtmintimeout before the estimator has samples.
let initial = hs::CBT_INITIAL_TIMEOUT_MS;
let floor = hs::CBT_MIN_TIMEOUT_MS;
assert!(initial >= floor, "initial CBT below min floor");
assert!(initial >= 10_000, "initial CBT too low for HsDir circuits");
}
#[test]
fn no_preemptive_exit_ports() {
// Default predicted 80/443 circuits compete with IPT + HsDir builds.
// OnionWire never exits; keep the predicted list empty.
assert!(
hs::PREEMPTIVE_PREDICTED_PORTS.is_empty(),
"preemptive exit circuits starve HS publish"
);
}
#[test]
fn arti_status_running_is_ready_without_probe() {
assert!(hs::hs_is_ready(State::Running, false));
assert!(hs::hs_is_ready(State::DegradedReachable, false));
}
#[test]
fn bootstrapping_is_not_ready_until_a_probe_connects() {
// Combined status stays Bootstrapping through Arti's 5 min HsDir upload
// round even after some descriptors are already fetchable.
assert!(!hs::hs_is_ready(State::Bootstrapping, false));
assert!(hs::hs_is_ready(State::Bootstrapping, true));
}
#[test]
fn degraded_unreachable_is_ready_only_if_probe_connects() {
assert!(!hs::hs_is_ready(State::DegradedUnreachable, false));
assert!(hs::hs_is_ready(State::DegradedUnreachable, true));
}
#[test]
fn broken_or_shutdown_never_ready() {
assert!(!hs::hs_is_ready(State::Broken, true));
assert!(!hs::hs_is_ready(State::Shutdown, true));
}
#[test]
feat(core,sdk): explicit Tor lifecycle — stop, flush, observable state A node had no way to stop. `Wire` was a bare handle over a `Node`: dropping the Kotlin reference left Arti's client, the hosted v3 onion service, the outbox retry worker and the sqlite connection alive, and there was no way to ask where the onion service was. On Android the process is killed without warning by Doze and the background-process killer, so "drop everything when the process dies" is not a lifecycle. Core (`src/node.rs`, `src/hs.rs`): * `Node::shutdown()` — bounded outbox drain (10s), stop the onion service (the rendezvous task is aborted and the RunningOnionService dropped), abort the retry worker, checkpoint the sqlite WAL. Idempotent at this level: the flag is swapped first, so a racing second call is a no-op. * `Node::flush() -> FlushOutcome { attempted, delivered, remaining }` — one delivery attempt for every queued outbox row, ignoring backoff, then a WAL checkpoint. Bounded by 30s because a dead peer's onion holds a dial for ~20s and the caller is a UI thread. A timeout leaves rows in `sending`; `Outbox::reset_stale` requeues them on the next unlock, same as a process that died mid-attempt. * `Node::tor_state() -> TorState` (`Bootstrapping` / `Published` / `DegradedReachable` / `Stopped`) and `hs::tor_state_of(state, stopped, reachable)`, which mirrors `hs_is_ready` exactly instead of re-deriving readiness. * Every network entry point (`send`, `send_once`, `connect_onion`, `rotate`, `flush`) fails with a typed error after the node stops, rather than dialing a dead client. * `checkpoint_wal` reaches the database through a short-lived second connection: `Store` owns the write connection and does not lend it out, and a checkpoint is a property of the database, not of one connection. Best effort — WAL replay on open recovers anything committed. The `WorkerHandle` moved into a `Mutex<Option<...>>` so the teardown can *abort* the retry worker instead of only dropping it when the whole `Node` dies. SDK (`crates/onionwire-sdk/src/lib.rs`): * `Wire.shutdown()`, `Wire.flush(): FlushOutcome`, `Wire.torState(): TorState`. `Wire` now holds `Mutex<Option<Arc<Node>>>`, so teardown drops the last reference to the Tor client and the store instead of keeping them alive behind a JNI handle. * `WireError::Stopped` — a second flat variant, so "you must unlock again" is a typed `WireException.Stopped` in Kotlin, not a string match on `Failed`. * No `unwrap()` on a poisoned mutex anywhere: a poisoned handle reports `Stopped`, which is the correct recovery (unlock again). * Fixes the crate not compiling on this base at all: `Node::send` has returned `Result<OutboxStatus, String>` since the outbox landed, and the SDK still mapped it to `Result<(), String>` (E0308). CI's path allowlist excludes `crates/**` from the Rust job, which is why it stayed green. The live Tor test found a real bug in the first version of `tor_state`: Arti's combined status is still `Bootstrapping` after a *successful* probe of our own onion (that mismatch is what the 360s publish wait exists for), and a freshly launched service reports `Shutdown` before its publish reactor starts — so a node that was live and reachable reported `Bootstrapping`, and briefly `Stopped`, right after unlock. `Node` now tracks an `onion_reachable` flag set when the publish bar is crossed and cleared when `rotate` hard-cuts the service, and `Shutdown`/`Broken` on a live node read `Bootstrapping` (transient) rather than terminal.
2026-09-12 14:29:02 -04:00
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.
let onion = "facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion";
let label = hs::log_label(onion);
assert_ne!(label, onion, "status/probe logs must not use the locator");
assert!(
!label.contains("facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd"),
"log label leaked the onion body: {label}"
);
assert!(
label.contains('…') || label.contains("[scrubbed]"),
"expected safelog redaction, got {label}"
);
}
#[test]
fn client_config_mkdirs_state_and_cache_0700() {
let root = tempfile::tempdir().expect("tempdir");
let state = root.path().join("arti");
let cache = root.path().join("cache");
let _cfg = hs::client_config(&state, &cache);
let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&state), 0o700);
assert_eq!(mode(&cache), 0o700);
}