app: take an unconditional single-instance lock (M4)

Both the GUI (in startup) and headless take an unconditional flock on regent.lock (0600); a refused instance short-circuits activate/open so it cannot pair.
This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 8df0357d13
commit dd089e1855
7 files changed
+193 -53

No files matched your search

+13 -5
View File
@@ -688,11 +688,19 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
client even without the secret — a client-initiated pairing proves key
possession by receiving our response. A new client still needs the secret.
- **One instance only.** Two signers on one device key fight over `apps.json`.
The GUI owns the D-Bus name `org.kosmos.raucao.Regent`; headless checks
`NameHasOwner` and exits "Regent is already running". With **no session bus**
(a server, an SSH box) the GUI cannot run either, so headless falls back to an
exclusive `flock` on `regent.lock` — which also catches two headless runs
started at once. The kernel drops the lock on exit, so it cannot go stale.
The GUI owns the D-Bus name `org.kosmos.raucao.Regent`, so `NameHasOwner` is the
friendly first message ("Regent is already running"), but it is **not** the
guard: a headless run owns no name, and with no session bus (a server, an SSH
box) neither does a GUI. Both the GUI (`application::run`'s `startup` handler)
and headless (`headless::serve`) therefore take an **unconditional** exclusive
`flock` on `regent.lock` (mode 0600) through `instance::claim`, which fails
closed if the lock file cannot be created or locked. That is what catches two
headless runs, a GUI beside a headless one, and a second GUI on a machine with
no session bus. The lock is taken in `startup`, which GLib emits only for the
primary instance, so a secondary forwarding a `nostrconnect://` link still
reaches the primary; a refused instance also short-circuits `activate`/`open`,
because `quit()` alone does not stop them being emitted. The kernel drops the
lock on exit, so it cannot go stale.
- Errors are loud: `--headless`/`--pair` print a message and exit non-zero for a
bad URI, an unreadable vault, no identity key, or a relay that refused the
connect response.
+44 -1
View File
@@ -29,7 +29,7 @@ export HOME=$TMP_HOME
export CARGO_HOME=${CARGO_HOME:-$ORIGINAL_HOME/.cargo}
cleanup() {
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} ${BACKGROUND:-} 2>/dev/null
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} ${BACKGROUND:-} ${LOCK_HOLDER:-} 2>/dev/null
wait 2>/dev/null
rm -rf "$TMP_HOME"
}
@@ -367,6 +367,49 @@ kill "$HEADLESS" "$SUBSCRIBER" 2>/dev/null
HEADLESS=
SUBSCRIBER=
printf '\n== the single-instance lock ==\n'
# A headless run holds the lock, so no second Regent — headless or GUI — may run
# on the same device key. This is the M4 fix: the lock is taken unconditionally,
# not only when there is no session bus.
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_PROFILE_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --headless --passphrase-file "$PASSPHRASE_FILE" \
>"$TMP_HOME/lock-holder.log" 2>&1 &
LOCK_HOLDER=$!
sleep 5
grep -q 'signer listening' "$TMP_HOME/lock-holder.log"
check $? "the lock-holding headless instance is running"
LOCKFILE="$TMP_HOME/.local/share/$DATA_DIR/regent.lock"
[ -f "$LOCKFILE" ] && [ "$(stat -c '%a' "$LOCKFILE")" = 600 ]
check $? "regent.lock exists and is mode 0600"
# A second headless run must refuse and exit non-zero.
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --headless --passphrase-file "$PASSPHRASE_FILE" \
>"$TMP_HOME/lock-second.log" 2>&1
[ $? -ne 0 ]
check $? "a second headless run exits non-zero"
grep -q 'already running' "$TMP_HOME/lock-second.log"
check $? "a second headless run says Regent is already running"
# The GUI must refuse too, and must not build a window or pair.
GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
timeout 8 "$ROOT/$BUILD/regent" >"$TMP_HOME/lock-gui.log" 2>&1
grep -q 'already running' "$TMP_HOME/lock-gui.log"
check $? "the GUI refuses while headless holds the lock"
! grep -q 'opening the main window' "$TMP_HOME/lock-gui.log"
check $? "and the refused GUI did not present a window"
kill "$LOCK_HOLDER" 2>/dev/null
sleep 1
LOCK_HOLDER=
printf '\n== first run: no keys, so no signer ==\n'
# With no keys there is nothing to sign with and nothing to listen for, so the
# identities window is the whole app and the signer never starts. A fresh HOME is
+1
View File
@@ -52,6 +52,7 @@ cargo_build = custom_target(binary_name,
'src/application.rs',
'src/config.rs',
'src/headless.rs',
'src/instance.rs',
'src/portal.rs',
'src/runner.rs',
'src/runtime.rs',
+27 -1
View File
@@ -136,14 +136,36 @@ pub fn run(args: &[String], background: bool) -> glib::ExitCode {
}
app.add_action(&focus);
app.connect_startup(|_| load_css());
// The single-instance lock is taken here, in `startup`, which GLib emits
// only for the **primary** instance: a secondary that is forwarding a
// `nostrconnect://` link never runs it, so link forwarding is unaffected.
// `quit()` alone does not stop `activate`/`open` from being emitted, so a
// refused instance also short-circuits both handlers below — otherwise it
// would build a window, flash it, and (on the open path) pair before exiting.
let refused = Rc::new(Cell::new(false));
{
let refused = Rc::clone(&refused);
app.connect_startup(move |app| {
if !crate::instance::claim() {
eprintln!("regent: another Regent is already running");
refused.set(true);
app.quit();
return;
}
load_css();
});
}
{
let windows = Rc::clone(&windows);
let refused = Rc::clone(&refused);
// `--background` (an autostart launch) opens with no window, but only
// for the launch itself: a later activation — the app icon, a
// notification click — is the user asking for the window.
let first = Cell::new(true);
app.connect_activate(move |_| {
if refused.get() {
return;
}
windows.build();
if first.replace(false) && background && windows.has_keys() {
// A `--background` launch is what autostart runs, but it is also
@@ -164,7 +186,11 @@ pub fn run(args: &[String], background: bool) -> glib::ExitCode {
// away — the same approval dialog as pasting a code, over the main window.
{
let windows = Rc::clone(&windows);
let refused = Rc::clone(&refused);
app.connect_open(move |_, files, _hint| {
if refused.get() {
return;
}
windows.build();
windows.present_primary();
for file in files {
+17 -46
View File
@@ -230,18 +230,15 @@ async fn finish_pairing(
/// True if another Regent is already running.
///
/// The GUI owns the app's D-Bus name, so that is the first check. With no
/// session bus at all (a server, an SSH box) the GUI cannot run either, so an
/// exclusive lock on `regent.lock` catches a second **headless** run — which the
/// D-Bus check alone never could. The kernel releases the lock on exit, so it
/// cannot go stale.
/// A GUI owns the app's D-Bus name, so that is the specific first check. But a
/// headless run owns no name, and with no session bus (a server, an SSH box)
/// neither does a GUI — so the real guard is the process-wide lock in
/// [`crate::instance`], taken by both the GUI and headless. It is also what
/// catches a GUI starting beside a headless run, which the D-Bus check never
/// could. The kernel releases the lock on exit, so it cannot go stale.
fn another_instance_running() -> Result<bool, String> {
let Some(connection) = session_bus() else {
return Ok(!claim_lock_file());
};
let reply = connection
.call_sync(
if let Some(connection) = session_bus() {
let reply = connection.call_sync(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
@@ -251,47 +248,21 @@ fn another_instance_running() -> Result<bool, String> {
gtk::gio::DBusCallFlags::NONE,
-1,
gtk::gio::Cancellable::NONE,
)
.map_err(|error| error.to_string())?;
let (owned,): (bool,) = reply.get().ok_or("unexpected NameHasOwner reply")?;
Ok(owned)
);
if let Ok(reply) = reply {
let (owned,): (bool,) = reply.get().ok_or("unexpected NameHasOwner reply")?;
if owned {
return Ok(true);
}
}
}
Ok(!crate::instance::claim())
}
fn session_bus() -> Option<gtk::gio::DBusConnection> {
gtk::gio::bus_get_sync(gtk::gio::BusType::Session, gtk::gio::Cancellable::NONE).ok()
}
/// Hold `regent.lock` for the life of the process. False if another process has
/// it. Failing to create the file is not a reason to refuse to run.
fn claim_lock_file() -> bool {
static LOCK: std::sync::OnceLock<std::fs::File> = std::sync::OnceLock::new();
if LOCK.get().is_some() {
return true;
}
let path = KeyStore::default_path().with_file_name("regent.lock");
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let Ok(file) = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&path)
else {
return true;
};
match file.try_lock() {
Ok(()) => {
let _ = LOCK.set(file);
true
}
Err(std::fs::TryLockError::WouldBlock) => false,
Err(std::fs::TryLockError::Error(_)) => true,
}
}
/// The passphrase for an unattended run: a systemd credential
/// (`$CREDENTIALS_DIRECTORY/regent-passphrase`) first, then `--passphrase-file`.
/// Never argv or the environment, and never logged.
+90
View File
@@ -0,0 +1,90 @@
//! The single-instance lock.
//!
//! Two Regents on one device key would both answer requests and race on
//! `apps.json`/`keys.json`, so exactly one process may run — GUI or headless.
//! The app's D-Bus name catches a second **GUI**, but a headless run owns no
//! name, and on a machine with no session bus neither check works at all. An
//! exclusive `flock` on `regent.lock` is the one mechanism that covers every
//! combination, so both the GUI and headless take it. The kernel drops the lock
//! when the process exits, so it cannot go stale.
use std::fs::File;
use std::path::Path;
use std::sync::OnceLock;
use crate::store::keys::KeyStore;
/// The held lock file, kept for the life of the process. `flock` conflicts
/// across two descriptors even within one process, so re-claiming has to be a
/// memo, not a second open.
static LOCK: OnceLock<File> = OnceLock::new();
/// Take the process-wide single-instance lock.
///
/// `true` when this process now holds it — including a repeat call in the same
/// process. **Fails closed:** a lock file that cannot be created or locked
/// returns `false`, so an unreadable data directory refuses to run rather than
/// running unlocked; `WouldBlock` (another process holds it) is the ordinary
/// `false`.
pub fn claim() -> bool {
if LOCK.get().is_some() {
return true;
}
let path = KeyStore::default_path().with_file_name("regent.lock");
match claim_at(&path) {
Ok(file) => {
let _ = LOCK.set(file);
true
}
Err(_) => false,
}
}
/// Open `path` (creating it and its directory, mode 0600) and take an exclusive,
/// non-blocking lock on it. The returned `File` **holds** the lock until it is
/// dropped; the caller keeps it for the life of the process.
fn claim_at(path: &Path) -> std::io::Result<File> {
if let Some(parent) = path.parent() {
// The claim runs before the vault is opened, so on a fresh machine the
// data directory may not exist yet.
std::fs::create_dir_all(parent)?;
}
let mut options = std::fs::OpenOptions::new();
options.create(true).write(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = options.open(path)?;
file.try_lock()?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
/// A second, independent open of the same lock file is refused while the
/// first is held, and succeeds again once it is dropped. Tested on a temp
/// path so it never touches (or races with) the real data directory.
#[test]
fn a_second_lock_on_the_same_file_is_refused() {
let dir = std::env::temp_dir().join(format!("regent-lock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("regent.lock");
let held = claim_at(&path).expect("the first claim succeeds");
assert!(
claim_at(&path).is_err(),
"a second claim must be refused while the first is held"
);
drop(held);
assert!(claim_at(&path).is_ok(), "the lock is free again once dropped");
let _ = std::fs::remove_dir_all(&dir);
}
}
+1
View File
@@ -6,6 +6,7 @@
mod application;
mod config;
mod headless;
mod instance;
mod portal;
mod runner;
mod runtime;