signer: validate client relays and scope responses to the arrival relay (M3)
This commit is contained in:
5 files changed
+193
-19
No files matched your search
@@ -683,7 +683,13 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
`get_relays`), register the app, then send the `connect` **response** whose
|
||||
`result` is the client's secret, p-tagged to the client and signed by the
|
||||
device key. Running `--pair` is the consent; permissions are never
|
||||
auto-granted, and the URI/secret are never printed or logged.
|
||||
auto-granted, and the URI/secret are never printed or logged. Client-supplied
|
||||
relays are **`wss://` only and at most `MAX_CLIENT_RELAYS` (5)**, and a literal
|
||||
IP that is not globally routable is refused — a `ws://` or `169.254.x`/loopback
|
||||
relay would otherwise turn a hostile URI into a local-network probe. The
|
||||
`REGENT_RELAYS` test override skips both checks (as it already lets a test point
|
||||
the signer at `ws://127.0.0.1`); the relays that survive are shown in the
|
||||
pairing dialog's Details.
|
||||
- The responder answers `connect` with `"ack"` for an **already approved**
|
||||
client even without the secret — a client-initiated pairing proves key
|
||||
possession by receiving our response. A new client still needs the secret.
|
||||
@@ -743,15 +749,19 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
`verify_subscriptions`, **wait until connected**, then subscribe an explicit
|
||||
`(RelayUrl, Vec<Filter>)` target. Subscribing before the connection lands is
|
||||
trap #2 again, and it looks fine because the pairing itself publishes
|
||||
explicitly — only later requests silently never arrive. Requests and responses
|
||||
both use the shared, growable response-target set.
|
||||
explicitly — only later requests silently never arrive. The client's relays
|
||||
join the shared, growable **listening** set (`response_targets`), but a reply
|
||||
is published to the relay the request **arrived on** plus `config.relays` —
|
||||
never to another application's relay, so one app's prompt timing and response
|
||||
sizes are not observable to a client that joined a different relay.
|
||||
- `pair_client` (shared by the GUI and `--pair`) approves **before** publishing:
|
||||
the client validates the secret and usually sends `connect` immediately, which
|
||||
a new client cannot do without the bunker secret.
|
||||
- **Known limitation:** a manual stop/start drops the client's relays
|
||||
(`extra_relays` are per-run). Spec-compliant clients recover via
|
||||
`switch_relays`; others need re-pairing. Persisting per-app relays in
|
||||
`apps.json` is the clean follow-up.
|
||||
`apps.json` is the clean follow-up — and would also let a reply use a client's
|
||||
*other* relays; today it is the arrival relay plus the configured ones.
|
||||
- **Still deferred:** D-Bus activation (a `.service` file + `DBusActivatable`).
|
||||
|
||||
## The key vault (M8)
|
||||
|
||||
+11
-4
@@ -62,6 +62,10 @@ pub enum Request {
|
||||
/// the same string as `nostrconnect://…&perms=`). Client-supplied and
|
||||
/// shown for context only; granting stays per-request.
|
||||
requested: Option<String>,
|
||||
/// The relays the client asked us to use (`nostrconnect://`), for the
|
||||
/// dialog's Details. Empty for a request that carried none (the bunker
|
||||
/// direction). Display-only: never trusted.
|
||||
relays: Vec<String>,
|
||||
},
|
||||
/// An event would be signed with an identity key.
|
||||
Sign {
|
||||
@@ -328,7 +332,10 @@ mod tests {
|
||||
.ask_within(
|
||||
Duration::from_millis(50),
|
||||
Duration::from_millis(50),
|
||||
question(Request::Pair { requested: None }),
|
||||
question(Request::Pair {
|
||||
requested: None,
|
||||
relays: Vec::new(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(decision, Answer::denied());
|
||||
@@ -341,7 +348,7 @@ mod tests {
|
||||
let (approver, questions, _notices) = Approver::new();
|
||||
let drain = tokio::spawn(async move { while questions.recv().await.is_ok() {} });
|
||||
assert_eq!(
|
||||
approver.ask(question(Request::Pair { requested: None })).await,
|
||||
approver.ask(question(Request::Pair { requested: None, relays: Vec::new() })).await,
|
||||
Answer::denied()
|
||||
);
|
||||
drain.abort();
|
||||
@@ -369,8 +376,8 @@ mod tests {
|
||||
let before = Instant::now();
|
||||
// Nobody drains the queue, so both asks sit in it until the backstop.
|
||||
let (first, second) = tokio::join!(
|
||||
approver.ask_within(deadline, backstop, question(Request::Pair { requested: None })),
|
||||
approver.ask_within(deadline, backstop, question(Request::Pair { requested: None })),
|
||||
approver.ask_within(deadline, backstop, question(Request::Pair { requested: None, relays: Vec::new() })),
|
||||
approver.ask_within(deadline, backstop, question(Request::Pair { requested: None, relays: Vec::new() })),
|
||||
);
|
||||
assert_eq!(first, Answer::denied());
|
||||
assert_eq!(second, Answer::denied());
|
||||
|
||||
+157
-10
@@ -283,6 +283,26 @@ impl ReplayGuard {
|
||||
}
|
||||
}
|
||||
|
||||
/// The relays a response may be published to: the relay the request arrived on,
|
||||
/// plus the configured relays.
|
||||
///
|
||||
/// Scoped this way so one application's reply never reaches *another*
|
||||
/// application's relay. The relays a client asked us to join are still in the
|
||||
/// listening set (`response_targets`) so we receive there, but they are not a
|
||||
/// broadcast target for replies to other requests.
|
||||
fn response_targets_for(arrival: &RelayUrl, configured: &[RelayUrl]) -> Vec<RelayUrl> {
|
||||
let mut targets = Vec::with_capacity(configured.len() + 1);
|
||||
targets.push(arrival.clone());
|
||||
for relay in configured {
|
||||
if !targets.contains(relay) {
|
||||
targets.push(relay.clone());
|
||||
}
|
||||
}
|
||||
targets.sort();
|
||||
targets.dedup();
|
||||
targets
|
||||
}
|
||||
|
||||
pub struct Signer {
|
||||
config: Arc<SignerConfig>,
|
||||
client: Client,
|
||||
@@ -304,6 +324,10 @@ impl Signer {
|
||||
urls.sort();
|
||||
urls.dedup();
|
||||
let response_targets = Arc::new(Mutex::new(urls.clone()));
|
||||
// The configured relays are the one part of the response path a client
|
||||
// cannot influence: a reply goes to the relay its request arrived on plus
|
||||
// these, never to *another* client's relay (M3).
|
||||
let configured = Arc::new(config.relay_urls()?);
|
||||
|
||||
let client = Client::new();
|
||||
for url in &urls {
|
||||
@@ -346,11 +370,11 @@ impl Signer {
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
let replay = ReplayGuard::new();
|
||||
{
|
||||
let (client, config, running, response_targets, replay) = (
|
||||
let (client, config, running, configured, replay) = (
|
||||
client.clone(),
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&running),
|
||||
Arc::clone(&response_targets),
|
||||
Arc::clone(&configured),
|
||||
replay,
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
@@ -358,7 +382,7 @@ impl Signer {
|
||||
let Some(notification) = notifications.next().await else {
|
||||
break;
|
||||
};
|
||||
let ClientNotification::Event { event, .. } = notification else {
|
||||
let ClientNotification::Event { event, relay_url, .. } = notification else {
|
||||
continue;
|
||||
};
|
||||
if event.kind != Kind::NostrConnect {
|
||||
@@ -371,11 +395,11 @@ impl Signer {
|
||||
}
|
||||
match handle_request(&event, &config).await {
|
||||
Ok(Some(response)) => {
|
||||
// Clone the targets under a short lock; the lock is
|
||||
// never held across the publish below.
|
||||
let targets = response_targets.lock().unwrap().clone();
|
||||
// Responses go back to the relays the clients use,
|
||||
// again bypassing gossip routing.
|
||||
// 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}");
|
||||
}
|
||||
@@ -515,6 +539,51 @@ impl ClientPairing {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most relays a single `nostrconnect://` URI may ask us to join. A client
|
||||
/// needs one or two; an unbounded list is a resource and metadata problem.
|
||||
const MAX_CLIENT_RELAYS: usize = 5;
|
||||
|
||||
/// Whether the test relay override is active.
|
||||
///
|
||||
/// Matches `Config::relays`'s treatment of the value: an unset **or** empty
|
||||
/// (whitespace-only) `REGENT_RELAYS` counts as absent, so a test override means
|
||||
/// the same thing in both places.
|
||||
fn relays_test_override() -> bool {
|
||||
std::env::var("REGENT_RELAYS")
|
||||
.map(|value| !value.trim().is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether a client-supplied relay may be used.
|
||||
///
|
||||
/// Outside the `REGENT_RELAYS` test override this refuses a plaintext `ws://`
|
||||
/// relay and a literal IP that is not globally routable (`127.0.0.1`, a LAN or
|
||||
/// link-local address, a NAT64-mapped private address, …), which is what keeps a
|
||||
/// hostile `nostrconnect://` URI from turning the signer into a local-network
|
||||
/// probe. The override skips **both** checks, exactly as it already lets a test
|
||||
/// point the signer at a local `ws://127.0.0.1` relay.
|
||||
fn relay_allowed(relay: &RelayUrl, test_override: bool) -> std::result::Result<(), String> {
|
||||
if test_override {
|
||||
return Ok(());
|
||||
}
|
||||
if !relay.scheme().is_secure() {
|
||||
return Err(format!("refusing a plaintext relay: {relay}"));
|
||||
}
|
||||
if let Some(host) = relay.host() {
|
||||
let ip = match host {
|
||||
url::Host::Ipv4(ip) => std::net::IpAddr::V4(ip),
|
||||
url::Host::Ipv6(ip) => std::net::IpAddr::V6(ip),
|
||||
// A hostname is resolved later by the SDK; checking it here would
|
||||
// need a network round trip in a parse function.
|
||||
url::Host::Domain(_) => return Ok(()),
|
||||
};
|
||||
if !crate::store::icons::is_public(ip) {
|
||||
return Err(format!("refusing a non-public relay address: {relay}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parse a spec-shaped `nostrconnect://` URI (the client-initiated flow).
|
||||
///
|
||||
/// Parsed by hand, **not** with `NostrConnectUri::parse`: that one expects a
|
||||
@@ -531,6 +600,7 @@ pub fn parse_client_uri(uri: &str) -> Result<ClientPairing> {
|
||||
|
||||
let client = PublicKey::from_hex(parsed.host_str().unwrap_or_default())?;
|
||||
|
||||
let test_override = relays_test_override();
|
||||
let mut relays = Vec::new();
|
||||
let mut secret = None;
|
||||
let mut name = None;
|
||||
@@ -539,7 +609,14 @@ pub fn parse_client_uri(uri: &str) -> Result<ClientPairing> {
|
||||
let mut requested = None;
|
||||
for (key, value) in parsed.query_pairs() {
|
||||
match key.as_ref() {
|
||||
"relay" => relays.push(RelayUrl::parse(value.as_ref())?),
|
||||
"relay" => {
|
||||
if relays.len() >= MAX_CLIENT_RELAYS {
|
||||
return Err("the nostrconnect:// URI lists too many relays".into());
|
||||
}
|
||||
let relay = RelayUrl::parse(value.as_ref())?;
|
||||
relay_allowed(&relay, test_override)?;
|
||||
relays.push(relay);
|
||||
}
|
||||
"secret" => secret = Some(value.to_string()),
|
||||
"name" => name = Some(value.to_string()),
|
||||
"url" => url = Some(value.to_string()),
|
||||
@@ -765,7 +842,13 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
.filter(|previous| *previous != identity);
|
||||
let question = Question {
|
||||
client: client.clone(),
|
||||
request: Request::Pair { requested },
|
||||
request: Request::Pair {
|
||||
requested,
|
||||
// A `connect` request carries no relay list (the
|
||||
// client's relays are only known on the
|
||||
// client-initiated `nostrconnect://` path).
|
||||
relays: Vec::new(),
|
||||
},
|
||||
identity: signing_key(config, identity),
|
||||
rebind_from,
|
||||
};
|
||||
@@ -2851,6 +2934,70 @@ mod tests {
|
||||
assert!(parse_client_uri("https://example.com").is_err());
|
||||
}
|
||||
|
||||
/// A client-supplied relay is refused when it is plaintext or points at a
|
||||
/// non-public literal address — unless the test override is active. This is
|
||||
/// the pure policy behind `parse_client_uri` (M3).
|
||||
#[test]
|
||||
fn a_client_relay_must_be_secure_and_public() {
|
||||
let ws = RelayUrl::parse("ws://relay.example.com").unwrap();
|
||||
let wss = RelayUrl::parse("wss://relay.example.com").unwrap();
|
||||
let loopback = RelayUrl::parse("wss://127.0.0.1:1").unwrap();
|
||||
let link_local = RelayUrl::parse("wss://169.254.169.254").unwrap();
|
||||
let v6_loop = RelayUrl::parse("wss://[::1]:1").unwrap();
|
||||
let nat64 = RelayUrl::parse("wss://[64:ff9b::169.254.169.254]").unwrap();
|
||||
|
||||
// Without the override: the ws scheme and every non-public literal fails.
|
||||
assert!(relay_allowed(&wss, false).is_ok());
|
||||
assert!(relay_allowed(&ws, false).is_err());
|
||||
assert!(relay_allowed(&loopback, false).is_err());
|
||||
assert!(relay_allowed(&link_local, false).is_err());
|
||||
assert!(relay_allowed(&v6_loop, false).is_err());
|
||||
assert!(relay_allowed(&nat64, false).is_err());
|
||||
|
||||
// The override skips both checks — the acceptance `--pair` path.
|
||||
assert!(relay_allowed(&ws, true).is_ok());
|
||||
assert!(relay_allowed(&loopback, true).is_ok());
|
||||
assert!(relay_allowed(&wss, true).is_ok());
|
||||
}
|
||||
|
||||
/// A URI may not list more than `MAX_CLIENT_RELAYS`, and a plaintext relay is
|
||||
/// refused without the override.
|
||||
#[test]
|
||||
fn parse_client_uri_caps_and_filters_relays() {
|
||||
let keys = Keys::generate();
|
||||
let relays: String = (0..MAX_CLIENT_RELAYS + 1)
|
||||
.map(|n| format!("&relay=wss%3A%2F%2Frelay{n}.example.com"))
|
||||
.collect();
|
||||
let too_many = format!(
|
||||
"nostrconnect://{}?secret=abc{relays}",
|
||||
keys.public_key().to_hex()
|
||||
);
|
||||
assert!(parse_client_uri(&too_many).is_err(), "six relays is too many");
|
||||
|
||||
let plaintext = format!(
|
||||
"nostrconnect://{}?relay=ws%3A%2F%2Frelay.example.com&secret=abc",
|
||||
keys.public_key().to_hex()
|
||||
);
|
||||
// The test-override env var is not set in a normal `cargo test` run.
|
||||
assert!(parse_client_uri(&plaintext).is_err(), "ws:// is refused");
|
||||
}
|
||||
|
||||
/// A response goes to the relay the request arrived on plus the configured
|
||||
/// relays, never to another application's relay (M3).
|
||||
#[test]
|
||||
fn response_targets_scope_to_the_arrival_relay() {
|
||||
let arrival = RelayUrl::parse("wss://arrival.example.com").unwrap();
|
||||
let configured = RelayUrl::parse("wss://configured.example.com").unwrap();
|
||||
let targets = response_targets_for(&arrival, &[configured.clone(), arrival.clone()]);
|
||||
assert_eq!(targets.len(), 2, "the overlap collapses");
|
||||
assert!(targets.contains(&arrival));
|
||||
assert!(targets.contains(&configured));
|
||||
assert!(
|
||||
!targets.contains(&RelayUrl::parse("wss://other.example.com").unwrap()),
|
||||
"another client's relay is not a target"
|
||||
);
|
||||
}
|
||||
|
||||
/// Clients that always emit the metadata keys (`name=&url=&image=&perms=`)
|
||||
/// must not produce an empty name, an empty byline or a stored empty image.
|
||||
#[test]
|
||||
|
||||
+6
-1
@@ -623,10 +623,15 @@ fn more_details(question: &Question) -> gtk::ListBox {
|
||||
row.add_row(&plain::row("Declared URL", url));
|
||||
}
|
||||
match &question.request {
|
||||
Request::Pair { requested } => {
|
||||
Request::Pair { requested, relays } => {
|
||||
if let Some(requested) = requested {
|
||||
row.add_row(&plain::row("Asked for", requested));
|
||||
}
|
||||
// The relays the client asked us to join: display-only, and the one
|
||||
// place the user can inspect them before trusting the app (M3).
|
||||
for relay in relays {
|
||||
row.add_row(&plain::row("Relay", relay));
|
||||
}
|
||||
}
|
||||
Request::Sign { .. } => {}
|
||||
Request::Encrypt { method, peer, .. } | Request::Decrypt { method, peer, .. } => {
|
||||
|
||||
@@ -398,6 +398,11 @@ impl ConnectDialog {
|
||||
client: pairing.client_info(),
|
||||
request: Request::Pair {
|
||||
requested: pairing.requested.clone(),
|
||||
relays: pairing
|
||||
.relays
|
||||
.iter()
|
||||
.map(|relay| relay.to_string())
|
||||
.collect(),
|
||||
},
|
||||
identity: SigningKey {
|
||||
public_key: identity,
|
||||
|
||||
Reference in new issue
Block a user