policy: share the auto-approval limit with the running signer (M6)

This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 5a9fc6ee18
commit 5d750fb0d3
7 files changed
+129 -10

No files matched your search

+8 -1
View File
@@ -97,7 +97,14 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
- **Rate limit.** `signer::policy::RateLimiter` caps silent answers per app:
`auto-approve-limit` requests per minute (GSettings, default **30**). Past the
cap the request is asked again, so a runaway or compromised client turns back
into prompts instead of an open tap. Zero means never answer silently.
into prompts instead of an open tap. Zero means never answer silently. The
limit is a live `Arc<AtomicU32>` view of the setting, shared with the running
signer (`AppState::auto_approve_limit`; a `connect_changed` handler keeps it in
step), so setting it to 0 stops silent answers **immediately** — no stop/start,
and an external `gsettings set` is honoured too. The handler is installed on
the `gio::Settings` instance `AppState` holds for the process: it is owned by
that GObject and would die with it, and a bare `SignalHandlerId` keeps nothing
alive.
- **Replay and freshness (H1).** `kind:24133` is ephemeral, so the relay layer
never stores or deduplicates it: every delivery of the same event reaches the
responder again — a second relay, a reconnect, or an attacker replaying a
+9
View File
@@ -49,6 +49,15 @@ impl Config {
}
}
/// The underlying `gio::Settings`.
///
/// The long-lived caller must own this instance for as long as it needs the
/// `connect_changed` handler it installs: the handler is owned by the
/// GObject and dies with it (see `AppState`).
pub(crate) fn settings(&self) -> &gio::Settings {
&self.settings
}
/// The identity selected in the UI: it scopes the Apps/Activity pages and
/// is the default for new pairings. `None` means "the first stored key".
pub fn current_identity(&self) -> Option<PublicKey> {
+2 -1
View File
@@ -14,6 +14,7 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::AtomicU32;
use std::sync::{Arc, Mutex};
use glib::prelude::ToVariant;
@@ -155,7 +156,7 @@ async fn serve(
settings.relays(),
approver,
Arc::clone(&registry),
settings.auto_approve_limit(),
Arc::new(AtomicU32::new(settings.auto_approve_limit())),
activity.clone(),
changes.clone(),
names,
+3 -1
View File
@@ -180,7 +180,9 @@ impl SignerRunner {
let settings = Config::new();
let relays = settings.relays();
let auto_approve_limit = settings.auto_approve_limit();
// A live handle: the signer enforces the auto-approval limit from this
// `Arc`, so a change in Preferences applies without a restart.
let auto_approve_limit = self.state.auto_approve_limit();
// Only `Send` handles go into the async task; the runner and its widget
// stay on the main thread.
+3 -3
View File
@@ -9,7 +9,7 @@
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::{Duration, Instant};
use nostr::nips::{nip04, nip44};
@@ -138,7 +138,7 @@ impl SignerConfig {
relays: Vec<String>,
approver: Approver,
registry: Arc<Mutex<AppRegistry>>,
auto_approve_limit: u32,
auto_approve_limit: Arc<AtomicU32>,
activity: ActivityLog,
changes: async_channel::Sender<()>,
names: Arc<Mutex<HashMap<String, String>>>,
@@ -154,7 +154,7 @@ impl SignerConfig {
approver,
extra_relays: Vec::new(),
registry,
rate: RateLimiter::new(auto_approve_limit),
rate: RateLimiter::with_limit(auto_approve_limit),
activity,
changes,
})
+33 -3
View File
@@ -8,7 +8,8 @@
//! [`Permission`]: crate::store::apps::Permission
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
/// The window over which auto-approvals are counted.
@@ -17,13 +18,24 @@ pub const WINDOW: Duration = Duration::from_secs(60);
/// Caps how many requests a stored "always" permission answers silently, per
/// application. Past the cap Regent asks again, so a runaway or compromised
/// client turns back into prompts instead of an open tap.
///
/// The limit is a shared [`AtomicU32`], not a stored value, so lowering it in
/// Preferences — to 0, say, to stop a runaway client — applies to the running
/// signer immediately, without a stop/start.
pub struct RateLimiter {
limit: u32,
limit: Arc<AtomicU32>,
recent: Mutex<HashMap<String, VecDeque<Instant>>>,
}
impl RateLimiter {
/// A limiter with a fixed limit. Used by the test configs.
#[cfg(test)]
pub fn new(limit: u32) -> Self {
Self::with_limit(Arc::new(AtomicU32::new(limit)))
}
/// A limiter whose limit is a live view of a shared value.
pub fn with_limit(limit: Arc<AtomicU32>) -> Self {
Self {
limit,
recent: Mutex::new(HashMap::new()),
@@ -34,6 +46,7 @@ impl RateLimiter {
/// [`WINDOW`] is still under the limit. `false` means the request must be
/// put to the user after all.
pub fn claim(&self, app: &str) -> bool {
let limit = self.limit.load(Ordering::Relaxed);
let now = Instant::now();
let mut recent = self.recent.lock().unwrap();
let answers = recent.entry(app.to_string()).or_default();
@@ -43,7 +56,7 @@ impl RateLimiter {
{
answers.pop_front();
}
if answers.len() as u32 >= self.limit {
if answers.len() as u32 >= limit {
return false;
}
answers.push_back(now);
@@ -69,4 +82,21 @@ mod tests {
let limiter = RateLimiter::new(0);
assert!(!limiter.claim("a"));
}
/// The limit is live: lowering it (to 0) must stop silent answers on the
/// next claim, without a restart — that is the whole point of M6.
#[test]
fn the_limit_can_change_while_the_limiter_is_alive() {
let shared = Arc::new(AtomicU32::new(2));
let limiter = RateLimiter::with_limit(Arc::clone(&shared));
assert!(limiter.claim("a"));
assert!(limiter.claim("a"));
assert!(!limiter.claim("a"), "at the cap");
shared.store(0, Ordering::Relaxed);
assert!(!limiter.claim("b"), "zero halts silent answers at once");
shared.store(5, Ordering::Relaxed);
assert!(limiter.claim("b"), "and raising it resumes");
}
}
+71 -1
View File
@@ -6,6 +6,7 @@ use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use nostr::nips::nip19::ToBech32;
@@ -13,6 +14,7 @@ use nostr::prelude::PublicKey;
use gtk::gdk;
use gtk::gio;
use gtk::gio::prelude::SettingsExt;
use crate::config::Config;
use crate::runtime;
@@ -73,6 +75,13 @@ pub struct AppState {
/// 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>>,
/// Preferences, held for the process: the `auto-approve-limit`
/// `connect_changed` handler is owned by its `gio::Settings` instance and
/// dies when that instance is finalized. Never read after construction —
/// the underscore is deliberate.
_config: Config,
/// A live view of `auto-approve-limit`, shared with the running signer.
auto_approve_limit: Arc<AtomicU32>,
}
impl AppState {
@@ -84,11 +93,28 @@ impl AppState {
pub fn new() -> Result<Rc<Self>, KeyError> {
let store = Arc::new(KeyStore::connect()?);
let (changes, changes_rx) = async_channel::bounded(1);
// The auto-approval limit is a live view of the setting: the signer
// shares this `Arc`, so a change — including 0, or one made outside the
// UI — applies immediately. `Config` is held on the state because the
// handler is owned by its `gio::Settings`, which must stay alive.
let config = Config::new();
let auto_approve_limit = Arc::new(AtomicU32::new(config.auto_approve_limit()));
{
let limit = Arc::clone(&auto_approve_limit);
let _ = config
.settings()
.connect_changed(Some("auto-approve-limit"), move |settings, _key| {
let value = settings.int("auto-approve-limit").max(0) as u32;
limit.store(value, Ordering::Relaxed);
});
}
let state = Rc::new(Self {
store,
registry: Arc::new(Mutex::new(AppRegistry::load())),
activity: ActivityLog::new(),
current: Arc::new(Mutex::new(Config::new().current_identity())),
current: Arc::new(Mutex::new(config.current_identity())),
names: Arc::new(Mutex::new(HashMap::new())),
profiles: Profiles::new(),
icons: Rc::new(IconStore::new()),
@@ -98,6 +124,8 @@ impl AppState {
change_listeners: RefCell::new(Vec::new()),
changes,
sleep_subscriptions: RefCell::new(Vec::new()),
_config: config,
auto_approve_limit,
});
{
@@ -665,6 +693,13 @@ impl AppState {
self.changes.clone()
}
/// The auto-approval limit as a live, shared value. The running signer reads
/// it on every silent answer; a settings change updates it through the
/// `connect_changed` handler installed in `AppState::new`.
pub fn auto_approve_limit(&self) -> Arc<AtomicU32> {
Arc::clone(&self.auto_approve_limit)
}
/// Register a listener for key/store changes. It runs immediately: the
/// vault is already open by the time any view is built.
pub fn listen(&self, listener: impl Fn() + 'static) {
@@ -800,4 +835,39 @@ mod tests {
"the identity's avatar stays"
);
}
/// The auto-approval limit is a live view of the setting: a change on the
/// `gio::Settings` instance the handler is installed on updates the shared
/// `Arc` synchronously (M6). Skipped when the schema is not installed — a
/// plain `cargo test` without `GSETTINGS_SCHEMA_DIR`, where `Settings::new`
/// aborts rather than erroring.
#[test]
fn the_auto_approval_limit_round_trips_through_the_setting() {
if gio::SettingsSchemaSource::default()
.and_then(|source| source.lookup(crate::APP_ID, true))
.is_none()
{
return;
}
let config = Config::new();
let original = config.auto_approve_limit();
let limit = Arc::new(AtomicU32::new(original));
{
let limit = Arc::clone(&limit);
let _ = config
.settings()
.connect_changed(Some("auto-approve-limit"), move |settings, _key| {
limit.store(
settings.int("auto-approve-limit").max(0) as u32,
Ordering::Relaxed,
);
});
}
let changed = if original == 7 { 8 } else { 7 };
config.set_auto_approve_limit(changed);
assert_eq!(limit.load(Ordering::Relaxed), changed);
// Leave the setting as it was found.
config.set_auto_approve_limit(original);
assert_eq!(limit.load(Ordering::Relaxed), original);
}
}