Files
tsunagi/crates/tsunagi-core/src/error.rs
T
Aleksandr Bogomiakov 90ef5cefec Retire offline node claims with equal network-wide cleanup rights
Offline devices reserved names and IPv4 addresses indefinitely, leaving stale
members in the device history. Give every authenticated network participant
the same right to retire another device's observed signed claim without an
owner, quorum, permanent identity ban or secret change.

Add a separately signed retirement containing the target's original signed
claim as proof. Verify both signatures and network scopes, retain the strongest
proved cutoff per target with deterministic ties, and suppress claim versions
at or below it in membership, hostname ownership and IPv4 allocation. Keep the
old signed records and range agreement, and retain markers after a newer claim
returns so old replicas cannot resurrect obsolete reservations. A returning
device signs a newer claim, allocates against current holders and resets its
previous hostname priority rather than taking a reused name with an old time.

Commit local retirement and the requester's author counter atomically before
announcing it; receivers persist proofs before applying them. Bound history to
1024 targets by default, reject additional targets without evicting protection,
and treat corrupt or over-limit mandatory storage as an explicit error. Repeat
bounded marker batches with a per-session rotating cursor so queue pressure
cannot indefinitely starve later markers. Exclude retired claims and cached
hints from history-derived discovery without preventing a fresh authenticated
device from returning.

Expose Agent::forget_node through the shared local control API. CLI command
tsng network forget-node accepts exact network names, full ids or unique id
prefixes, and exact node hostnames, ids, prefixes or overlay IPv4 addresses.
Ambiguous selections change nothing. Recheck the observed version and refuse
self, online nodes, the selected exit node and absent or changed claims.
Add Forget with an identity confirmation to offline tray device rows. Widen
Show devices to 1440x640 with an 800x400 minimum to fit its contents.

Control ALPN/version advances to tsunagi/ctrl/7 and local IPC to 21; upgrade
all peers and restart the agent with matching CLI/tray clients. Data ALPN 5,
network identity derivation, handshake encoding and existing record signing
bytes remain unchanged. SQLite schema 9 adds retirement storage while retaining
identity, secrets, settings and signed claims. Document behavior and limits.

Validation on Linux through nix develop:
- cargo fmt --all -- --check
- cargo clippy --locked --workspace --all-targets -- -D warnings
- cargo test --locked --workspace --all-targets: 519 passed, 2 existing ignored
  tests; inherited TSUNAGI_CONTROL_SOCKET and TSUNAGI_CONTROL_GROUP were unset
- git diff --check and the built CLI forget-node help

Tests use real iroh authentication and SQLite. Cover restart, stale-replica
recovery, equal rights and network isolation, hostname reuse and return, twelve
marker batches through a two-message queue, malformed signatures and proofs,
invented future cutoffs, deterministic merge, capacity, migration and injected
counter-write rollback, selectors and cleanup through two real CLI processes.
Earlier iterations caught a private test API, a collapsible tray conditional
and a crash-based CLI test waiting for QUIC's idle timeout; corrected before
the final successful suite. Manual tray rendering, macOS/Windows, privileged
TUNs and public-network traversal were not run. The requested RC tag is
v0.1.0-rc.31; no push was requested.
2026-10-12 18:04:29 +01:00

228 lines
7.5 KiB
Rust

