state: lock the vault on suspend and count sleep in the auto-lock (M5)
This commit is contained in:
5 files changed
+164
-8
No files matched your search
@@ -796,7 +796,15 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
- **Auto-lock is a hard timeout since the unlock** (`lock-timeout`, default
|
||||
900 s, 0 = never), checked by a 30 s `glib` timer in `state.rs`, plus "Lock
|
||||
now". It is deliberately **not** an idle timer that request traffic resets — a
|
||||
chatty client would hold the vault open forever. Headless never auto-locks
|
||||
chatty client would hold the vault open forever. The elapsed time is measured
|
||||
with **`CLOCK_BOOTTIME`** (`store::keys::boottime`), not `Instant`, because
|
||||
`CLOCK_MONOTONIC` stops while the machine is suspended — a laptop that slept
|
||||
through the timeout must still lock on resume. `boottime` is the **one `unsafe`
|
||||
call in the tree** (a `libc::clock_gettime`). The vault also locks immediately
|
||||
on **suspend** (`org.freedesktop.login1` `PrepareForSleep` on the system bus)
|
||||
and on the **screen locking** (`org.gnome.ScreenSaver.ActiveChanged` on the
|
||||
session bus) — both best-effort, since a machine without logind or a screen
|
||||
saver just keeps the timer. Headless never auto-locks
|
||||
(there is nobody to re-prompt). Dropping the cache triggers rust-nostr's
|
||||
`non_secure_erase`, a best-effort volatile overwrite with **no contract**; the
|
||||
docs must not pretend it is a guarantee.
|
||||
|
||||
Generated
+1
@@ -2016,6 +2016,7 @@ dependencies = [
|
||||
"image",
|
||||
"ksni",
|
||||
"libadwaita",
|
||||
"libc",
|
||||
"nostr",
|
||||
"nostr-sdk",
|
||||
"qrcode",
|
||||
|
||||
@@ -36,6 +36,10 @@ serde_json = { version = "1", features = ["preserve_order"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
zeroize = "1"
|
||||
base64 = "0.22"
|
||||
# The one `unsafe` in the tree: `CLOCK_BOOTTIME`, so the vault's auto-lock
|
||||
# timeout counts time spent suspended (`Instant` is `CLOCK_MONOTONIC`, which
|
||||
# stops during suspend). See `store::keys::boottime`.
|
||||
libc = "0.2"
|
||||
qrcode = { version = "0.14", features = ["image"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
|
||||
|
||||
+71
-2
@@ -12,6 +12,7 @@ use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use gtk::gdk;
|
||||
use gtk::gio;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::runtime;
|
||||
@@ -69,6 +70,9 @@ pub struct AppState {
|
||||
change_listeners: RefCell<Vec<Listener>>,
|
||||
/// The responder pings this after it changes the registry or the log.
|
||||
changes: async_channel::Sender<()>,
|
||||
/// The suspend and screen-lock hooks that lock the vault. Kept for the
|
||||
/// process: a `gio::SignalSubscription` unsubscribes when dropped.
|
||||
sleep_subscriptions: RefCell<Vec<gio::SignalSubscription>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -93,6 +97,7 @@ impl AppState {
|
||||
listeners: RefCell::new(Vec::new()),
|
||||
change_listeners: RefCell::new(Vec::new()),
|
||||
changes,
|
||||
sleep_subscriptions: RefCell::new(Vec::new()),
|
||||
});
|
||||
|
||||
{
|
||||
@@ -106,6 +111,7 @@ impl AppState {
|
||||
|
||||
state.refresh_identities();
|
||||
state.watch_auto_lock();
|
||||
state.watch_lock_on_sleep();
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
@@ -113,7 +119,8 @@ impl AppState {
|
||||
///
|
||||
/// A **hard** timeout measured from the unlock, not an idle timer that
|
||||
/// request traffic resets: otherwise a client that keeps asking would hold
|
||||
/// the keys open forever.
|
||||
/// the keys open forever. Measured with [`crate::store::keys::boottime`], so
|
||||
/// time spent suspended counts — `Instant` would not.
|
||||
fn watch_auto_lock(self: &Rc<Self>) {
|
||||
let state = Rc::clone(self);
|
||||
glib::timeout_add_seconds_local(30, move || {
|
||||
@@ -122,9 +129,10 @@ impl AppState {
|
||||
return glib::ControlFlow::Continue;
|
||||
}
|
||||
let store = state.store();
|
||||
let now = crate::store::keys::boottime();
|
||||
let expired = store
|
||||
.unlocked_at()
|
||||
.map(|at| at.elapsed() >= std::time::Duration::from_secs(timeout as u64))
|
||||
.map(|at| crate::store::keys::lock_expired(at, now, timeout))
|
||||
.unwrap_or(false);
|
||||
if expired {
|
||||
store.lock();
|
||||
@@ -135,6 +143,57 @@ impl AppState {
|
||||
});
|
||||
}
|
||||
|
||||
/// Lock the vault the moment the machine suspends or the screen locks.
|
||||
///
|
||||
/// The 30 s timer above would catch a long suspend eventually, but the vault
|
||||
/// should not stay open through one at all. Both hooks are best-effort: a
|
||||
/// machine without logind, or without a screen saver on the session bus,
|
||||
/// simply gets no hook and keeps the timer. The subscriptions are stored on
|
||||
/// the state because a `gio::SignalSubscription` unsubscribes when dropped.
|
||||
fn watch_lock_on_sleep(self: &Rc<Self>) {
|
||||
let mut subscriptions = Vec::new();
|
||||
|
||||
if let Ok(connection) =
|
||||
gio::bus_get_sync(gio::BusType::System, gio::Cancellable::NONE)
|
||||
{
|
||||
let state = Rc::clone(self);
|
||||
subscriptions.push(connection.subscribe_to_signal(
|
||||
Some("org.freedesktop.login1"),
|
||||
Some("org.freedesktop.login1.Manager"),
|
||||
Some("PrepareForSleep"),
|
||||
Some("/org/freedesktop/login1"),
|
||||
None,
|
||||
gio::DBusSignalFlags::NONE,
|
||||
move |signal: gio::DBusSignalRef| {
|
||||
if signal.parameters.child_value(0).get::<bool>().unwrap_or(false) {
|
||||
lock_on_sleep(&state, "suspend");
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
if let Ok(connection) =
|
||||
gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE)
|
||||
{
|
||||
let state = Rc::clone(self);
|
||||
subscriptions.push(connection.subscribe_to_signal(
|
||||
Some("org.gnome.ScreenSaver"),
|
||||
Some("org.gnome.ScreenSaver"),
|
||||
Some("ActiveChanged"),
|
||||
Some("/org/gnome/ScreenSaver"),
|
||||
None,
|
||||
gio::DBusSignalFlags::NONE,
|
||||
move |signal: gio::DBusSignalRef| {
|
||||
if signal.parameters.child_value(0).get::<bool>().unwrap_or(false) {
|
||||
lock_on_sleep(&state, "the screen locking");
|
||||
}
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
*self.sleep_subscriptions.borrow_mut() = subscriptions;
|
||||
}
|
||||
|
||||
/// Whether the vault still needs the passphrase.
|
||||
pub fn is_locked(&self) -> bool {
|
||||
self.store.is_locked()
|
||||
@@ -636,6 +695,16 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock the vault because the machine is going away (suspend, screen lock).
|
||||
fn lock_on_sleep(state: &AppState, reason: &str) {
|
||||
let store = state.store();
|
||||
if !store.is_locked() {
|
||||
store.lock();
|
||||
eprintln!("regent: the key vault locked on {reason}");
|
||||
state.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Which identity to keep selected after a refresh.
|
||||
///
|
||||
/// Prefer the **live** selection (a pick made while the refresh was in flight),
|
||||
|
||||
+79
-5
@@ -21,7 +21,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Instant;
|
||||
use std::time::Duration;
|
||||
|
||||
use nostr::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -93,8 +93,10 @@ pub struct KeyStore {
|
||||
path: PathBuf,
|
||||
state: Mutex<State>,
|
||||
unlocked: Mutex<Option<Unlocked>>,
|
||||
/// When the vault was opened, for the auto-lock timeout.
|
||||
unlocked_at: Mutex<Option<Instant>>,
|
||||
/// When the vault was opened, for the auto-lock timeout. Measured as
|
||||
/// [`boottime`] (seconds since boot, including suspend), not an `Instant`,
|
||||
/// so a machine that sleeps through the timeout still locks on resume.
|
||||
unlocked_at: Mutex<Option<Duration>>,
|
||||
}
|
||||
|
||||
impl KeyStore {
|
||||
@@ -188,7 +190,7 @@ impl KeyStore {
|
||||
}
|
||||
|
||||
/// When the vault was opened, for the auto-lock timer.
|
||||
pub fn unlocked_at(&self) -> Option<Instant> {
|
||||
pub fn unlocked_at(&self) -> Option<Duration> {
|
||||
*self.unlocked_at.lock().unwrap()
|
||||
}
|
||||
|
||||
@@ -204,7 +206,7 @@ impl KeyStore {
|
||||
.map_err(|error| format!("the unlock task failed: {error}"))??;
|
||||
|
||||
*self.unlocked.lock().unwrap() = Some(Unlocked { keys });
|
||||
*self.unlocked_at.lock().unwrap() = Some(Instant::now());
|
||||
*self.unlocked_at.lock().unwrap() = Some(boottime());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -483,6 +485,51 @@ impl KeyStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Monotonic time since boot, **including time spent suspended**.
|
||||
///
|
||||
/// The auto-lock timeout must count a laptop that slept through it, so it cannot
|
||||
/// use [`std::time::Instant`]: that is `CLOCK_MONOTONIC`, which on Linux stops
|
||||
/// while the machine is suspended. `CLOCK_BOOTTIME` keeps advancing. This is the
|
||||
/// single `unsafe` call in the tree.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn boottime() -> Duration {
|
||||
let mut ts = libc::timespec {
|
||||
tv_sec: 0,
|
||||
tv_nsec: 0,
|
||||
};
|
||||
// SAFETY: `ts` is a valid, writable `timespec` and `CLOCK_BOOTTIME` is a
|
||||
// valid clock id, so the call cannot read or write outside `ts`.
|
||||
let rc = unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut ts) };
|
||||
if rc == 0 {
|
||||
Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
|
||||
} else {
|
||||
wall_clock()
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-Linux fallback: the wall clock, in the same unit as [`boottime`].
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) fn boottime() -> Duration {
|
||||
wall_clock()
|
||||
}
|
||||
|
||||
/// Seconds since the Unix epoch. Coarser than [`boottime`] across a wall-clock
|
||||
/// step, but the same unit — and a vault that over-locks is safe.
|
||||
fn wall_clock() -> Duration {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the vault has been open longer than `timeout_secs`.
|
||||
///
|
||||
/// A `timeout_secs` of 0 means "never lock". A `now` before `unlocked_at` (a
|
||||
/// clock anomaly, which `CLOCK_BOOTTIME` cannot produce) does not lock: the
|
||||
/// timeout is best-effort safety, and the ordinary poll still runs.
|
||||
pub(crate) fn lock_expired(unlocked_at: Duration, now: Duration, timeout_secs: u32) -> bool {
|
||||
timeout_secs != 0 && now.saturating_sub(unlocked_at) >= Duration::from_secs(timeout_secs as u64)
|
||||
}
|
||||
|
||||
/// Decrypt every entry, so a wrong passphrase fails before anything is cached.
|
||||
///
|
||||
/// Each decrypted key is checked against the pubkey stored beside it: a
|
||||
@@ -790,4 +837,31 @@ mod tests {
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// The auto-lock timeout is measured from the unlock: under it, no lock; at
|
||||
/// it, lock. Zero means never, and a clock anomaly does not lock.
|
||||
#[test]
|
||||
fn the_auto_lock_timeout_counts_time_since_the_unlock() {
|
||||
let unlocked = Duration::from_secs(100);
|
||||
assert!(!lock_expired(unlocked, Duration::from_secs(130), 60));
|
||||
assert!(!lock_expired(unlocked, Duration::from_secs(159), 60));
|
||||
assert!(lock_expired(unlocked, Duration::from_secs(160), 60));
|
||||
assert!(lock_expired(unlocked, Duration::from_secs(500), 60));
|
||||
assert!(
|
||||
!lock_expired(unlocked, Duration::from_secs(86_400), 0),
|
||||
"zero means never lock"
|
||||
);
|
||||
assert!(
|
||||
!lock_expired(unlocked, Duration::from_secs(50), 60),
|
||||
"a clock anomaly must not lock"
|
||||
);
|
||||
}
|
||||
|
||||
/// `boottime` is monotonic; the auto-lock comparison relies on it.
|
||||
#[test]
|
||||
fn boottime_does_not_go_backwards() {
|
||||
let first = boottime();
|
||||
let second = boottime();
|
||||
assert!(second >= first);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user