signer: rotate the pairing secret on every new pairing (L1)

This commit is contained in:
raucao committed 2026-11-30 10:31:00 +04:00
1 parent b4fe138641
commit 910554c8d6
6 files changed
+222 -27

No files matched your search

+10
View File
@@ -708,6 +708,16 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
- 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.
- **The pairing secret rotates (L1).** `SignerConfig.secret` (and the
`bunker://` `config.uri`) are shared `Arc<Mutex<String>>`s; a successful **new**
pairing — the responder's `connect` arm after `approve`, and `pair_client` after
`complete_pairing` — calls `rotate_secret`, which mints a fresh 96-bit secret
and rebuilds the URI. So a copied/shoulder-surfed `bunker://` string stops
pairing a **new** client after the next pairing; every **approved** client keeps
reconnecting through the `"ack"` path above, unaffected. The secret was already
per-run (`random_secret()` in `from_store`), so this only shortens its life
*within* a run. The presented secret is compared in **constant time**
(`subtle::ConstantTimeEq`), never `==`.
- **One instance only.** Two signers on one device key fight over `apps.json`.
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
Generated
+1
View File
@@ -2023,6 +2023,7 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
"subtle",
"tempfile",
"tokio",
"url",
+2
View File
@@ -36,6 +36,8 @@ serde_json = { version = "1", features = ["preserve_order"] }
serde = { version = "1", features = ["derive"] }
zeroize = "1"
base64 = "0.22"
# Constant-time comparison for the pairing secret (L1).
subtle = "2"
# The one `unsafe` in the tree: `CLOCK_BOOTTIME`, so the vault's auto-lock
# timeout counts time spent suspended (`Instant` is `CLOCK_MONOTONIC`, which
# stops during suspend). See `store::keys::boottime`.
+1 -1
View File
@@ -127,7 +127,7 @@ impl SignerRunner {
pub fn bunker_uri(&self) -> Option<String> {
match &*self.status.borrow() {
Status::Running(signer) => Some(signer.bunker_uri().to_string()),
Status::Running(signer) => Some(signer.bunker_uri()),
_ => None,
}
}
+206 -24
View File
@@ -15,6 +15,7 @@ use std::time::{Duration, Instant};
use nostr::nips::{nip04, nip44};
use nostr::prelude::*;
use nostr_sdk::prelude::*;
use subtle::ConstantTimeEq;
use self::approval::{
Approver, ClientInfo, Decision, Notice, Question, Request, SigningKey, TagView,
@@ -113,8 +114,11 @@ pub struct SignerConfig {
pub default_identity: Arc<Mutex<Option<PublicKey>>>,
pub relays: Vec<String>,
/// The value a client must present in `connect`. Rotating it invalidates
/// previously handed-out connection strings.
pub secret: String,
/// previously handed-out connection strings; shared so the responder can
/// rotate it on a successful new pairing (L1).
pub secret: Arc<Mutex<String>>,
/// The `bunker://` connection string, rebuilt whenever the secret rotates.
pub uri: Arc<Mutex<String>>,
/// Asks the user before any sensitive request is answered.
pub approver: Approver,
/// Relays a client asked us to use (`nostrconnect://`), on top of the
@@ -144,13 +148,17 @@ impl SignerConfig {
names: Arc<Mutex<HashMap<String, String>>>,
default_identity: Arc<Mutex<Option<PublicKey>>>,
) -> Result<Self> {
let device_keys = store.device_key()?;
let secret = random_secret();
let uri = bunker_uri(&device_keys.public_key(), &relays, &secret);
Ok(Self {
device_keys: store.device_key()?,
device_keys,
keys: IdentityKeys::Store(store),
names,
default_identity,
relays,
secret: random_secret(),
secret: Arc::new(Mutex::new(secret)),
uri: Arc::new(Mutex::new(uri)),
approver,
extra_relays: Vec::new(),
registry,
@@ -320,7 +328,6 @@ pub struct Signer {
/// client asked for. Grows at runtime via [`Signer::add_client_relays`];
/// the responder task reads it under a short lock when it answers.
response_targets: Arc<Mutex<Vec<RelayUrl>>>,
uri: String,
}
impl Signer {
@@ -440,19 +447,20 @@ impl Signer {
});
}
let uri = bunker_uri(&config.device_keys.public_key(), &config.relays, &config.secret);
Ok(Self {
config,
client,
running,
response_targets,
uri,
})
}
/// The `bunker://` connection string to hand to an application.
pub fn bunker_uri(&self) -> &str {
&self.uri
///
/// Rebuilt whenever a new pairing rotates the secret, so a copied string
/// stops working for *new* pairings.
pub fn bunker_uri(&self) -> String {
self.config.uri.lock().unwrap().clone()
}
pub fn device_public_key(&self) -> PublicKey {
@@ -710,6 +718,11 @@ pub async fn pair_client(
return Err(error);
}
// A successful client-initiated pairing is also a "new pairing": rotate the
// shared connection string (L1), from the same call site as the responder's
// connect arm.
rotate_secret(&signer.config);
eprintln!(
"regent: paired {} as {}",
pairing.client.to_bech32().unwrap_or_default(),
@@ -786,6 +799,32 @@ fn random_secret() -> String {
Keys::generate().public_key().to_hex()[..24].to_string()
}
/// Whether the presented pairing secret matches, in constant time (L1).
///
/// `ct_eq` on the byte slices returns `0` for different lengths, so a wrong
/// length is simply "no match".
fn secret_matches(secret: &Mutex<String>, presented: &str) -> bool {
secret
.lock()
.unwrap()
.as_bytes()
.ct_eq(presented.as_bytes())
.unwrap_u8()
== 1
}
/// Give the signer a fresh pairing secret and rebuild its connection string.
///
/// Called after a successful **new** pairing (L1): an already shared
/// `bunker://` URI then no longer pairs a *new* client, while every approved
/// client keeps working through the `connect` `"ack"` path.
fn rotate_secret(config: &SignerConfig) {
let secret = random_secret();
let uri = bunker_uri(&config.device_keys.public_key(), &config.relays, &secret);
*config.secret.lock().unwrap() = secret;
*config.uri.lock().unwrap() = uri;
}
/// Decrypt a request, decide what to answer, and build the response event.
///
/// The envelope is parsed by hand: rust-nostr's typed NIP-46 request cannot
@@ -845,11 +884,12 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
// client must still present the secret.
if approved {
Ok("ack".to_string())
} else if presented != config.secret {
} else if !secret_matches(&config.secret, &presented) {
// 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.
// consent path for a client-initiated pairing. The comparison is
// constant-time (L1).
return Ok(None);
} else {
// Bind the new pairing to the current identity (or the first
@@ -909,6 +949,12 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
Some(&identity),
audit::outcome::PAIRED,
);
// A successful new pairing invalidates the
// shared connection string for any *future*
// new pairing (L1). Already-approved clients
// keep reconnecting through the `approved`
// path above.
rotate_secret(config);
}
result
}
@@ -1711,13 +1757,17 @@ mod tests {
identity_public.to_hex(),
"Test identity".to_string(),
)])));
let device_keys = Keys::generate();
let relays = vec![relay.to_string()];
let (secret, uri) = test_secret(&device_keys, &relays, "test-secret");
SignerConfig {
device_keys: Keys::generate(),
device_keys,
keys: IdentityKeys::Fixed(identity),
names,
default_identity: Arc::new(Mutex::new(Some(identity_public))),
relays: vec![relay.to_string()],
secret: "test-secret".to_string(),
relays,
secret,
uri,
approver,
extra_relays: Vec::new(),
registry: Arc::new(Mutex::new(AppRegistry::default())),
@@ -1727,6 +1777,19 @@ mod tests {
}
}
/// The secret/URI handles a test signer starts with.
fn test_secret(
device_keys: &Keys,
relays: &[String],
secret: &str,
) -> (Arc<Mutex<String>>, Arc<Mutex<String>>) {
let uri = bunker_uri(&device_keys.public_key(), relays, secret);
(
Arc::new(Mutex::new(secret.to_string())),
Arc::new(Mutex::new(uri)),
)
}
/// The single identity a test signer is configured with.
fn user_public(config: &SignerConfig) -> PublicKey {
config
@@ -1788,7 +1851,7 @@ mod tests {
let expected = user_public(&config);
let signer = Signer::start(config).await.expect("start signer");
let output = nak_signs(signer.bunker_uri()).await;
let output = nak_signs(&signer.bunker_uri()).await;
relay.stop();
signer.stop().await;
@@ -1824,6 +1887,75 @@ mod tests {
);
}
/// A client-initiated pairing (the `nostrconnect://` flow) rotates the
/// shared connection string too (L1), from the same `pair_client` call site
/// the GUI and `--pair` use.
#[tokio::test]
#[ignore = "needs nak; run with --ignored"]
async fn nak_a_client_initiated_pairing_rotates_the_secret() {
let mut relay = TestRelay::start().await;
let (approver, _approvals, _seen) = recording_approver(|_| Decision::Always);
let config = config(&relay.relay, approver);
let identity = user_public(&config);
let registry = Arc::clone(&config.registry);
let signer = Signer::start(config).await.expect("start signer");
let before = signer.bunker_uri();
let client = Keys::generate().public_key();
// `nak serve` mutes an event no one is listening for, so the connect
// response needs a subscriber on the client's key (as the acceptance
// test does).
let mut subscriber = std::process::Command::new("nak")
.args([
"req",
"--stream",
"-k",
"24133",
"-p",
&client.to_hex(),
&relay.relay,
])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn nak subscriber");
tokio::time::sleep(Duration::from_secs(2)).await;
let pairing = ClientPairing {
client,
relays: vec![RelayUrl::parse(&relay.relay).unwrap()],
secret: "client-secret".to_string(),
name: None,
url: None,
image: None,
requested: None,
};
let activity = ActivityLog::at(std::path::PathBuf::new());
let (changes, _rx) = async_channel::unbounded();
let paired = pair_client(
&signer,
&registry,
&activity,
&changes,
&pairing,
identity,
None,
)
.await;
let after = signer.bunker_uri();
let _ = subscriber.kill();
let _ = subscriber.wait();
relay.stop();
signer.stop().await;
paired.expect("pair the client");
assert_ne!(
before, after,
"a client-initiated pairing rotates the connection string"
);
}
/// A denial has to reach the client: nak must not get a signature.
#[tokio::test]
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
@@ -1836,7 +1968,7 @@ mod tests {
let config = config(&relay.relay, approver);
let signer = Signer::start(config).await.expect("start signer");
let output = nak_signs(signer.bunker_uri()).await;
let output = nak_signs(&signer.bunker_uri()).await;
relay.stop();
signer.stop().await;
@@ -1859,7 +1991,7 @@ mod tests {
let config = config(&relay.relay, approver);
let signer = Signer::start(config).await.expect("start signer");
let first = nak_signs(signer.bunker_uri()).await;
let first = nak_signs(&signer.bunker_uri()).await;
assert!(
first.status.success(),
"the first sign failed: {}",
@@ -1873,7 +2005,7 @@ mod tests {
.count();
// The same client, the same kind: this must not ask again.
let second = nak_signs(signer.bunker_uri()).await;
let second = nak_signs(&signer.bunker_uri()).await;
relay.stop();
signer.stop().await;
@@ -1905,7 +2037,7 @@ mod tests {
let config = config(&relay.relay, approver);
let signer = Signer::start(config).await.expect("start signer");
let output = nak_signs(signer.bunker_uri()).await;
let output = nak_signs(&signer.bunker_uri()).await;
relay.stop();
signer.stop().await;
@@ -1990,7 +2122,7 @@ mod tests {
client,
&device,
"connect",
serde_json::json!(["", config.secret, "", ""]),
serde_json::json!(["", config.secret.lock().unwrap().clone(), "", ""]),
);
let response = handle_request(&request, config)
.await
@@ -2053,13 +2185,17 @@ mod tests {
identity.to_hex(),
"Test identity".to_string(),
)])));
let device_keys = Keys::generate();
let relays = vec![relay.to_string()];
let (secret, uri) = test_secret(&device_keys, &relays, "test-secret");
SignerConfig {
device_keys: Keys::generate(),
device_keys,
keys: IdentityKeys::Store(store),
names,
default_identity: Arc::new(Mutex::new(Some(identity))),
relays: vec![relay.to_string()],
secret: "test-secret".to_string(),
relays,
secret,
uri,
approver,
extra_relays: Vec::new(),
registry: Arc::new(Mutex::new(AppRegistry::default())),
@@ -3197,6 +3333,52 @@ mod tests {
assert!(read_response(&response, &client, &device)["result"].is_string());
}
/// A successful new pairing rotates the shared connection string (L1): an
/// old secret no longer pairs a new client, while an approved client keeps
/// reconnecting without one.
#[tokio::test]
async fn a_successful_pairing_rotates_the_secret() {
let client = Keys::generate();
let (approver, task, _) = recording_approver(|_| Decision::Always);
let config = config("ws://127.0.0.1:1", approver);
let old_secret = config.secret.lock().unwrap().clone();
let old_uri = config.uri.lock().unwrap().clone();
pair(&client, &config).await;
assert_ne!(
config.secret.lock().unwrap().clone(),
old_secret,
"the pairing secret rotated"
);
assert_ne!(
config.uri.lock().unwrap().clone(),
old_uri,
"the connection string was rebuilt"
);
// A *new* client presenting the old secret gets no reply.
let stranger = Keys::generate();
let request = client_request(
&stranger,
&config.device_keys.public_key(),
"connect",
serde_json::json!(["", old_secret, "", ""]),
);
assert!(
handle_request(&request, &config)
.await
.expect("handle")
.is_none(),
"the old secret no longer pairs a new client"
);
// But the current secret still pairs.
let second = Keys::generate();
pair(&second, &config).await;
task.abort();
}
/// A new client still has to prove it was handed the connection string.
#[tokio::test]
async fn an_unapproved_client_needs_the_secret() {
@@ -3405,7 +3587,7 @@ mod tests {
&client_a,
&device,
"connect",
serde_json::json!(["", config.secret, "", ""]),
serde_json::json!(["", config.secret.lock().unwrap().clone(), "", ""]),
);
handle_request(&request, &config)
.await
+2 -2
View File
@@ -333,9 +333,9 @@ impl ConnectDialog {
// Display only: the copy button and the QR code still use the
// full string. The row shows the head and the secret tail.
self.uri
.set_subtitle(&plain::shorten_uri(signer.bunker_uri()));
.set_subtitle(&plain::shorten_uri(&signer.bunker_uri()));
if self.reveal.is_expanded() {
self.show_qr(signer.bunker_uri());
self.show_qr(&signer.bunker_uri());
}
}
}