//! Error types for the whole library.
//!
//! The library never panics on untrusted network input: every decoding and
//! validation failure is represented as a [`ProtocolError`] and surfaced as a
//! rejected message or session, never as a process abort.
use std::path::PathBuf;
use crate::identity::NetworkId;
/// Convenient result alias used across the crate.
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Top level error type of the library.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// A node-history cleanup is unsafe, stale or cannot be performed.
#[error("cannot forget node: {0}")]
ForgetNode(String),
/// An ordered local data-plane protocol selection is invalid.
#[error("invalid protocol selection: {0}")]
InvalidProtocols(String),
/// The supplied network name does not satisfy the documented rules.
#[error("invalid network name: {0}")]
InvalidNetworkName(&'static str),
/// The supplied network secret does not satisfy the documented rules.
///
/// The secret itself is never included in the message.
#[error("invalid network secret: {0}")]
InvalidNetworkSecret(&'static str),
/// A textual identifier could not be parsed.
#[error("invalid {kind}: {reason}")]
InvalidEncoding {
/// What was being parsed, e.g. `network id`.
kind: &'static str,
/// Why parsing failed.
reason: &'static str,
},
/// The mandatory state directory is already owned by another live agent.
///
/// This is an ownership lock, not a "file exists" check.
#[error("state directory {path} is owned by another running agent instance")]
StateLocked {
/// Directory that could not be locked.
path: PathBuf,
},
/// The mandatory state store is unusable. It is never silently recreated.
#[error("mandatory state store at {path} is unusable and was NOT reset: {reason}")]
StateCorrupted {
/// Path of the unusable store.
path: PathBuf,
/// Human readable reason, free of secrets.
reason: String,
},
/// The mandatory state store has a schema this build cannot handle.
#[error(
"state store schema version {found} is not supported by this build (supported: {supported})"
)]
UnsupportedSchema {
/// Version found on disk.
found: i64,
/// Version this build writes.
supported: i64,
},
/// A storage operation failed.
#[error("storage error: {0}")]
Storage(String),
/// A filesystem operation failed.
#[error("io error at {path}: {source}")]
Io {
/// Path involved in the failure.
path: PathBuf,
/// Underlying error.
#[source]
source: std::io::Error,
},
/// Binding or driving the iroh endpoint failed.
#[error("iroh endpoint error: {0}")]
Endpoint(String),
/// A control protocol violation.
#[error(transparent)]
Protocol(#[from] ProtocolError),
/// The requested network is not currently active on this agent.
#[error("network {0} is not active")]
NetworkNotActive(NetworkId),
/// The requested network is already active on this agent.
#[error("network {0} is already active")]
NetworkAlreadyActive(NetworkId),
/// The requested network is not configured in the state store.
#[error("network {0} is not configured")]
NetworkUnknown(NetworkId),
/// An overlay range overlaps networks already active on this agent.
#[error(
"network {network} cannot start: {range} overlaps active networks {conflicts:?}; switch to it to suspend those networks"
)]
NetworkRangeConflict {
/// Network that could not start.
network: NetworkId,
/// Its agreed or proposed range.
range: crate::state::Ipv4Range,
/// Active networks that must be suspended first.
conflicts: Vec<NetworkId>,
},
/// No session with that peer exists in the given network.
#[error("no authenticated session with peer {peer} in network {network}")]
NoSuchPeer {
/// Network the lookup was scoped to.
network: NetworkId,
/// Peer that was looked up, short form.
peer: String,
},
/// The agent is shutting down or already stopped.
#[error("agent is stopped")]
Stopped,
/// Something that had to answer in bounded time did not.
///
/// Reported instead of waited out: an agent that has wedged must not
/// leave a command hanging with nothing on screen and no way out.
#[error("{what} did not answer in time")]
Timeout {
/// What was asked, phrased so the message stands on its own.
what: String,
},
/// The request is understood and cannot be done as things stand.
#[error("{reason}")]
Rejected {
/// Why, phrased so the message stands on its own.
reason: String,
},
/// Discovery backend failure. Never fatal for the agent.
#[error("discovery error: {0}")]
Discovery(String),
}
/// Errors produced while speaking the control protocol.
///
/// These always result in rejecting a single message or a single session. They
/// never stop other networks, other peers, or the agent itself.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProtocolError {
/// The peer announced an unsupported control protocol version.
#[error("unsupported control protocol version {found} (this build speaks {supported})")]
UnsupportedVersion {
/// Version announced by the peer.
found: u16,
/// Version this build speaks.
supported: u16,
},
/// A frame header announced more bytes than the configured limit allows.
///
/// Checked *before* any buffer of that size is allocated.
#[error("frame of {announced} bytes exceeds the {limit} byte limit")]
FrameTooLarge {
/// Length announced in the frame header.
announced: u64,
/// Configured limit.
limit: usize,
},
/// A frame could not be decoded.
#[error("malformed frame: {0}")]
Malformed(&'static str),
/// The stream ended before a complete frame was read.
#[error("stream closed while reading a frame")]
StreamClosed,
/// An underlying stream read or write failed.
#[error("stream error: {0}")]
Stream(String),
/// The peer failed to prove knowledge of the derived network secret.
#[error("network authentication failed")]
AuthenticationFailed,
/// The peer asked for a network this agent does not have active.
#[error("peer requested an unknown or inactive network")]
UnknownNetwork,
/// A message carried a network id different from the session's network.
#[error("message network id does not match the authenticated session network")]
NetworkMismatch,
/// A regular control message arrived before the handshake completed.
#[error("control message received before authentication completed")]
NotAuthenticated,
/// A handshake step did not complete within the configured timeout.
#[error("handshake timed out")]
HandshakeTimeout,
/// A field exceeded its configured bound.
#[error("field `{field}` exceeds its limit ({len} > {limit})")]
FieldTooLarge {
/// Name of the offending field.
field: &'static str,
/// Observed length.
len: usize,
/// Configured limit.
limit: usize,
},
/// The connection is not usable for deriving channel binding material.
#[error("connection does not provide TLS exporter material: {0}")]
NoChannelBinding(String),
}