signer: drop strangers silently and dispatch with bounded concurrency (M8)

This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent 75f4998ced
commit 0f983ff558
4 files changed
+111 -45

No files matched your search

+9 -1
View File
@@ -83,10 +83,18 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
`get_relays`, `switch_relays`, `ping`, `sign_event`,
`nip04/nip44_encrypt|decrypt`.
- **Approved ≠ silent (M4).** A client that is not in the registry gets no answer
to anything except `connect`; an approved client is remembered in `apps.json`
to anything except `connect` — the request is dropped **silently** (`Ok(None)`,
no reply, no log), and a `connect` with a wrong or absent secret is dropped the
same way, so a stranger cannot use error replies as a presence oracle. An
approved client is remembered in `apps.json`
but **every sensitive request is still put to the user**: `sign_event`,
`nip04/nip44_encrypt` and `nip04/nip44_decrypt`. `get_public_key`,
`get_relays`, `switch_relays` and `ping` stay automatic.
- **Bounded-concurrency dispatch (M8).** The responder handles requests
concurrently, up to `DISPATCH_PERMITS` (16) at a time, so a prompt that waits
out the approval deadline cannot stall `ping`, `get_public_key` or an
auto-approved signature behind it. The `Approver`'s drain still serializes the
interactive dialogs themselves, so two prompts are never on screen at once.
- **Policy model.** A dialog answers Deny / Allow once / Allow always. "Always"
stores a `Permission` on the app in `apps.json`: for `sign_event` an allow-list
of **kinds**, for encryption a **method name**. A request covered by a stored
+1 -1
View File
@@ -26,7 +26,7 @@ nostr-sdk = { version = "0.45", default-features = false, features = ["rustls-tl
# App icons are fetched from attacker-controlled URLs, so the HTTP client is
# built per fetch with the validated addresses pinned (see `store::icons`).
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal", "net"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time", "signal", "net", "sync"] }
# The status-bar indicator, via the KDE/freedesktop StatusNotifierItem spec.
# Tokio (not the `blocking` API): it shares Regent's runtime. zbus opens its own
# session connection and never owns the app's D-Bus name.
+4 -3
View File
@@ -236,9 +236,10 @@ DEVICE_HEX=$(nak decode "$DEVICE_NPUB")
printf '\n== a client logging itself out ==\n'
# Nothing else tells the user an application deleted itself and its permissions,
# so a client-initiated logout must raise a notification. Send it before the
# sign request below: the responder answers requests one at a time, and the open
# sign prompt would otherwise hold the loop until its deadline.
# so a client-initiated logout must raise a notification. Sent before the sign
# request below so the two notices are raised in a predictable order; the
# responder now dispatches concurrently, so it is no longer required for the
# loop to make progress.
LOGOUT_ENVELOPE=$(python3 -c 'import json; print(json.dumps({
"id": "acceptance-logout",
"method": "logout",
+97 -40
View File
@@ -205,6 +205,15 @@ const REQUEST_FRESHNESS: Duration = Duration::from_secs(120);
/// Upper bound on the replay window's seen-id set.
const SEEN_CAPACITY: usize = 4096;
/// How many requests may be handled at once.
///
/// Non-interactive requests (`ping`, `get_public_key`, an auto-approved
/// signature) must not queue behind a prompt that can wait out the approval
/// deadline, so the responder dispatches concurrently up to this many. The
/// `Approver` still serializes the dialogs themselves, so this never puts two
/// prompts on screen.
const DISPATCH_PERMITS: usize = 16;
/// Drops replayed or stale NIP-46 requests.
///
/// `kind:24133` is ephemeral, so the relay layer never stores or deduplicates it
@@ -378,6 +387,11 @@ impl Signer {
replay,
);
tokio::spawn(async move {
// Bounded concurrency (M8): a prompt can wait out the approval
// deadline, and a serial loop would stall every other request
// behind it. The permit is acquired in the loop (the
// backpressure point) and moved into the task.
let permits = Arc::new(tokio::sync::Semaphore::new(DISPATCH_PERMITS));
while running.load(Ordering::SeqCst) {
let Some(notification) = notifications.next().await else {
break;
@@ -389,26 +403,39 @@ impl Signer {
continue;
}
// Drop a replayed, duplicated or stale request before it can
// reach the user or the policy gate (H1).
// reach the user or the policy gate (H1). Synchronous, so
// dedup happens exactly once per delivery.
if !replay.accept(&event) {
continue;
}
match handle_request(&event, &config).await {
Ok(Some(response)) => {
// Reply on the relay the request arrived on, plus the
// configured relays. Scoped this way, one
// application's response never reaches another
// application's relay (M3).
let targets = response_targets_for(&relay_url, &configured);
if let Err(error) = client.send_event(&response).to(targets).await {
eprintln!("regent: could not answer a request: {error}");
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
break;
};
let config = Arc::clone(&config);
let client = client.clone();
let configured = Arc::clone(&configured);
let relay_url = relay_url.clone();
let event = *event;
tokio::spawn(async move {
let _permit = permit;
match handle_request(&event, &config).await {
Ok(Some(response)) => {
// Reply on the relay the request arrived on,
// plus the configured relays. Scoped this way,
// one application's response never reaches
// another application's relay (M3).
let targets = response_targets_for(&relay_url, &configured);
if let Err(error) = client.send_event(&response).to(targets).await {
eprintln!("regent: could not answer a request: {error}");
}
}
Ok(None) => {}
Err(error) => {
eprintln!("regent: bad request from {}: {error}", event.pubkey);
}
}
Ok(None) => {}
Err(error) => {
eprintln!("regent: bad request from {}: {error}", event.pubkey);
}
}
});
}
});
}
@@ -787,15 +814,13 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
.unwrap_or_default();
// Everything except pairing requires an application the user has approved;
// bootstrapping happens through `connect`, which asks.
// bootstrapping happens through `connect`, which asks. An unapproved client
// gets **no answer at all** for anything else: a signed error reply would be
// a presence oracle for the device key (and amplify relay traffic), so the
// request is dropped silently. Nothing is logged either.
let approved = config.registry.lock().unwrap().contains(&event.pubkey);
if method != "connect" && !approved {
return respond(
config,
event,
&id,
Err(format!("{method}: this application has not been approved")),
);
return Ok(None);
}
// Who is asking, for the dialog. A fresh pairing shows what the client just
@@ -821,7 +846,11 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
if approved {
Ok("ack".to_string())
} else if presented != config.secret {
Err("unauthorized".to_string())
// A wrong or absent secret gets no reply: an error back to a
// stranger is a presence oracle, and a client that knows the
// secret does not need the feedback. Running `--pair` is the
// consent path for a client-initiated pairing.
return Ok(None);
} else {
// Bind the new pairing to the current identity (or the first
// stored key). The registry, never this default, is consulted
@@ -2613,11 +2642,11 @@ mod tests {
for _ in 0..20 {
let request = client_request(&client, &device, "sign_event", sign_params(1, "hi"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["error"].is_string());
let response = handle_request(&request, &config).await.expect("handle");
assert!(
response.is_none(),
"an unapproved request gets no reply (M8)"
);
}
task.abort();
@@ -2628,6 +2657,38 @@ mod tests {
let _ = std::fs::remove_file(&path);
}
/// A stranger gets no reply to any method but `connect` — the documented
/// "no answer except connect" invariant, now enforced (M8).
#[tokio::test]
async fn a_stranger_gets_no_reply_to_any_method_but_connect() {
let client = Keys::generate();
let (path, log) = temp_log();
let (approver, task, _) = recording_approver(|_| Decision::Always);
let (changes, _changes_rx) = async_channel::unbounded();
let config = config_with("ws://127.0.0.1:1", approver, log.clone(), changes);
let device = config.device_keys.public_key();
for (method, params) in [
("ping", serde_json::json!([])),
("get_public_key", serde_json::json!([])),
("get_relays", serde_json::json!([])),
("sign_event", sign_params(1, "hi")),
("nip44_encrypt", serde_json::json!([])),
] {
let request = client_request(&client, &device, method, params);
assert!(
handle_request(&request, &config)
.await
.expect("handle")
.is_none(),
"{method} from a stranger must get no reply"
);
}
task.abort();
let _ = std::fs::remove_file(&path);
}
/// `incoming()` is strict about the shapes that decide what is signed: a
/// malformed event is refused rather than silently coerced (H2).
#[test]
@@ -2764,13 +2825,10 @@ mod tests {
assert!(read_response(&response, &client, &device)["result"].is_string());
assert!(!config.registry.lock().unwrap().contains(&client.public_key()));
// A request after logout is refused.
// A request after logout gets no reply: the client is unapproved again.
let request = client_request(&client, &device, "sign_event", sign_params(1, "hi"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["error"].is_string());
let response = handle_request(&request, &config).await.expect("handle");
assert!(response.is_none(), "a logged-out client gets no reply");
let pairs_before = seen
.lock()
@@ -3153,14 +3211,13 @@ mod tests {
"connect",
serde_json::json!(["", "not-the-secret", "", ""]),
);
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
let response = handle_request(&request, &config).await.expect("handle");
task.abort();
assert!(answer["error"].is_string(), "got {answer}");
assert!(
response.is_none(),
"a wrong secret gets no reply — no presence oracle (M8)"
);
}
/// Registry changes wake the Apps and Activity pages.