Rename the CLI package to tsunagi and its executable to tsng
The command line package is now `tsunagi` and builds the `tsng` executable, which the packages, the unit, the installers and the workflows install and run. The core library package becomes `tsunagi-core`, keeping the library name `tsunagi`, so no code changes `use tsunagi::...`. Directories follow (crates/tsunagi-core, crates/tsunagi). Every command shown to a person is now `tsng ...`. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
bb38562b0a
commit
9966b50407
120 files changed
+631
-635
No files matched your search
@@ -0,0 +1,231 @@
|
||||
//! The disposable cache store, `cache.sqlite`.
|
||||
//!
|
||||
//! Everything here is recoverable. A missing cache is recreated, a corrupt one
|
||||
//! is thrown away and recreated, and a stale one is simply wrong data that the
|
||||
//! rest of the system is expected to tolerate.
|
||||
//!
|
||||
//! Crucially, a stale cache never bypasses identity or network authentication:
|
||||
//! cached hints only produce *candidates*, which still have to pass the
|
||||
//! handshake.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rusqlite::{Connection, params};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::NetworkId;
|
||||
|
||||
/// Schema version written by this build.
|
||||
pub const SCHEMA_VERSION: i64 = 1;
|
||||
|
||||
/// A cached address hint for one peer in one network.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AddressHint {
|
||||
/// Network the hint belongs to.
|
||||
pub network_id: NetworkId,
|
||||
/// Peer endpoint id, 32 bytes.
|
||||
pub endpoint_id: [u8; 32],
|
||||
/// Serialised address, currently `ip:<socketaddr>` or `relay:<url>`.
|
||||
pub addr: String,
|
||||
/// Unix seconds when this hint was last confirmed.
|
||||
pub last_seen: i64,
|
||||
}
|
||||
|
||||
/// Why the cache had to be recreated, if it did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CacheOutcome {
|
||||
/// Opened normally.
|
||||
Opened,
|
||||
/// Created because nothing was there.
|
||||
Created,
|
||||
/// Discarded and recreated. The reason is free of secrets.
|
||||
Reset(String),
|
||||
}
|
||||
|
||||
/// The disposable cache store.
|
||||
#[derive(Debug)]
|
||||
pub struct CacheStore {
|
||||
conn: Connection,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl CacheStore {
|
||||
/// Opens the cache, discarding and recreating it if it is unusable.
|
||||
pub fn open_or_reset(path: impl AsRef<Path>) -> Result<(Self, CacheOutcome)> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let existed = path.exists();
|
||||
|
||||
match Self::try_open(&path, existed) {
|
||||
Ok(store) => Ok((
|
||||
store,
|
||||
if existed {
|
||||
CacheOutcome::Opened
|
||||
} else {
|
||||
CacheOutcome::Created
|
||||
},
|
||||
)),
|
||||
Err(reason) => {
|
||||
tracing::warn!(path = %path.display(), %reason, "discarding unusable cache");
|
||||
Self::remove_files(&path);
|
||||
let store = Self::try_open(&path, false)
|
||||
.map_err(|err| Error::Storage(format!("cannot recreate cache: {err}")))?;
|
||||
Ok((store, CacheOutcome::Reset(reason)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_open(path: &Path, check_integrity: bool) -> std::result::Result<Self, String> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|err| format!("cannot create cache directory: {err}"))?;
|
||||
}
|
||||
let conn = Connection::open(path).map_err(|err| format!("cannot open: {err}"))?;
|
||||
super::restrict_path_permissions(path).map_err(|err| format!("{err}"))?;
|
||||
super::apply_common_pragmas(&conn).map_err(|err| format!("cannot configure: {err}"))?;
|
||||
|
||||
if check_integrity {
|
||||
let integrity: String = conn
|
||||
.query_row("PRAGMA integrity_check", [], |row| row.get(0))
|
||||
.map_err(|err| format!("integrity check failed: {err}"))?;
|
||||
if integrity != "ok" {
|
||||
return Err(format!("integrity check reported: {integrity}"));
|
||||
}
|
||||
}
|
||||
|
||||
let found: i64 = conn
|
||||
.query_row("PRAGMA user_version", [], |row| row.get(0))
|
||||
.map_err(|err| format!("cannot read schema version: {err}"))?;
|
||||
if found > SCHEMA_VERSION {
|
||||
return Err(format!(
|
||||
"cache schema version {found} is newer than {SCHEMA_VERSION}"
|
||||
));
|
||||
}
|
||||
if found < SCHEMA_VERSION {
|
||||
conn.execute_batch(
|
||||
"BEGIN;
|
||||
DROP TABLE IF EXISTS address_hints;
|
||||
CREATE TABLE address_hints (
|
||||
network_id BLOB NOT NULL,
|
||||
endpoint_id BLOB NOT NULL,
|
||||
addr TEXT NOT NULL,
|
||||
last_seen INTEGER NOT NULL,
|
||||
PRIMARY KEY (network_id, endpoint_id, addr)
|
||||
);
|
||||
PRAGMA user_version = 1;
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(|err| format!("cannot create cache schema: {err}"))?;
|
||||
} else {
|
||||
conn.query_row("SELECT count(*) FROM address_hints", [], |row| {
|
||||
row.get::<_, i64>(0)
|
||||
})
|
||||
.map_err(|err| format!("cache schema is unusable: {err}"))?;
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
conn,
|
||||
path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
fn remove_files(path: &Path) {
|
||||
for suffix in ["", "-wal", "-shm", "-journal"] {
|
||||
let mut name = path.as_os_str().to_os_string();
|
||||
name.push(suffix);
|
||||
let _ = std::fs::remove_file(PathBuf::from(name));
|
||||
}
|
||||
}
|
||||
|
||||
/// Path of the underlying file.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Records an address hint, keeping at most `max_per_peer` newest entries.
|
||||
pub fn record_hint(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
endpoint_id: &[u8; 32],
|
||||
addr: &str,
|
||||
max_per_peer: usize,
|
||||
) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO address_hints (network_id, endpoint_id, addr, last_seen)
|
||||
VALUES (?1, ?2, ?3, ?4)
|
||||
ON CONFLICT(network_id, endpoint_id, addr)
|
||||
DO UPDATE SET last_seen = excluded.last_seen",
|
||||
params![
|
||||
network_id.as_bytes().as_slice(),
|
||||
endpoint_id.as_slice(),
|
||||
addr,
|
||||
super::state::now_unix()
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot record address hint: {err}")))?;
|
||||
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM address_hints
|
||||
WHERE network_id = ?1 AND endpoint_id = ?2 AND addr NOT IN (
|
||||
SELECT addr FROM address_hints
|
||||
WHERE network_id = ?1 AND endpoint_id = ?2
|
||||
ORDER BY last_seen DESC LIMIT ?3
|
||||
)",
|
||||
params![
|
||||
network_id.as_bytes().as_slice(),
|
||||
endpoint_id.as_slice(),
|
||||
max_per_peer as i64
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot prune address hints: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns every hint known for a network.
|
||||
pub fn hints_for_network(&self, network_id: NetworkId) -> Result<Vec<AddressHint>> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT endpoint_id, addr, last_seen FROM address_hints
|
||||
WHERE network_id = ?1 ORDER BY last_seen DESC",
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot read address hints: {err}")))?;
|
||||
let rows = stmt
|
||||
.query_map(params![network_id.as_bytes().as_slice()], |row| {
|
||||
let endpoint_id: Vec<u8> = row.get(0)?;
|
||||
let addr: String = row.get(1)?;
|
||||
let last_seen: i64 = row.get(2)?;
|
||||
Ok((endpoint_id, addr, last_seen))
|
||||
})
|
||||
.map_err(|err| Error::Storage(format!("cannot read address hints: {err}")))?;
|
||||
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (endpoint_id, addr, last_seen) =
|
||||
row.map_err(|err| Error::Storage(format!("cannot read hint row: {err}")))?;
|
||||
// A malformed row in a disposable store is skipped, not fatal.
|
||||
let Ok(endpoint_id) = <[u8; 32]>::try_from(endpoint_id.as_slice()) else {
|
||||
continue;
|
||||
};
|
||||
out.push(AddressHint {
|
||||
network_id,
|
||||
endpoint_id,
|
||||
addr,
|
||||
last_seen,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Drops all hints for a network.
|
||||
pub fn forget_network(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM address_hints WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice()],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot clear address hints: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Ownership lock for a state directory.
|
||||
//!
|
||||
//! One persistent state directory belongs to exactly one live agent instance.
|
||||
//! Checking whether a file exists is not enough — a stale file from a crashed
|
||||
//! process must not block a restart, and two concurrently starting agents must
|
||||
//! not both win. An advisory OS file lock gives both properties.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use fs4::{FileExt, TryLockError};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
/// An exclusive lock held for the lifetime of an agent.
|
||||
///
|
||||
/// Dropping it releases the lock, so a cleanly stopped agent leaves the
|
||||
/// directory immediately reopenable.
|
||||
#[derive(Debug)]
|
||||
pub struct DirectoryLock {
|
||||
file: File,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl DirectoryLock {
|
||||
/// Acquires the lock, failing fast if another live agent holds it.
|
||||
pub fn acquire(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let file = OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.truncate(false)
|
||||
.open(&path)
|
||||
.map_err(|source| Error::Io {
|
||||
path: path.clone(),
|
||||
source,
|
||||
})?;
|
||||
super::restrict_permissions(&file, &path)?;
|
||||
|
||||
match FileExt::try_lock(&file) {
|
||||
Ok(()) => Ok(Self { file, path }),
|
||||
Err(TryLockError::WouldBlock) => Err(Error::StateLocked {
|
||||
path: path
|
||||
.parent()
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| path.clone()),
|
||||
}),
|
||||
Err(TryLockError::Error(source)) => Err(Error::Io { path, source }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of the lock file.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DirectoryLock {
|
||||
fn drop(&mut self) {
|
||||
// Best effort: the OS releases the lock when the descriptor closes anyway.
|
||||
let _ = FileExt::unlock(&self.file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
//! Persistence, split into mandatory state and a disposable cache.
|
||||
//!
|
||||
//! | store | contents | on damage |
|
||||
//! |----------------|--------------------------------------------------------|-----------|
|
||||
//! | `state.sqlite` | device identity, network configuration, hostname | hard error |
|
||||
//! | `cache.sqlite` | address hints and other recoverable data | discarded and recreated |
|
||||
//!
|
||||
//! Both files are created with owner-only permissions where the platform
|
||||
//! supports it. The state directory additionally carries an ownership lock, see
|
||||
//! [`DirectoryLock`].
|
||||
//!
|
||||
//! SQLite is synchronous. Every call that touches a database therefore runs on
|
||||
//! a blocking pool via [`tokio::task::spawn_blocking`], and no database lock is
|
||||
//! ever held across a network `await`.
|
||||
|
||||
mod cache;
|
||||
mod lock;
|
||||
mod state;
|
||||
|
||||
pub use cache::{AddressHint, CacheOutcome, CacheStore};
|
||||
pub use lock::DirectoryLock;
|
||||
pub use state::{SCHEMA_VERSION, StateStore, StoredNetwork};
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
use crate::config::StoragePaths;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::{DeviceIdentity, NetworkId, NetworkName, NetworkSecret};
|
||||
use crate::state::SignedRecord;
|
||||
|
||||
/// Applies the pragmas both stores share.
|
||||
fn apply_common_pragmas(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restricts a file to the current user where the platform supports it.
|
||||
#[cfg(unix)]
|
||||
fn restrict_permissions(file: &std::fs::File, path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let perms = std::fs::Permissions::from_mode(0o600);
|
||||
file.set_permissions(perms).map_err(|source| Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
/// On Windows, files inherit the parent directory's ACL, which for the
|
||||
/// per-user application data directory is already restricted to that user.
|
||||
#[cfg(not(unix))]
|
||||
fn restrict_permissions(_file: &std::fs::File, _path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restricts a file to the user that owns it.
|
||||
///
|
||||
/// Part of what the system level offers a protocol: a plugin keeping keys of
|
||||
/// its own on disk has the same obligation as the agent, and should not have
|
||||
/// to work out the platform details again to meet it.
|
||||
#[cfg(unix)]
|
||||
pub fn restrict_path_permissions(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|source| {
|
||||
Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Restricts a file to the user that owns it. A no-op off Unix.
|
||||
#[cfg(not(unix))]
|
||||
pub fn restrict_path_permissions(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Restricts a directory to the user that owns it.
|
||||
#[cfg(unix)]
|
||||
pub fn restrict_dir_permissions(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).map_err(|source| {
|
||||
Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Restricts a directory to the user that owns it. A no-op off Unix.
|
||||
#[cfg(not(unix))]
|
||||
pub fn restrict_dir_permissions(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates a directory and every parent, restricted to this user.
|
||||
pub fn create_dir(path: &Path) -> Result<()> {
|
||||
std::fs::create_dir_all(path).map_err(|source| Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
restrict_dir_permissions(path)
|
||||
}
|
||||
|
||||
/// Async facade over both stores, holding the directory ownership lock.
|
||||
///
|
||||
/// Cloning shares the same underlying connections and the same lock.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Storage {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
state: Mutex<StateStore>,
|
||||
cache: Mutex<Option<CacheStore>>,
|
||||
cache_outcome: CacheOutcome,
|
||||
paths: StoragePaths,
|
||||
lock: Mutex<Option<DirectoryLock>>,
|
||||
}
|
||||
|
||||
impl Storage {
|
||||
/// Opens both stores and takes the ownership lock on the state directory.
|
||||
///
|
||||
/// Fails with [`Error::StateLocked`] if another live agent owns the state
|
||||
/// directory, and with [`Error::StateCorrupted`] if the mandatory state is
|
||||
/// unusable. A broken cache is silently discarded and reported through
|
||||
/// [`Storage::cache_outcome`].
|
||||
pub fn open(paths: &StoragePaths) -> Result<Self> {
|
||||
create_dir(&paths.state_dir)?;
|
||||
create_dir(&paths.cache_dir)?;
|
||||
|
||||
let lock = DirectoryLock::acquire(paths.lock_file())?;
|
||||
let state = StateStore::open(paths.state_db())?;
|
||||
let (cache, cache_outcome) = CacheStore::open_or_reset(paths.cache_db())?;
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(Inner {
|
||||
state: Mutex::new(state),
|
||||
cache: Mutex::new(Some(cache)),
|
||||
cache_outcome,
|
||||
paths: paths.clone(),
|
||||
lock: Mutex::new(Some(lock)),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// What happened to the cache when the agent started.
|
||||
pub fn cache_outcome(&self) -> &CacheOutcome {
|
||||
&self.inner.cache_outcome
|
||||
}
|
||||
|
||||
/// The configured paths.
|
||||
pub fn paths(&self) -> &StoragePaths {
|
||||
&self.inner.paths
|
||||
}
|
||||
|
||||
fn lock_state(&self) -> MutexGuard<'_, StateStore> {
|
||||
match self.inner.state.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock_cache(&self) -> MutexGuard<'_, Option<CacheStore>> {
|
||||
match self.inner.cache.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a closure against the mandatory state store on the blocking pool.
|
||||
async fn with_state<T, F>(&self, f: F) -> Result<T>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&StateStore) -> Result<T> + Send + 'static,
|
||||
{
|
||||
let inner = Arc::clone(&self.inner);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let guard = match inner.state.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
f(&guard)
|
||||
})
|
||||
.await
|
||||
.map_err(|err| Error::Storage(format!("state task failed: {err}")))?
|
||||
}
|
||||
|
||||
/// Runs a closure against the cache, tolerating an unavailable cache.
|
||||
///
|
||||
/// If the cache has been disabled because it misbehaved, the closure is
|
||||
/// skipped and `default` is returned.
|
||||
async fn with_cache<T, F>(&self, default: T, f: F) -> T
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce(&CacheStore) -> Result<T> + Send + 'static,
|
||||
{
|
||||
let inner = Arc::clone(&self.inner);
|
||||
let joined = tokio::task::spawn_blocking(move || {
|
||||
let guard = match inner.cache.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
match guard.as_ref() {
|
||||
Some(cache) => f(cache),
|
||||
None => Err(Error::Storage("cache is unavailable".into())),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
|
||||
match joined {
|
||||
Ok(Ok(value)) => value,
|
||||
Ok(Err(err)) => {
|
||||
tracing::debug!(%err, "cache operation failed; continuing without it");
|
||||
default
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::debug!(%err, "cache task failed; continuing without it");
|
||||
default
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads or creates the persistent device identity.
|
||||
pub async fn device_identity(&self) -> Result<DeviceIdentity> {
|
||||
self.with_state(|state| state.load_or_create_device_identity())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Lists configured networks.
|
||||
pub async fn list_networks(&self) -> Result<Vec<StoredNetwork>> {
|
||||
self.with_state(|state| state.list_networks()).await
|
||||
}
|
||||
|
||||
/// Stores or updates a network configuration.
|
||||
pub async fn upsert_network(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
name: NetworkName,
|
||||
secret: NetworkSecret,
|
||||
auto_start: bool,
|
||||
) -> Result<()> {
|
||||
self.with_state(move |state| state.upsert_network(network_id, &name, &secret, auto_start))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Persists local broadcast participation for one configured network.
|
||||
pub async fn set_broadcast(&self, network_id: NetworkId, enabled: bool) -> Result<()> {
|
||||
self.with_state(move |state| state.set_broadcast(network_id, enabled))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Persists whether this agent offers itself as an exit node in a network.
|
||||
pub async fn set_exit_node(&self, network_id: NetworkId, enabled: bool) -> Result<()> {
|
||||
self.with_state(move |state| state.set_exit_node(network_id, enabled))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Persists the member this device sends its internet traffic through.
|
||||
pub async fn set_exit_via(&self, network_id: NetworkId, via: Option<[u8; 32]>) -> Result<()> {
|
||||
self.with_state(move |state| state.set_exit_via(network_id, via.as_ref()))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Updates the auto-start flag of a network.
|
||||
pub async fn set_auto_start(&self, network_id: NetworkId, auto_start: bool) -> Result<()> {
|
||||
self.with_state(move |state| state.set_auto_start(network_id, auto_start))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Removes a network configuration and its cached hints.
|
||||
pub async fn remove_network(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.with_state(move |state| {
|
||||
state.remove_network(network_id)?;
|
||||
state.forget_signed_records(network_id)?;
|
||||
state.forget_peer_hostnames(network_id)
|
||||
})
|
||||
.await?;
|
||||
self.with_cache((), move |cache| cache.forget_network(network_id))
|
||||
.await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads the stored hostname.
|
||||
pub async fn hostname(&self) -> Result<Option<String>> {
|
||||
self.with_state(|state| state.hostname()).await
|
||||
}
|
||||
|
||||
/// Writes the stored hostname.
|
||||
pub async fn set_hostname(&self, hostname: String) -> Result<()> {
|
||||
self.with_state(move |state| state.set_hostname(&hostname))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Remembers the hostname a member announced, so it can still be named
|
||||
/// once it is away.
|
||||
pub async fn remember_peer_hostname(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
endpoint_id: [u8; 32],
|
||||
hostname: String,
|
||||
) -> Result<()> {
|
||||
self.with_state(move |state| {
|
||||
state.remember_peer_hostname(network_id, &endpoint_id, &hostname)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The hostnames members of a network last announced.
|
||||
pub async fn peer_hostnames(&self, network_id: NetworkId) -> Result<Vec<([u8; 32], String)>> {
|
||||
self.with_state(move |state| state.peer_hostnames(network_id))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Records an address hint. Failures are non-fatal.
|
||||
pub async fn record_hint(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
endpoint_id: [u8; 32],
|
||||
addr: String,
|
||||
max_per_peer: usize,
|
||||
) {
|
||||
self.with_cache((), move |cache| {
|
||||
cache.record_hint(network_id, &endpoint_id, &addr, max_per_peer)
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Loads every signed record known for a network.
|
||||
pub async fn signed_records(&self, network_id: NetworkId) -> Result<Vec<SignedRecord>> {
|
||||
self.with_state(move |state| state.signed_records(network_id))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stores a record received from another replica.
|
||||
pub async fn put_signed_record(&self, record: SignedRecord) -> Result<()> {
|
||||
self.with_state(move |state| state.put_signed_record(&record))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stores one of this agent's own records and bumps its counter in one
|
||||
/// transaction, which must happen before the record is announced.
|
||||
pub async fn publish_own_record(&self, record: SignedRecord) -> Result<()> {
|
||||
self.with_state(move |state| state.publish_own_record(&record))
|
||||
.await
|
||||
}
|
||||
|
||||
/// The highest version this agent has ever published for a network.
|
||||
pub async fn own_record_version(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
author: iroh::EndpointId,
|
||||
) -> Result<u64> {
|
||||
self.with_state(move |state| state.own_record_version(network_id, author))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reads cached address hints. Returns an empty list if the cache is gone.
|
||||
pub async fn hints_for_network(&self, network_id: NetworkId) -> Vec<AddressHint> {
|
||||
self.with_cache(Vec::new(), move |cache| cache.hints_for_network(network_id))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Synchronously reads the hostname. Used only during startup.
|
||||
pub(crate) fn hostname_blocking(&self) -> Result<Option<String>> {
|
||||
self.lock_state().hostname()
|
||||
}
|
||||
|
||||
/// Whether the cache is currently usable.
|
||||
pub fn cache_healthy(&self) -> bool {
|
||||
self.lock_cache().is_some()
|
||||
}
|
||||
|
||||
/// Releases the state directory ownership lock.
|
||||
///
|
||||
/// Called by [`crate::Agent::shutdown`] so that a cleanly stopped agent
|
||||
/// leaves its directory immediately claimable by another instance. The
|
||||
/// databases stay open and readable, but this handle no longer owns the
|
||||
/// directory and must not be used to write after this point.
|
||||
pub fn release_ownership_lock(&self) {
|
||||
let mut guard = match self.inner.lock.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
guard.take();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a wipe covers: every entry in the two directories.
|
||||
///
|
||||
/// Reported before anything is removed, and again afterwards, because a
|
||||
/// command whose whole job is to destroy state has to be able to say exactly
|
||||
/// what it is about to destroy.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct WipePlan {
|
||||
/// Entries in the state directory, which is the mandatory state and
|
||||
/// anything a plugin keeps beside it.
|
||||
pub state: Vec<std::path::PathBuf>,
|
||||
/// Entries in the cache directory.
|
||||
pub cache: Vec<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl WipePlan {
|
||||
/// Whether there is anything to remove at all.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.state.is_empty() && self.cache.is_empty()
|
||||
}
|
||||
|
||||
/// Every entry, state first.
|
||||
pub fn entries(&self) -> impl Iterator<Item = &std::path::Path> {
|
||||
self.state
|
||||
.iter()
|
||||
.chain(self.cache.iter())
|
||||
.map(std::path::PathBuf::as_path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists what [`wipe`] would remove, without removing anything.
|
||||
pub fn wipe_plan(paths: &StoragePaths) -> Result<WipePlan> {
|
||||
Ok(WipePlan {
|
||||
state: removable(&paths.state_dir, &paths.state_db())?,
|
||||
cache: removable(&paths.cache_dir, &paths.cache_db())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Removes everything in both directories, leaving this device a stranger.
|
||||
///
|
||||
/// The device identity, every network it belongs to, every signed record and
|
||||
/// everything a plugin kept beside them. The next start generates a new
|
||||
/// identity and knows nothing, which is the point: after this there is no
|
||||
/// membership left to be surprised by.
|
||||
///
|
||||
/// What it is **not** is a goodbye. Other members keep the claims this device
|
||||
/// signed, because signed state has no expiry and there is nobody left here
|
||||
/// to sign a release. Leaving each network first with
|
||||
/// [`crate::Agent::leave_network`] is what frees the address and the name.
|
||||
///
|
||||
/// Refuses while an agent owns the state directory, and refuses a directory
|
||||
/// with no `state.sqlite` in it — a wipe pointed at the wrong place by a
|
||||
/// mistyped `--state-dir` would otherwise remove somebody's documents.
|
||||
pub fn wipe(paths: &StoragePaths) -> Result<WipePlan> {
|
||||
let plan = wipe_plan(paths)?;
|
||||
// Held across the removal, so an agent cannot start into a directory
|
||||
// that is half gone. The lock file is itself removed at the end: on
|
||||
// Unix the lock lives on the open handle, not on the name.
|
||||
let lock = DirectoryLock::acquire(paths.lock_file())?;
|
||||
|
||||
for entry in plan.entries() {
|
||||
remove_entry(entry)?;
|
||||
}
|
||||
drop(lock);
|
||||
// Created by acquiring the lock a moment ago, so it is ours to remove
|
||||
// and nothing is left behind claiming the directory.
|
||||
let _ = std::fs::remove_file(paths.lock_file());
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Every entry of `dir`, once `marker` proves it is one of ours.
|
||||
///
|
||||
/// An empty or missing directory is nothing to remove rather than an error:
|
||||
/// wiping twice must be as ordinary as wiping once.
|
||||
fn removable(dir: &Path, marker: &Path) -> Result<Vec<std::path::PathBuf>> {
|
||||
if !dir.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
let read = std::fs::read_dir(dir).map_err(|source| Error::Io {
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
for entry in read {
|
||||
let entry = entry.map_err(|source| Error::Io {
|
||||
path: dir.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
entries.push(entry.path());
|
||||
}
|
||||
if entries.is_empty() {
|
||||
return Ok(entries);
|
||||
}
|
||||
|
||||
// The marker is what tells a state directory from a directory that
|
||||
// merely got named as one. The lock file counts too: an agent that
|
||||
// crashed before writing anything still leaves that.
|
||||
let ours = marker.exists() || dir.join("state.lock").exists();
|
||||
if !ours {
|
||||
return Err(Error::Storage(format!(
|
||||
"{} does not look like a tsunagi directory: no {} in it. Nothing was removed.",
|
||||
dir.display(),
|
||||
marker.file_name().map_or_else(
|
||||
|| marker.display().to_string(),
|
||||
|name| name.to_string_lossy().into_owned()
|
||||
)
|
||||
)));
|
||||
}
|
||||
entries.sort();
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn remove_entry(path: &Path) -> Result<()> {
|
||||
let metadata = match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) => metadata,
|
||||
// Gone between the plan and the removal is the outcome asked for.
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(source) => {
|
||||
return Err(Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
});
|
||||
}
|
||||
};
|
||||
let removed = if metadata.is_dir() {
|
||||
std::fs::remove_dir_all(path)
|
||||
} else {
|
||||
std::fs::remove_file(path)
|
||||
};
|
||||
removed.map_err(|source| Error::Io {
|
||||
path: path.to_path_buf(),
|
||||
source,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,954 @@
|
||||
//! The mandatory state store, `state.sqlite`.
|
||||
//!
|
||||
//! Holds the persistent device identity, configured networks (including their
|
||||
//! shared secrets, which are needed to re-derive keys after a restart), the
|
||||
//! stored hostname and auto-start flags.
|
||||
//!
|
||||
//! Corruption is reported, never silently repaired: a damaged state store must
|
||||
//! not quietly turn into a brand new identity.
|
||||
//!
|
||||
//! Future work will add per-author record versions, accepted signed states and
|
||||
//! revocations here. When that lands, writing an event and bumping the author's
|
||||
//! own counter must happen in one SQLite transaction *before* the change is
|
||||
//! published to the network.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::identity::{DeviceIdentity, NetworkId, NetworkName, NetworkSecret};
|
||||
use crate::state::{RecordBody, SignedRecord};
|
||||
|
||||
/// Schema version written by this build.
|
||||
pub const SCHEMA_VERSION: i64 = 6;
|
||||
|
||||
/// Key of the stored hostname setting.
|
||||
const SETTING_HOSTNAME: &str = "hostname";
|
||||
|
||||
/// A network as persisted in the state store.
|
||||
///
|
||||
/// The secret is held in a [`NetworkSecret`], which redacts itself from `Debug`
|
||||
/// and zeroizes on drop.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredNetwork {
|
||||
/// Derived public network identifier.
|
||||
pub network_id: NetworkId,
|
||||
/// Network name.
|
||||
pub name: NetworkName,
|
||||
/// Shared secret, needed to re-derive keys after restart.
|
||||
pub secret: NetworkSecret,
|
||||
/// Whether the network is activated automatically at agent startup.
|
||||
pub auto_start: bool,
|
||||
/// Local broadcast participation, enabled unless explicitly disabled.
|
||||
pub broadcast: bool,
|
||||
/// This agent offers itself as an exit node here. Off unless turned on.
|
||||
pub exit_node: bool,
|
||||
/// The member this device sends all its internet traffic through, if any.
|
||||
pub exit_via: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// The mandatory state store.
|
||||
#[derive(Debug)]
|
||||
pub struct StateStore {
|
||||
conn: Connection,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl StateStore {
|
||||
/// Opens (creating if absent) the state store at `path`.
|
||||
///
|
||||
/// Returns [`Error::StateCorrupted`] if the file exists but is not a usable
|
||||
/// database. The file is never deleted or recreated by this function.
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let existed = path.exists();
|
||||
// The database file is created on demand, so the directory holding
|
||||
// it has to be too — with the same restricted permissions the agent
|
||||
// would have given it, never looser.
|
||||
if let Some(parent) = path.parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
{
|
||||
super::create_dir(parent)?;
|
||||
}
|
||||
let conn = Connection::open(&path).map_err(|err| Error::StateCorrupted {
|
||||
path: path.clone(),
|
||||
reason: format!("cannot open database: {err}"),
|
||||
})?;
|
||||
|
||||
super::restrict_path_permissions(&path)?;
|
||||
super::apply_common_pragmas(&conn).map_err(|err| Error::StateCorrupted {
|
||||
path: path.clone(),
|
||||
reason: format!("cannot configure database: {err}"),
|
||||
})?;
|
||||
|
||||
if existed {
|
||||
let integrity: String = conn
|
||||
.query_row("PRAGMA integrity_check", [], |row| row.get(0))
|
||||
.map_err(|err| Error::StateCorrupted {
|
||||
path: path.clone(),
|
||||
reason: format!("integrity check failed: {err}"),
|
||||
})?;
|
||||
if integrity != "ok" {
|
||||
return Err(Error::StateCorrupted {
|
||||
path,
|
||||
reason: format!("integrity check reported: {integrity}"),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let store = Self { conn, path };
|
||||
store.migrate()?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// Path of the underlying file.
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
fn corrupt(&self, reason: impl std::fmt::Display) -> Error {
|
||||
Error::StateCorrupted {
|
||||
path: self.path.clone(),
|
||||
reason: reason.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate(&self) -> Result<()> {
|
||||
let found: i64 = self
|
||||
.conn
|
||||
.query_row("PRAGMA user_version", [], |row| row.get(0))
|
||||
.map_err(|err| self.corrupt(format!("cannot read schema version: {err}")))?;
|
||||
|
||||
if found > SCHEMA_VERSION {
|
||||
return Err(Error::UnsupportedSchema {
|
||||
found,
|
||||
supported: SCHEMA_VERSION,
|
||||
});
|
||||
}
|
||||
if found == SCHEMA_VERSION {
|
||||
return self.verify_shape();
|
||||
}
|
||||
|
||||
// Migration 2 -> 3: the record body gained a hostname, which changed
|
||||
// the signing domain, and the version counter gained an author.
|
||||
//
|
||||
// The stored records are discarded rather than carried over. They
|
||||
// were signed under a domain that no longer verifies, so keeping them
|
||||
// would mean holding rows that every read has to reject — and one of
|
||||
// those rejections could be mistaken for corruption. Each member
|
||||
// re-publishes its claim on the next run, which is the one thing here
|
||||
// that repairs itself.
|
||||
if (2..3).contains(&found) {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"BEGIN;
|
||||
DROP TABLE IF EXISTS signed_records;
|
||||
DROP TABLE IF EXISTS own_record_version;
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(|err| self.corrupt(format!("cannot migrate schema to 3: {err}")))?;
|
||||
self.conn
|
||||
.execute_batch(SIGNED_RECORDS_SCHEMA)
|
||||
.map_err(|err| self.corrupt(format!("cannot migrate schema to 3: {err}")))?;
|
||||
}
|
||||
|
||||
// Migration 1 -> 2: signed records that outlive a session.
|
||||
if (1..2).contains(&found) {
|
||||
self.conn
|
||||
.execute_batch(SIGNED_RECORDS_SCHEMA)
|
||||
.map_err(|err| self.corrupt(format!("cannot migrate schema to 2: {err}")))?;
|
||||
}
|
||||
|
||||
// Migration 0 -> 1: initial schema.
|
||||
if found < 1 {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"BEGIN;
|
||||
CREATE TABLE device_identity (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
secret_key BLOB NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE networks (
|
||||
network_id BLOB PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
secret BLOB NOT NULL,
|
||||
auto_start INTEGER NOT NULL DEFAULT 1,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
PRAGMA user_version = 1;
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(|err| self.corrupt(format!("cannot create schema: {err}")))?;
|
||||
self.conn
|
||||
.execute_batch(SIGNED_RECORDS_SCHEMA)
|
||||
.map_err(|err| self.corrupt(format!("cannot create schema: {err}")))?;
|
||||
}
|
||||
if found < 4 {
|
||||
self.conn.execute_batch("BEGIN;
|
||||
ALTER TABLE networks ADD COLUMN broadcast INTEGER NOT NULL DEFAULT 1 CHECK (broadcast IN (0,1));
|
||||
PRAGMA user_version = 4;
|
||||
COMMIT;").map_err(|err| self.corrupt(format!("cannot migrate schema to 4: {err}")))?;
|
||||
}
|
||||
if found < 5 {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS peer_hostnames (
|
||||
network_id BLOB NOT NULL,
|
||||
endpoint_id BLOB NOT NULL,
|
||||
hostname TEXT NOT NULL,
|
||||
PRIMARY KEY (network_id, endpoint_id)
|
||||
);
|
||||
PRAGMA user_version = 5;
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(|err| self.corrupt(format!("cannot migrate schema to 5: {err}")))?;
|
||||
}
|
||||
if found < 6 {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"BEGIN;
|
||||
ALTER TABLE networks ADD COLUMN exit_node INTEGER NOT NULL DEFAULT 0 CHECK (exit_node IN (0,1));
|
||||
ALTER TABLE networks ADD COLUMN exit_via BLOB;
|
||||
PRAGMA user_version = 6;
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(|err| self.corrupt(format!("cannot migrate schema to 6: {err}")))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Confirms the expected tables exist, so that a truncated or foreign
|
||||
/// database is reported rather than used.
|
||||
fn verify_shape(&self) -> Result<()> {
|
||||
for table in [
|
||||
"device_identity",
|
||||
"networks",
|
||||
"settings",
|
||||
"signed_records",
|
||||
"peer_hostnames",
|
||||
] {
|
||||
let present: Option<String> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?1",
|
||||
params![table],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(|err| self.corrupt(format!("cannot inspect schema: {err}")))?;
|
||||
if present.is_none() {
|
||||
return Err(self.corrupt(format!("table `{table}` is missing")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads the stored device identity, if there is one.
|
||||
///
|
||||
/// Reads and never writes, so asking who this device is does not decide
|
||||
/// it. A store that has never run an agent has no identity yet, which is
|
||||
/// `None` rather than an error.
|
||||
///
|
||||
/// A stored key of the wrong length is a corruption error, never a reason
|
||||
/// to silently mint a new identity.
|
||||
pub fn device_identity(&self) -> Result<Option<DeviceIdentity>> {
|
||||
let stored: Option<Vec<u8>> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT secret_key FROM device_identity WHERE id = 1",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(|err| self.corrupt(format!("cannot read device identity: {err}")))?;
|
||||
|
||||
let Some(bytes) = stored else {
|
||||
return Ok(None);
|
||||
};
|
||||
let bytes: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
|
||||
self.corrupt(format!(
|
||||
"stored device key has {} bytes, expected 32; refusing to replace it",
|
||||
bytes.len()
|
||||
))
|
||||
})?;
|
||||
Ok(Some(DeviceIdentity::from_secret_bytes(&bytes)))
|
||||
}
|
||||
|
||||
/// Loads the stored device identity, creating one on first use.
|
||||
pub fn load_or_create_device_identity(&self) -> Result<DeviceIdentity> {
|
||||
if let Some(identity) = self.device_identity()? {
|
||||
return Ok(identity);
|
||||
}
|
||||
|
||||
let identity = DeviceIdentity::generate();
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO device_identity (id, secret_key, created_at) VALUES (1, ?1, ?2)",
|
||||
params![identity.secret_bytes().as_slice(), now_unix()],
|
||||
)
|
||||
.map_err(|err| self.corrupt(format!("cannot store device identity: {err}")))?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
/// Replaces the device identity, giving up what the outgoing key held.
|
||||
///
|
||||
/// A device key is the author of every record this agent has signed, so
|
||||
/// replacing it makes this a different member. The addresses and names
|
||||
/// the old key claimed would otherwise stay reserved to a key nobody
|
||||
/// holds, and nothing could ever free them — there is no way to sign on
|
||||
/// another author's behalf, and by design there is no authority that
|
||||
/// could overrule one.
|
||||
///
|
||||
/// So the outgoing key signs a release for every network on its way out.
|
||||
/// That is the revocation: a positive statement, merged like any other,
|
||||
/// which frees the address and the name for whoever wants them next.
|
||||
///
|
||||
/// All of it commits together. A crash part way through must not leave an
|
||||
/// identity that has already been replaced beside releases that were
|
||||
/// never written, because the old key would then be gone and unable to
|
||||
/// sign them.
|
||||
///
|
||||
/// Returns the new identity and the networks a release was signed for.
|
||||
pub fn rotate_device_identity(&self) -> Result<(DeviceIdentity, Vec<NetworkId>)> {
|
||||
let outgoing = self.device_identity()?;
|
||||
let networks = self.list_networks()?;
|
||||
let replacement = DeviceIdentity::generate();
|
||||
|
||||
let transaction = self
|
||||
.conn
|
||||
.unchecked_transaction()
|
||||
.map_err(|err| Error::Storage(format!("cannot begin a transaction: {err}")))?;
|
||||
|
||||
let mut released = Vec::new();
|
||||
if let Some(outgoing) = &outgoing {
|
||||
let author = outgoing.endpoint_id();
|
||||
let signing = outgoing.signing_key();
|
||||
for network in &networks {
|
||||
let previous: Option<i64> = transaction
|
||||
.query_row(
|
||||
"SELECT version FROM own_record_version
|
||||
WHERE network_id = ?1 AND author = ?2",
|
||||
params![
|
||||
network.network_id.as_bytes().as_slice(),
|
||||
author.as_bytes().as_slice()
|
||||
],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(|err| Error::Storage(format!("cannot read our version: {err}")))?;
|
||||
// A key that never published anything has nothing to give up.
|
||||
let Some(previous) = previous else { continue };
|
||||
|
||||
let version = (previous.max(0) as u64).saturating_add(1);
|
||||
let record =
|
||||
SignedRecord::sign(&signing, network.network_id, version, RecordBody::Release);
|
||||
let body = postcard::to_stdvec(&record.body)
|
||||
.map_err(|err| Error::Storage(format!("cannot encode a record body: {err}")))?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO signed_records (network_id, author, version, body, signature)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(network_id, author) DO UPDATE SET
|
||||
version = excluded.version,
|
||||
body = excluded.body,
|
||||
signature = excluded.signature",
|
||||
params![
|
||||
record.network.as_slice(),
|
||||
record.author.as_slice(),
|
||||
record.version as i64,
|
||||
body,
|
||||
record.signature
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store a release: {err}")))?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO own_record_version (network_id, author, version)
|
||||
VALUES (?1, ?2, ?3)
|
||||
ON CONFLICT(network_id, author) DO UPDATE SET
|
||||
version = max(version, excluded.version)",
|
||||
params![
|
||||
record.network.as_slice(),
|
||||
record.author.as_slice(),
|
||||
record.version as i64
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store our version: {err}")))?;
|
||||
released.push(network.network_id);
|
||||
}
|
||||
}
|
||||
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO device_identity (id, secret_key, created_at) VALUES (1, ?1, ?2)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
secret_key = excluded.secret_key,
|
||||
created_at = excluded.created_at",
|
||||
params![replacement.secret_bytes().as_slice(), now_unix()],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store the new identity: {err}")))?;
|
||||
|
||||
transaction
|
||||
.commit()
|
||||
.map_err(|err| Error::Storage(format!("cannot commit the new identity: {err}")))?;
|
||||
Ok((replacement, released))
|
||||
}
|
||||
|
||||
/// Inserts or updates a network configuration.
|
||||
pub fn upsert_network(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
name: &NetworkName,
|
||||
secret: &NetworkSecret,
|
||||
auto_start: bool,
|
||||
) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO networks (network_id, name, secret, auto_start, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(network_id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
secret = excluded.secret,
|
||||
auto_start = excluded.auto_start",
|
||||
params![
|
||||
network_id.as_bytes().as_slice(),
|
||||
name.as_str(),
|
||||
secret.expose(),
|
||||
auto_start as i64,
|
||||
now_unix()
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store network: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets the auto-start flag of a configured network.
|
||||
pub fn set_auto_start(&self, network_id: NetworkId, auto_start: bool) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE networks SET auto_start = ?2 WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice(), auto_start as i64],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot update network: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves local participation without changing identity, membership or auto-start.
|
||||
pub fn set_broadcast(&self, network_id: NetworkId, enabled: bool) -> Result<()> {
|
||||
let changed = self
|
||||
.conn
|
||||
.execute(
|
||||
"UPDATE networks SET broadcast = ?2 WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice(), enabled as i64],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot update broadcast policy: {err}")))?;
|
||||
if changed == 0 {
|
||||
return Err(Error::NetworkUnknown(network_id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a network configuration entirely.
|
||||
pub fn remove_network(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM networks WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice()],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot remove network: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves whether this agent offers itself as an exit node in a network.
|
||||
pub fn set_exit_node(&self, network_id: NetworkId, enabled: bool) -> Result<()> {
|
||||
let changed = self
|
||||
.conn
|
||||
.execute(
|
||||
"UPDATE networks SET exit_node = ?2 WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice(), enabled as i64],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot update exit node offer: {err}")))?;
|
||||
if changed == 0 {
|
||||
return Err(Error::NetworkUnknown(network_id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves which member this device sends its internet traffic through.
|
||||
///
|
||||
/// One device has one default route, so choosing an exit node in one
|
||||
/// network clears the choice in every other.
|
||||
pub fn set_exit_via(&self, network_id: NetworkId, via: Option<&[u8; 32]>) -> Result<()> {
|
||||
let tx = self
|
||||
.conn
|
||||
.unchecked_transaction()
|
||||
.map_err(|err| Error::Storage(format!("cannot update exit node: {err}")))?;
|
||||
let changed = tx
|
||||
.execute(
|
||||
"UPDATE networks SET exit_via = ?2 WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice(), via.map(|v| v.as_slice())],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot update exit node: {err}")))?;
|
||||
if changed == 0 {
|
||||
return Err(Error::NetworkUnknown(network_id));
|
||||
}
|
||||
if via.is_some() {
|
||||
tx.execute(
|
||||
"UPDATE networks SET exit_via = NULL WHERE network_id != ?1",
|
||||
params![network_id.as_bytes().as_slice()],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot update exit node: {err}")))?;
|
||||
}
|
||||
tx.commit()
|
||||
.map_err(|err| Error::Storage(format!("cannot update exit node: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lists every configured network.
|
||||
pub fn list_networks(&self) -> Result<Vec<StoredNetwork>> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT network_id, name, secret, auto_start, broadcast, exit_node, exit_via FROM networks ORDER BY name")
|
||||
.map_err(|err| Error::Storage(format!("cannot list networks: {err}")))?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
let id: Vec<u8> = row.get(0)?;
|
||||
let name: String = row.get(1)?;
|
||||
let secret: Vec<u8> = row.get(2)?;
|
||||
let auto_start: i64 = row.get(3)?;
|
||||
Ok((
|
||||
id,
|
||||
name,
|
||||
secret,
|
||||
auto_start != 0,
|
||||
row.get::<_, bool>(4)?,
|
||||
row.get::<_, bool>(5)?,
|
||||
row.get::<_, Option<Vec<u8>>>(6)?,
|
||||
))
|
||||
})
|
||||
.map_err(|err| Error::Storage(format!("cannot list networks: {err}")))?;
|
||||
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (id, name, secret, auto_start, broadcast, exit_node, exit_via) =
|
||||
row.map_err(|err| Error::Storage(format!("cannot read network row: {err}")))?;
|
||||
let id: [u8; 32] = id
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| self.corrupt("stored network id is not 32 bytes"))?;
|
||||
out.push(StoredNetwork {
|
||||
network_id: NetworkId::from_bytes(id),
|
||||
name: NetworkName::new(name)?,
|
||||
secret: NetworkSecret::from_bytes(secret)?,
|
||||
auto_start,
|
||||
broadcast,
|
||||
exit_node,
|
||||
exit_via: exit_via.and_then(|bytes| <[u8; 32]>::try_from(bytes.as_slice()).ok()),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Reads the stored hostname, if any.
|
||||
pub fn hostname(&self) -> Result<Option<String>> {
|
||||
self.get_setting(SETTING_HOSTNAME)
|
||||
}
|
||||
|
||||
/// Stores the hostname.
|
||||
///
|
||||
/// Today this is a local setting. In the future a rename must be a signed
|
||||
/// record that revokes the specific old binding and announces the new one,
|
||||
/// ideally atomically in one record.
|
||||
pub fn set_hostname(&self, hostname: &str) -> Result<()> {
|
||||
self.set_setting(SETTING_HOSTNAME, hostname)
|
||||
}
|
||||
|
||||
/// Loads every signed record known for a network.
|
||||
///
|
||||
/// Records are returned as stored; the caller verifies them, because the
|
||||
/// database is not a trust boundary — a restored backup or a copied file
|
||||
/// could contain anything.
|
||||
pub fn signed_records(&self, network_id: NetworkId) -> Result<Vec<SignedRecord>> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT author, version, body, signature FROM signed_records
|
||||
WHERE network_id = ?1",
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot read signed records: {err}")))?;
|
||||
let rows = stmt
|
||||
.query_map(params![network_id.as_bytes().as_slice()], |row| {
|
||||
let author: Vec<u8> = row.get(0)?;
|
||||
let version: i64 = row.get(1)?;
|
||||
let body: Vec<u8> = row.get(2)?;
|
||||
let signature: Vec<u8> = row.get(3)?;
|
||||
Ok((author, version, body, signature))
|
||||
})
|
||||
.map_err(|err| Error::Storage(format!("cannot read signed records: {err}")))?;
|
||||
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (author, version, body, signature) =
|
||||
row.map_err(|err| Error::Storage(format!("cannot read a record row: {err}")))?;
|
||||
let Ok(author) = <[u8; 32]>::try_from(author.as_slice()) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(body) = postcard::from_bytes(&body) else {
|
||||
continue;
|
||||
};
|
||||
out.push(SignedRecord {
|
||||
author,
|
||||
network: *network_id.as_bytes(),
|
||||
version: version as u64,
|
||||
body,
|
||||
signature,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Stores a record received from somebody else.
|
||||
pub fn put_signed_record(&self, record: &SignedRecord) -> Result<()> {
|
||||
let body = postcard::to_stdvec(&record.body)
|
||||
.map_err(|err| Error::Storage(format!("cannot encode a record body: {err}")))?;
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO signed_records (network_id, author, version, body, signature)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(network_id, author) DO UPDATE SET
|
||||
version = excluded.version,
|
||||
body = excluded.body,
|
||||
signature = excluded.signature",
|
||||
params![
|
||||
record.network.as_slice(),
|
||||
record.author.as_slice(),
|
||||
record.version as i64,
|
||||
body,
|
||||
record.signature
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store a signed record: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stores one of **our own** records and bumps our counter, atomically.
|
||||
///
|
||||
/// The model requires that a record and the author's own version counter
|
||||
/// are committed together, and **before** the record is published, so a
|
||||
/// crash can never leave us able to reuse a version number we already put
|
||||
/// on the wire.
|
||||
pub fn publish_own_record(&self, record: &SignedRecord) -> Result<()> {
|
||||
let body = postcard::to_stdvec(&record.body)
|
||||
.map_err(|err| Error::Storage(format!("cannot encode a record body: {err}")))?;
|
||||
let transaction = self
|
||||
.conn
|
||||
.unchecked_transaction()
|
||||
.map_err(|err| Error::Storage(format!("cannot begin a transaction: {err}")))?;
|
||||
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO signed_records (network_id, author, version, body, signature)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5)
|
||||
ON CONFLICT(network_id, author) DO UPDATE SET
|
||||
version = excluded.version,
|
||||
body = excluded.body,
|
||||
signature = excluded.signature",
|
||||
params![
|
||||
record.network.as_slice(),
|
||||
record.author.as_slice(),
|
||||
record.version as i64,
|
||||
body,
|
||||
record.signature
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store our record: {err}")))?;
|
||||
transaction
|
||||
.execute(
|
||||
"INSERT INTO own_record_version (network_id, author, version)
|
||||
VALUES (?1, ?2, ?3)
|
||||
ON CONFLICT(network_id, author) DO UPDATE SET
|
||||
version = max(version, excluded.version)",
|
||||
params![
|
||||
record.network.as_slice(),
|
||||
record.author.as_slice(),
|
||||
record.version as i64
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot store our version: {err}")))?;
|
||||
|
||||
transaction
|
||||
.commit()
|
||||
.map_err(|err| Error::Storage(format!("cannot commit our record: {err}")))
|
||||
}
|
||||
|
||||
/// The highest version an author has ever published for a network.
|
||||
///
|
||||
/// Monotonic even if the record is later replaced by a conflicting one,
|
||||
/// so a number is never reused. Keyed by author as well: a replaced
|
||||
/// device key is a different author and starts its own sequence, while
|
||||
/// the outgoing one keeps its place so the release it signs on the way
|
||||
/// out cannot collide with something it already published.
|
||||
pub fn own_record_version(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
author: iroh::EndpointId,
|
||||
) -> Result<u64> {
|
||||
let version: Option<i64> = self
|
||||
.conn
|
||||
.query_row(
|
||||
"SELECT version FROM own_record_version WHERE network_id = ?1 AND author = ?2",
|
||||
params![
|
||||
network_id.as_bytes().as_slice(),
|
||||
author.as_bytes().as_slice()
|
||||
],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(|err| Error::Storage(format!("cannot read our version: {err}")))?;
|
||||
Ok(version.unwrap_or(0).max(0) as u64)
|
||||
}
|
||||
|
||||
/// Forgets every record of a network.
|
||||
pub fn forget_signed_records(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM signed_records WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice()],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot clear signed records: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remembers the hostname a member last announced.
|
||||
pub fn remember_peer_hostname(
|
||||
&self,
|
||||
network_id: NetworkId,
|
||||
endpoint_id: &[u8; 32],
|
||||
hostname: &str,
|
||||
) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO peer_hostnames (network_id, endpoint_id, hostname)
|
||||
VALUES (?1, ?2, ?3)
|
||||
ON CONFLICT(network_id, endpoint_id) DO UPDATE SET hostname = excluded.hostname",
|
||||
params![
|
||||
network_id.as_bytes().as_slice(),
|
||||
endpoint_id.as_slice(),
|
||||
hostname
|
||||
],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot remember a hostname: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The last hostname every member of a network announced.
|
||||
pub fn peer_hostnames(&self, network_id: NetworkId) -> Result<Vec<([u8; 32], String)>> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT endpoint_id, hostname FROM peer_hostnames WHERE network_id = ?1")
|
||||
.map_err(|err| Error::Storage(format!("cannot read hostnames: {err}")))?;
|
||||
let rows = stmt
|
||||
.query_map(params![network_id.as_bytes().as_slice()], |row| {
|
||||
Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, String>(1)?))
|
||||
})
|
||||
.map_err(|err| Error::Storage(format!("cannot read hostnames: {err}")))?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (id, hostname) =
|
||||
row.map_err(|err| Error::Storage(format!("cannot read hostnames: {err}")))?;
|
||||
if let Ok(id) = <[u8; 32]>::try_from(id.as_slice()) {
|
||||
out.push((id, hostname));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Forgets every remembered hostname of a network.
|
||||
pub fn forget_peer_hostnames(&self, network_id: NetworkId) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"DELETE FROM peer_hostnames WHERE network_id = ?1",
|
||||
params![network_id.as_bytes().as_slice()],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot forget hostnames: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads an arbitrary setting.
|
||||
pub fn get_setting(&self, key: &str) -> Result<Option<String>> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT value FROM settings WHERE key = ?1",
|
||||
params![key],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()
|
||||
.map_err(|err| Error::Storage(format!("cannot read setting `{key}`: {err}")))
|
||||
}
|
||||
|
||||
/// Writes an arbitrary setting.
|
||||
pub fn set_setting(&self, key: &str, value: &str) -> Result<()> {
|
||||
self.conn
|
||||
.execute(
|
||||
"INSERT INTO settings (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
params![key, value],
|
||||
)
|
||||
.map_err(|err| Error::Storage(format!("cannot write setting `{key}`: {err}")))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Schema for the signed records described in [`crate::state`].
|
||||
///
|
||||
/// The version counter is keyed by author as well as network. A device key
|
||||
/// can be replaced, and the replacement is a different author: it must start
|
||||
/// its own sequence rather than inherit one, and the outgoing author's last
|
||||
/// version has to survive so its release record cannot collide with
|
||||
/// something it already published.
|
||||
const SIGNED_RECORDS_SCHEMA: &str = "BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS signed_records (
|
||||
network_id BLOB NOT NULL,
|
||||
author BLOB NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
body BLOB NOT NULL,
|
||||
signature BLOB NOT NULL,
|
||||
PRIMARY KEY (network_id, author)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS own_record_version (
|
||||
network_id BLOB NOT NULL,
|
||||
author BLOB NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
PRIMARY KEY (network_id, author)
|
||||
);
|
||||
PRAGMA user_version = 3;
|
||||
COMMIT;";
|
||||
|
||||
/// Seconds since the Unix epoch, saturating at 0 before it.
|
||||
pub(crate) fn now_unix() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod broadcast_storage_tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use crate::identity::NetworkKeys;
|
||||
|
||||
#[test]
|
||||
fn exit_node_choices_are_off_by_default_and_one_choice_clears_the_others() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = StateStore::open(dir.path().join("state.sqlite")).unwrap();
|
||||
let secret = NetworkSecret::from_bytes([5; 32]).unwrap();
|
||||
let make = |name: &str| {
|
||||
let name = NetworkName::new(name).unwrap();
|
||||
let id = NetworkKeys::derive(&name, &secret).network_id();
|
||||
store.upsert_network(id, &name, &secret, true).unwrap();
|
||||
id
|
||||
};
|
||||
let (a, b) = (make("exit-a"), make("exit-b"));
|
||||
let listed = || store.list_networks().unwrap();
|
||||
assert!(
|
||||
listed()
|
||||
.iter()
|
||||
.all(|n| !n.exit_node && n.exit_via.is_none())
|
||||
);
|
||||
|
||||
store.set_exit_node(a, true).unwrap();
|
||||
store.set_exit_via(a, Some(&[7; 32])).unwrap();
|
||||
store.set_exit_via(b, Some(&[8; 32])).unwrap();
|
||||
let by_id = |id: NetworkId| listed().into_iter().find(|n| n.network_id == id).unwrap();
|
||||
assert!(by_id(a).exit_node, "offering is per network and kept");
|
||||
assert_eq!(by_id(a).exit_via, None, "one default route: a was cleared");
|
||||
assert_eq!(by_id(b).exit_via, Some([8; 32]));
|
||||
|
||||
store.set_exit_via(b, None).unwrap();
|
||||
assert_eq!(by_id(b).exit_via, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_remembered_hostname_survives_a_restart_and_follows_the_latest_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("state.sqlite");
|
||||
let name = NetworkName::new("hostnames").unwrap();
|
||||
let secret = NetworkSecret::from_bytes([9; 32]).unwrap();
|
||||
let id = NetworkKeys::derive(&name, &secret).network_id();
|
||||
let peer = [3u8; 32];
|
||||
|
||||
let store = StateStore::open(&path).unwrap();
|
||||
store.remember_peer_hostname(id, &peer, "laptop").unwrap();
|
||||
store.remember_peer_hostname(id, &peer, "laptop-2").unwrap();
|
||||
drop(store);
|
||||
|
||||
let store = StateStore::open(&path).unwrap();
|
||||
assert_eq!(
|
||||
store.peer_hostnames(id).unwrap(),
|
||||
vec![(peer, "laptop-2".to_string())]
|
||||
);
|
||||
store.forget_peer_hostnames(id).unwrap();
|
||||
assert!(store.peer_hostnames(id).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v3_migration_preserves_identity_and_networks_and_defaults_broadcast_on() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("state.sqlite");
|
||||
let name = NetworkName::new("migration-broadcast").unwrap();
|
||||
let secret = NetworkSecret::from_bytes([7; 32]).unwrap();
|
||||
let id = NetworkKeys::derive(&name, &secret).network_id();
|
||||
let store = StateStore::open(&path).unwrap();
|
||||
let identity = store
|
||||
.load_or_create_device_identity()
|
||||
.unwrap()
|
||||
.endpoint_id();
|
||||
store.upsert_network(id, &name, &secret, false).unwrap();
|
||||
store.set_hostname("old-host").unwrap();
|
||||
store
|
||||
.conn
|
||||
.execute_batch(
|
||||
"ALTER TABLE networks DROP COLUMN broadcast; \
|
||||
ALTER TABLE networks DROP COLUMN exit_node; \
|
||||
ALTER TABLE networks DROP COLUMN exit_via; \
|
||||
PRAGMA user_version=3;",
|
||||
)
|
||||
.unwrap();
|
||||
drop(store);
|
||||
let store = StateStore::open(&path).unwrap();
|
||||
let networks = store.list_networks().unwrap();
|
||||
assert_eq!(networks.len(), 1);
|
||||
assert_eq!(networks[0].network_id, id);
|
||||
assert!(!networks[0].auto_start);
|
||||
assert!(networks[0].broadcast);
|
||||
assert_eq!(store.hostname().unwrap().as_deref(), Some("old-host"));
|
||||
assert_eq!(
|
||||
store
|
||||
.load_or_create_device_identity()
|
||||
.unwrap()
|
||||
.endpoint_id(),
|
||||
identity
|
||||
);
|
||||
store.set_broadcast(id, false).unwrap();
|
||||
store.upsert_network(id, &name, &secret, true).unwrap();
|
||||
drop(store);
|
||||
let store = StateStore::open(&path).unwrap();
|
||||
assert!(
|
||||
!store.list_networks().unwrap()[0].broadcast,
|
||||
"rejoin and restart preserve opt-out"
|
||||
);
|
||||
store.remove_network(id).unwrap();
|
||||
store.upsert_network(id, &name, &secret, true).unwrap();
|
||||
assert!(
|
||||
store.list_networks().unwrap()[0].broadcast,
|
||||
"forgotten network gets defaults"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user