signer: drop replayed and stale NIP-46 requests (H1)

kind:24133 is ephemeral, so every relay delivery of a captured request reached the responder again. A ReplayGuard in the responder loop now drops an event whose created_at is outside a 120 s window (or predates this run) and any event id already seen.
This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 12b78c848c
commit a5a1788319
2 files changed
+260 -3

No files matched your search

+10
View File
@@ -98,6 +98,16 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
`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.
- **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
captured request. `signer::ReplayGuard`, checked in the responder loop before
`handle_request`, drops a wrapper event whose `created_at` is more than
`REQUEST_FRESHNESS` (120 s) from now, one minted before this run started, and
any event id already seen (bounded by `SEEN_CAPACITY`). The dedup is **in
memory only**: a stop/start cycle inside the freshness window re-admits a
request minted shortly before the restart (a persisted high-water mark is the
documented alternative; not implemented).
- Approvals go through `signer::approval::Approver`: the responder asks over a
channel, the dialog answers, and **a timeout or a missing UI denies** — never
allows. Client names/URLs shown in the dialog are client-supplied and must be
+250 -3
View File
@@ -7,10 +7,10 @@
//! Every sensitive request is put to the user (M4); "allow always" stores a
//! per-app permission, and every answer is recorded in the activity log (M5).
use std::collections::HashMap;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use std::time::{Duration, Instant};
use nostr::nips::{nip04, nip44};
use nostr::prelude::*;
@@ -200,6 +200,89 @@ fn app_identity(config: &SignerConfig, client: &PublicKey) -> std::result::Resul
.ok_or_else(|| "this application has no identity key".to_string())
}
/// How far a request's `created_at` may deviate from now, either way.
const REQUEST_FRESHNESS: Duration = Duration::from_secs(120);
/// Upper bound on the replay window's seen-id set.
const SEEN_CAPACITY: usize = 4096;
/// Drops replayed or stale NIP-46 requests.
///
/// `kind:24133` is ephemeral, so the relay layer never stores or deduplicates it
/// (nostr-sdk rejects it as `Rejected(Ephemeral)`) and every delivery of the same
/// event reaches the responder again — from a second relay, a reconnect, or an
/// attacker replaying a captured request. Without this guard a captured request
/// could mint fresh signatures, force a `logout`, burn the rate limit, or flood
/// prompts.
///
/// Freshness is wall-clock ([`Timestamp`], as `created_at` is); the in-memory age
/// of a seen id is monotonic ([`Instant`]), so a wall-clock step cannot make a
/// seen id look fresh again.
struct ReplayGuard {
/// When this run started, for the cross-restart bound.
started_at: Timestamp,
/// Seen event ids, with the monotonic instant they were seen.
seen: Mutex<HashMap<EventId, Instant>>,
/// The same ids in insertion order, for capacity eviction (a `HashMap` has
/// no age order).
order: Mutex<VecDeque<EventId>>,
}
impl ReplayGuard {
fn new() -> Self {
Self {
started_at: Timestamp::now(),
seen: Mutex::new(HashMap::new()),
order: Mutex::new(VecDeque::new()),
}
}
/// Whether a request should be processed. Returns `false` (drop silently —
/// never log per drop, which would be an attacker-controlled stderr tap) for
/// a wrapper `created_at` outside the freshness window, a request minted
/// before this run, or an id already seen.
fn accept(&self, event: &Event) -> bool {
let now = Timestamp::now();
let created = event.created_at;
if created > now + REQUEST_FRESHNESS || created + REQUEST_FRESHNESS < now {
return false;
}
// Belt-and-braces against clock skew; implied by the freshness rule in
// the common case.
if created + REQUEST_FRESHNESS < self.started_at {
return false;
}
let mut seen = self.seen.lock().unwrap();
if seen.contains_key(&event.id) {
return false;
}
seen.insert(event.id, Instant::now());
let mut order = self.order.lock().unwrap();
order.push_back(event.id);
while order.len() > SEEN_CAPACITY {
if let Some(oldest) = order.pop_front() {
seen.remove(&oldest);
}
}
// Expire ids older than the window; insertion order is age order for the
// monotonic ages stored here.
let cutoff = Instant::now();
while let Some(front) = order.front() {
let expired = seen
.get(front)
.map(|at| cutoff.duration_since(*at) > REQUEST_FRESHNESS)
.unwrap_or(true);
if !expired {
break;
}
let oldest = order.pop_front().unwrap();
seen.remove(&oldest);
}
true
}
}
pub struct Signer {
config: Arc<SignerConfig>,
client: Client,
@@ -261,12 +344,14 @@ impl Signer {
client.subscribe(targets).await?;
let running = Arc::new(AtomicBool::new(true));
let replay = ReplayGuard::new();
{
let (client, config, running, response_targets) = (
let (client, config, running, response_targets, replay) = (
client.clone(),
Arc::clone(&config),
Arc::clone(&running),
Arc::clone(&response_targets),
replay,
);
tokio::spawn(async move {
while running.load(Ordering::SeqCst) {
@@ -279,6 +364,11 @@ impl Signer {
if event.kind != Kind::NostrConnect {
continue;
}
// Drop a replayed, duplicated or stale request before it can
// reach the user or the policy gate (H1).
if !replay.accept(&event) {
continue;
}
match handle_request(&event, &config).await {
Ok(Some(response)) => {
// Clone the targets under a short lock; the lock is
@@ -1656,6 +1746,33 @@ mod tests {
client.sign_event(unsigned).expect("sign the request")
}
/// The same as [`client_request`], with an explicit `created_at` so a test
/// can build a stale or future-dated request.
fn client_request_at(
client: &Keys,
device: &PublicKey,
method: &str,
params: serde_json::Value,
created_at: Timestamp,
) -> Event {
let envelope = serde_json::json!({ "id": "test", "method": method, "params": params });
let content = nip44::encrypt(
client.secret_key(),
device,
envelope.to_string(),
nip44::Version::V2,
)
.expect("encrypt the request");
let unsigned = UnsignedEvent::new(
client.public_key(),
created_at,
Kind::NostrConnect,
[Tag::public_key(*device)],
content,
);
client.sign_event(unsigned).expect("sign the request")
}
/// Decrypt a response the way the client would.
fn read_response(response: &Event, client: &Keys, device: &PublicKey) -> serde_json::Value {
let plain =
@@ -2746,4 +2863,134 @@ mod tests {
assert!(answer["error"].is_string(), "got {answer}");
assert!(answer["result"].is_null());
}
fn guard_event(created_at: Timestamp) -> Event {
let keys = Keys::generate();
let unsigned = UnsignedEvent::new(
keys.public_key(),
created_at,
Kind::NostrConnect,
Vec::new(),
"x",
);
keys.sign_event(unsigned).expect("sign")
}
/// A fresh request is accepted once; the same event id again is dropped.
#[test]
fn the_replay_guard_accepts_an_id_once() {
let guard = ReplayGuard::new();
let event = guard_event(Timestamp::now());
assert!(guard.accept(&event));
assert!(!guard.accept(&event), "a replayed id is dropped");
}
/// A request outside the freshness window is dropped, either way.
#[test]
fn the_replay_guard_drops_stale_and_future_requests() {
let guard = ReplayGuard::new();
let stale = guard_event(Timestamp::now() - Duration::from_secs(600));
assert!(!guard.accept(&stale), "an old request is stale");
let future = guard_event(Timestamp::now() + Duration::from_secs(600));
assert!(!guard.accept(&future), "a future request is not live");
}
/// A request minted before this run is dropped (cross-restart replay). This
/// is implied by the freshness rule in the common case; kept as a bound.
#[test]
fn the_replay_guard_drops_a_pre_run_request() {
let guard = ReplayGuard::new();
let old = guard_event(Timestamp::now() - Duration::from_secs(300));
assert!(!guard.accept(&old));
}
/// Poll `predicate` until it is true or `timeout` elapses.
async fn wait_until(mut predicate: impl FnMut() -> bool, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if predicate() {
return true;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
predicate()
}
/// The replay guard is wired into the running responder, not only unit
/// tested: the same signed request delivered by **two relays** must produce
/// exactly one ask, and a stale-dated one must produce none.
#[tokio::test]
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
async fn a_replayed_request_is_answered_once() {
let mut relay_a = TestRelay::local().await;
let mut relay_b = TestRelay::local().await;
let (approver, _approvals, seen) = recording_approver(|_| Decision::Always);
let mut config = config(&relay_a.relay, approver);
config.relays = vec![relay_a.relay.clone(), relay_b.relay.clone()];
let device = config.device_keys.public_key();
let signer = Signer::start(config).await.expect("start signer");
// Two publishers, one per relay.
let pub_a = Client::new();
pub_a.add_relay(relay_a.relay.clone()).await.expect("add a");
let pub_b = Client::new();
pub_b.add_relay(relay_b.relay.clone()).await.expect("add b");
pub_a.connect().await;
pub_b.connect().await;
pub_a.connect().and_wait(Duration::from_secs(15)).await;
pub_b.connect().and_wait(Duration::from_secs(15)).await;
let client = Keys::generate();
let connect = client_request(
&client,
&device,
"connect",
serde_json::json!(["", "test-secret", "", ""]),
);
pub_a.send_event(&connect).await.expect("publish connect");
assert!(
wait_until(
|| seen
.lock()
.unwrap()
.iter()
.any(|request| matches!(request, Request::Pair { .. })),
Duration::from_secs(10),
)
.await,
"the pairing should reach the responder"
);
// The same signed request on both relays: one ask, not two.
let request = client_request(&client, &device, "sign_event", sign_params(1, "hi"));
pub_a.send_event(&request).await.expect("publish a");
pub_b.send_event(&request).await.expect("publish b");
assert!(
wait_until(|| sign_asks(&seen) >= 1, Duration::from_secs(10)).await,
"the request should reach the responder"
);
tokio::time::sleep(Duration::from_secs(2)).await;
assert_eq!(
sign_asks(&seen),
1,
"a request delivered twice must be answered once"
);
// A request minted long ago is dropped by the freshness window.
let stale = client_request_at(
&client,
&device,
"sign_event",
sign_params(1, "old"),
Timestamp::now() - Duration::from_secs(600),
);
pub_a.send_event(&stale).await.expect("publish stale");
tokio::time::sleep(Duration::from_secs(2)).await;
assert_eq!(sign_asks(&seen), 1, "a stale request must be dropped");
signer.stop().await;
relay_a.stop();
relay_b.stop();
}
}