Ask the user before signing, encrypting or decrypting

This commit is contained in:
raucao committed 2026-11-13 16:38:26 +04:00
1 parent ddf15b3a1f
commit 36322259a0
4 files changed
+898 -103

No files matched your search

+29 -6
View File
@@ -27,19 +27,42 @@ pub struct ClientInfo {
/// What is being asked for.
///
/// `Sign`, `Encrypt` and `Decrypt` are used from M4, when every sensitive
/// request is put to the user.
#[allow(dead_code)]
/// Everything the dialog shows beyond the client identity is already reduced to
/// plain text here: `preview` and `tags` are derived from client-supplied
/// content and must only ever be rendered as text, never as markup.
#[derive(Debug, Clone)]
pub enum Request {
/// An application wants to connect for the first time.
Pair,
/// An event would be signed with the identity key.
Sign { kind: u16, preview: String },
Sign {
kind: u16,
preview: String,
tags: String,
},
/// A message would be encrypted to someone.
Encrypt { peer: String },
Encrypt {
method: &'static str,
peer: String,
preview: String,
},
/// A message would be decrypted from someone.
Decrypt { peer: String },
Decrypt {
method: &'static str,
peer: String,
preview: String,
},
}
impl Request {
/// Whether an "always" answer may be stored for this request.
///
/// Decryption is a content oracle: silently decrypting anything is the flaw
/// this project exists to replace, so it may never be answered without
/// asking and never remembers a yes.
pub fn allows_always(&self) -> bool {
!matches!(self, Request::Decrypt { .. })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+652 -42
View File
@@ -17,10 +17,12 @@ use nostr::prelude::*;
use nostr_sdk::prelude::*;
use self::approval::{Approver, ClientInfo, Decision, Request};
use crate::store::apps::AppRegistry;
use self::policy::RateLimiter;
use crate::store::apps::{AppRegistry, Permission};
use crate::store::keys::KeyStore;
pub mod approval;
pub mod policy;
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
pub type Result<T> = std::result::Result<T, Error>;
@@ -34,10 +36,12 @@ pub struct SignerConfig {
/// The value a client must present in `connect`. Rotating it invalidates
/// previously handed-out connection strings.
pub secret: String,
/// Asks the user; M4 will use it for every sensitive request.
/// Asks the user before any sensitive request is answered.
pub approver: Approver,
/// Which applications have been approved.
/// Which applications have been approved, and what they may do silently.
pub registry: Arc<Mutex<AppRegistry>>,
/// Caps silent answers for each stored "always" permission.
pub rate: RateLimiter,
}
impl SignerConfig {
@@ -46,6 +50,7 @@ impl SignerConfig {
relays: Vec<String>,
approver: Approver,
registry: Arc<Mutex<AppRegistry>>,
auto_approve_limit: u32,
) -> Result<Self> {
Ok(Self {
device_keys: store.device_key().await?,
@@ -57,6 +62,7 @@ impl SignerConfig {
secret: random_secret(),
approver,
registry,
rate: RateLimiter::new(auto_approve_limit),
})
}
@@ -216,7 +222,8 @@ fn random_secret() -> String {
/// The envelope is parsed by hand: rust-nostr's typed NIP-46 request cannot
/// represent a spec-shaped `sign_event` (it expects a full event with
/// `pubkey`/`id`/`sig`, which is not what clients send).
async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>> { let plain = match nip44::decrypt(config.device_keys.secret_key(), &event.pubkey, &event.content)
async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>> {
let plain = match nip44::decrypt(config.device_keys.secret_key(), &event.pubkey, &event.content)
{
Ok(plain) => plain,
Err(_) => nip04::decrypt(config.device_keys.secret_key(), &event.pubkey, &event.content)?,
@@ -249,6 +256,19 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
);
}
// Who is asking, for the dialog. A fresh pairing shows what the client just
// declared; everything else shows what was recorded when it was approved.
let client = if method == "connect" {
client_info(&event.pubkey, &params)
} else {
config
.registry
.lock()
.unwrap()
.client(&event.pubkey)
.unwrap_or_else(|| bare_client(&event.pubkey))
};
let result: std::result::Result<String, String> = match method {
"connect" => {
let presented = params.get(1).cloned().unwrap_or_default();
@@ -257,7 +277,6 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
} else if approved {
Ok("ack".to_string())
} else {
let client = client_info(&event.pubkey, &params);
match config.approver.ask(client.clone(), Request::Pair).await {
Decision::Deny => Err("the user declined the connection".to_string()),
_ => config
@@ -286,38 +305,143 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
}
"switch_relays" => Ok(serde_json::json!(config.relays).to_string()),
"ping" => Ok("pong".to_string()),
"sign_event" => sign_event(params.first(), &config.user_keys),
"nip04_encrypt" => {
let peer = peer(&params)?;
nip04::encrypt(config.user_keys.secret_key(), &peer, payload(&params))
.map_err(|error| error.to_string())
}
"nip04_decrypt" => {
let peer = peer(&params)?;
nip04::decrypt(config.user_keys.secret_key(), &peer, payload(&params))
.map_err(|error| error.to_string())
}
"nip44_encrypt" => {
let peer = peer(&params)?;
nip44::encrypt(
config.user_keys.secret_key(),
&peer,
payload(&params),
nip44::Version::V2,
)
.map_err(|error| error.to_string())
}
"nip44_decrypt" => {
let peer = peer(&params)?;
nip44::decrypt(config.user_keys.secret_key(), &peer, payload(&params))
.map_err(|error| error.to_string())
}
"sign_event" => match incoming(params.first()) {
Err(error) => Err(error),
Ok(incoming) => {
let kind = incoming.kind.as_u16();
let request = Request::Sign {
kind,
preview: preview(&incoming.content),
tags: tag_summary(&incoming.tags),
};
let permission = Permission::Kind(kind);
match gate(config, &client, request, Some(permission)).await {
Decision::Deny => Err("the user declined to sign the event".to_string()),
_ => sign(incoming, &config.user_keys),
}
}
},
m @ ("nip04_encrypt" | "nip44_encrypt") => match peer(&params) {
Err(error) => Err(error),
Ok(peer) => {
let request = Request::Encrypt {
method: nim_name(m),
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
preview: preview(payload(&params)),
};
let permission = Permission::Method(m.to_string());
match gate(config, &client, request, Some(permission)).await {
Decision::Deny => Err("the user declined to encrypt the message".to_string()),
_ => encrypt(m, config.user_keys.secret_key(), &peer, payload(&params)),
}
}
},
m @ ("nip04_decrypt" | "nip44_decrypt") => match peer(&params) {
Err(error) => Err(error),
Ok(peer) => {
// Decryption may never be answered without asking: no permission
// is offered, so it always reaches the user.
let request = Request::Decrypt {
method: nim_name(m),
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
preview: preview(payload(&params)),
};
match gate(config, &client, request, None).await {
Decision::Deny => Err("the user declined to decrypt the message".to_string()),
_ => decrypt(m, config.user_keys.secret_key(), &peer, payload(&params)),
}
}
},
other => Err(format!("unsupported method: {other}")),
};
respond(config, event, &id, result)
}
/// Put a request to the user unless a stored permission covers it.
///
/// The policy check and the recording are both short, synchronous lock
/// operations: the lock is never held across the `await` that asks the user.
async fn gate(
config: &SignerConfig,
client: &ClientInfo,
request: Request,
permission: Option<Permission>,
) -> Decision {
if let Some(permission) = &permission {
let covered = config
.registry
.lock()
.unwrap()
.permits(&client.public_key, permission);
if covered && config.rate.claim(&client.public_key.to_hex()) {
return Decision::Once;
}
}
let decision = config.approver.ask(client.clone(), request).await;
if decision == Decision::Always {
if let Some(permission) = permission {
if let Err(error) = config
.registry
.lock()
.unwrap()
.allow(&client.public_key, permission)
{
eprintln!("regent: could not remember the permission: {error}");
}
}
}
decision
}
/// A client with no recorded metadata, for an approved key we cannot describe.
fn bare_client(public_key: &PublicKey) -> ClientInfo {
ClientInfo {
public_key: *public_key,
name: None,
url: None,
image: None,
}
}
/// The NIP name for an encrypt/decrypt method, for display.
fn nim_name(method: &str) -> &'static str {
if method.starts_with("nip04") {
"nip04"
} else {
"nip44"
}
}
fn encrypt(
method: &str,
secret_key: &SecretKey,
peer: &PublicKey,
payload: &str,
) -> std::result::Result<String, String> {
if method.starts_with("nip04") {
nip04::encrypt(secret_key, peer, payload).map_err(|error| error.to_string())
} else {
nip44::encrypt(secret_key, peer, payload, nip44::Version::V2)
.map_err(|error| error.to_string())
}
}
fn decrypt(
method: &str,
secret_key: &SecretKey,
peer: &PublicKey,
ciphertext: &str,
) -> std::result::Result<String, String> {
if method.starts_with("nip04") {
nip04::decrypt(secret_key, peer, ciphertext).map_err(|error| error.to_string())
} else {
nip44::decrypt(secret_key, peer, ciphertext).map_err(|error| error.to_string())
}
}
/// Build the answer: NIP-44 encrypted (what both go-nostr and rust-nostr
/// expect), p-tagging the client, signed with the device key.
fn respond(
@@ -367,16 +491,22 @@ fn client_info(public_key: &PublicKey, params: &[String]) -> ClientInfo {
}
}
fn sign_event(
raw: Option<&String>,
user_keys: &Keys,
) -> std::result::Result<String, String> {
/// An event a client asked to have signed, still unsigned.
struct Incoming {
kind: Kind,
content: String,
created_at: Timestamp,
tags: Vec<Tag>,
}
/// Parse the event out of a `sign_event` parameter.
fn incoming(raw: Option<&String>) -> std::result::Result<Incoming, String> {
let raw = raw.ok_or("sign_event: missing event")?;
let value: serde_json::Value =
serde_json::from_str(raw).map_err(|error| error.to_string())?;
let kind = Kind::from(value["kind"].as_u64().unwrap_or(1) as u16);
let content = value["content"].as_str().unwrap_or_default();
let content = value["content"].as_str().unwrap_or_default().to_string();
let created_at = value["created_at"]
.as_u64()
.map(Timestamp::from)
@@ -391,13 +521,86 @@ fn sign_event(
})
.unwrap_or_default();
let unsigned = UnsignedEvent::new(user_keys.public_key(), created_at, kind, tags, content);
Ok(Incoming {
kind,
content,
created_at,
tags,
})
}
fn sign(incoming: Incoming, user_keys: &Keys) -> std::result::Result<String, String> {
let unsigned = UnsignedEvent::new(
user_keys.public_key(),
incoming.created_at,
incoming.kind,
incoming.tags,
incoming.content,
);
user_keys
.sign_event(unsigned)
.map(|event| event.as_json())
.map_err(|error| error.to_string())
}
/// How much of a client-supplied string is shown in a dialog.
const PREVIEW_CHARS: usize = 280;
/// A plain, bounded preview of attacker-controlled text.
///
/// The result is only ever rendered as text — never as markup — so a client
/// cannot fake Regent's own formatting.
fn preview(text: &str) -> String {
let text = text.replace('\r', "");
if text.is_empty() {
return "(empty)".to_string();
}
let mut shown: String = text.chars().take(PREVIEW_CHARS).collect();
if text.chars().count() > PREVIEW_CHARS {
shown.push('…');
}
shown
}
/// A short, plain summary of an event's tags: `name=value, name=value, …`.
fn tag_summary(tags: &[Tag]) -> String {
if tags.is_empty() {
return "No tags".to_string();
}
let mut parts = Vec::new();
for tag in tags.iter().take(6) {
let fields = tag.as_slice();
let name = fields.first().map(String::as_str).unwrap_or_default();
let values = fields
.iter()
.skip(1)
.take(2)
.map(|value| shorten(value))
.collect::<Vec<_>>()
.join(" ");
if values.is_empty() {
parts.push(name.to_string());
} else {
parts.push(format!("{name}={values}"));
}
}
let mut summary = parts.join(", ");
if tags.len() > 6 {
summary.push_str(", …");
}
summary
}
/// Trim a single tag value so a wall of text cannot flood the dialog.
fn shorten(value: &str) -> String {
const LIMIT: usize = 16;
let mut shown: String = value.chars().take(LIMIT).collect();
if value.chars().count() > LIMIT {
shown.push('…');
}
shown
}
/// The peer pubkey that the first parameter of the nip04/nip44 calls refers to.
fn peer(params: &[String]) -> std::result::Result<PublicKey, String> {
let raw = params.first().ok_or("missing peer pubkey")?;
@@ -426,16 +629,28 @@ mod tests {
Self { relay, child: None }
}
None => {
const PORT: u16 = 10566;
// The tests run in parallel, so each gets its own relay; a
// shared port means the second `nak serve` fails to bind and
// the tests then hang on a relay that never answers.
static NEXT_PORT: std::sync::atomic::AtomicU16 =
std::sync::atomic::AtomicU16::new(10566);
let port = NEXT_PORT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let child = std::process::Command::new("nak")
.args(["serve", "--port", &PORT.to_string()])
.args(["serve", "--port", &port.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("spawn nak serve");
tokio::time::sleep(Duration::from_millis(800)).await;
// Wait for it to actually accept connections rather than
// guessing a sleep.
for _ in 0..50 {
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
Self {
relay: format!("ws://127.0.0.1:{PORT}"),
relay: format!("ws://127.0.0.1:{port}"),
child: Some(child),
}
}
@@ -445,6 +660,7 @@ mod tests {
fn stop(&mut self) {
if let Some(child) = &mut self.child {
let _ = child.kill();
let _ = child.wait();
}
}
}
@@ -460,6 +676,30 @@ mod tests {
(approver, handle)
}
/// Answers with `decide`, and records every question that was asked.
fn recording_approver<F>(
decide: F,
) -> (
Approver,
tokio::task::JoinHandle<()>,
Arc<Mutex<Vec<Request>>>,
)
where
F: Fn(&Request) -> Decision + Send + 'static,
{
let (approver, questions) = Approver::new();
let seen = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&seen);
let handle = tokio::spawn(async move {
while let Ok(question) = questions.recv().await {
let decision = decide(&question.request);
log.lock().unwrap().push(question.request.clone());
let _ = question.reply.send(decision).await;
}
});
(approver, handle, seen)
}
fn config(relay: &str, approver: Approver) -> SignerConfig {
SignerConfig {
device_keys: Keys::generate(),
@@ -468,6 +708,7 @@ mod tests {
secret: "test-secret".to_string(),
approver,
registry: Arc::new(Mutex::new(AppRegistry::default())),
rate: RateLimiter::new(60),
}
}
@@ -492,7 +733,7 @@ mod tests {
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
async fn nak_can_pair_and_sign() {
let mut relay = TestRelay::start().await;
let (approver, approvals) = auto_approver(Decision::Always);
let (approver, approvals, seen) = recording_approver(|_| Decision::Always);
let config = config(&relay.relay, approver);
let expected = config.user_keys.public_key();
let signer = Signer::start(config).await.expect("start signer");
@@ -515,6 +756,94 @@ mod tests {
expected.to_hex(),
"the event must be signed by the identity key, not the device key"
);
// The point of M4: the user saw what was being signed.
let seen = seen.lock().unwrap();
let signed = seen
.iter()
.find_map(|request| match request {
Request::Sign { kind, preview, .. } => Some((*kind, preview.clone())),
_ => None,
})
.expect("the signer must have asked before signing");
assert_eq!(signed.0, 1, "nak signs a kind 1 note");
assert!(
signed.1.contains("hello from nak"),
"the dialog must show the content, saw {:?}",
signed.1
);
}
/// 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"]
async fn nak_signing_is_refused_when_the_user_says_no() {
let mut relay = TestRelay::start().await;
let (approver, approvals, _) = recording_approver(|request| match request {
Request::Pair => Decision::Always,
_ => Decision::Deny,
});
let config = config(&relay.relay, approver);
let signer = Signer::start(config).await.expect("start signer");
let output = nak_signs(signer.bunker_uri()).await;
relay.stop();
signer.stop().await;
approvals.abort();
assert!(
!output.status.success(),
"nak must not receive a signature after a denial: {}",
String::from_utf8_lossy(&output.stdout)
);
}
/// "Allow always" is remembered: the next identical request is answered
/// without asking, while a different kind asks again.
#[tokio::test]
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
async fn nak_allow_always_skips_the_next_ask() {
let mut relay = TestRelay::start().await;
let (approver, approvals, seen) = recording_approver(|_| Decision::Always);
let config = config(&relay.relay, approver);
let signer = Signer::start(config).await.expect("start signer");
let first = nak_signs(signer.bunker_uri()).await;
assert!(
first.status.success(),
"the first sign failed: {}",
String::from_utf8_lossy(&first.stderr)
);
let after_first = seen
.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Sign { .. }))
.count();
// The same client, the same kind: this must not ask again.
let second = nak_signs(signer.bunker_uri()).await;
relay.stop();
signer.stop().await;
approvals.abort();
assert!(
second.status.success(),
"the second sign failed: {}",
String::from_utf8_lossy(&second.stderr)
);
let after_second = seen
.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Sign { .. }))
.count();
assert_eq!(
after_first, after_second,
"an \"always\" answer must cover the next identical request"
);
}
/// Saying no has to mean no: the client must not be able to pair.
@@ -538,4 +867,285 @@ mod tests {
String::from_utf8_lossy(&output.stdout)
);
}
// ----- Deterministic tests against the responder itself. -----
//
// These drive `handle_request` as a client would — NIP-44 encrypted,
// p-tagged to the device key — but with a client key we control, so the
// policy paths can be checked without a relay or `nak`.
/// Build the kind:24133 event a client would send.
fn client_request(
client: &Keys,
device: &PublicKey,
method: &str,
params: serde_json::Value,
) -> 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(),
Timestamp::now(),
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 =
nip44::decrypt(client.secret_key(), device, &response.content).expect("decrypt");
serde_json::from_str(&plain).expect("a JSON envelope")
}
/// Pair the client and return the device key.
async fn pair(client: &Keys, config: &SignerConfig) -> PublicKey {
let device = config.device_keys.public_key();
let request = client_request(
client,
&device,
"connect",
serde_json::json!(["", config.secret, "", ""]),
);
let response = handle_request(&request, config)
.await
.expect("handle")
.expect("an answer");
assert!(
read_response(&response, client, &device)["result"].is_string(),
"pairing should succeed"
);
device
}
fn sign_params(kind: u16, content: &str) -> serde_json::Value {
serde_json::json!([serde_json::json!({
"kind": kind,
"content": content,
"tags": [["t", "nostr"]],
})
.to_string()])
}
fn sign_asks(seen: &Mutex<Vec<Request>>) -> usize {
seen.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Sign { .. }))
.count()
}
#[tokio::test]
async fn signing_asks_and_a_denial_reaches_the_client() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|request| match request {
Request::Pair => Decision::Always,
_ => Decision::Deny,
});
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
let request =
client_request(&client, &device, "sign_event", sign_params(1, "hello world"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
task.abort();
assert!(answer["result"].is_null());
assert!(
answer["error"]
.as_str()
.unwrap_or_default()
.contains("declined"),
"the client must see the denial, got {answer}"
);
// The dialog showed the kind and the content.
let seen = seen.lock().unwrap();
let shown = seen
.iter()
.find_map(|request| match request {
Request::Sign { kind, preview, tags } => {
Some((*kind, preview.clone(), tags.clone()))
}
_ => None,
})
.expect("the user was asked");
assert_eq!(shown.0, 1);
assert!(shown.1.contains("hello world"), "preview was {:?}", shown.1);
assert!(shown.2.contains("t=nostr"), "tags were {:?}", shown.2);
}
#[tokio::test]
async fn allow_always_skips_the_next_ask_for_that_kind() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|request| match request {
Request::Pair => Decision::Always,
Request::Sign { kind: 7, .. } => Decision::Deny,
_ => Decision::Always,
});
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
// A kind 1 note: allowed once, then remembered by kind.
for _ in 0..2 {
let request = client_request(&client, &device, "sign_event", sign_params(1, "one"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
assert!(
answer["result"].is_string(),
"kind 1 should be signed, got {answer}"
);
}
assert_eq!(
sign_asks(&seen),
1,
"the second kind 1 request must not ask again"
);
// A kind 7 reaction is not covered, so it asks (and is denied).
let request = client_request(&client, &device, "sign_event", sign_params(7, "+"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
task.abort();
assert!(answer["error"].is_string(), "kind 7 was denied");
assert_eq!(sign_asks(&seen), 2, "a new kind must ask");
}
#[tokio::test]
async fn encryption_can_be_remembered_but_decryption_always_asks() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|_| Decision::Always);
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
let user = config.user_keys.public_key();
let peer = client.public_key().to_hex();
// Encrypting twice: the first "always" stores the method, the second
// does not ask.
for _ in 0..2 {
let request = client_request(
&client,
&device,
"nip44_encrypt",
serde_json::json!([peer, "secret message"]),
);
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["result"].is_string());
}
// A ciphertext the user key can actually open, sent by this client.
let ciphertext =
nip44::encrypt(client.secret_key(), &user, "opened once", nip44::Version::V2)
.expect("encrypt");
for _ in 0..2 {
let request = client_request(
&client,
&device,
"nip44_decrypt",
serde_json::json!([peer, ciphertext]),
);
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
assert_eq!(
answer["result"].as_str(),
Some("opened once"),
"decryption should succeed"
);
}
task.abort();
let encrypts = seen
.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Encrypt { .. }))
.count();
let decrypts = seen
.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Decrypt { .. }))
.count();
assert_eq!(encrypts, 1, "an \"always\" encryption is answered silently");
assert_eq!(
decrypts, 2,
"decryption is a content oracle and must always ask"
);
}
/// Once the rate limit is spent, an "always" permission asks again.
#[tokio::test]
async fn an_exhausted_rate_limit_asks_again() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|_| Decision::Always);
let mut config = config("ws://127.0.0.1:1", approver);
config.rate = RateLimiter::new(1);
let device = pair(&client, &config).await;
// The first request asks and stores the kind; the second is answered
// silently (the one slot); the third is over the limit and asks again.
for _ in 0..3 {
let request = client_request(&client, &device, "sign_event", sign_params(1, "one"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["result"].is_string());
}
task.abort();
assert_eq!(
sign_asks(&seen),
2,
"one silent answer fits the limit; the next one asks again"
);
}
/// No UI, no answer: a dropped question must deny rather than hang.
#[tokio::test]
async fn a_dropped_question_is_a_denial() {
let (approver, questions) = Approver::new();
let drain = tokio::spawn(async move {
while let Ok(question) = questions.recv().await {
drop(question); // nobody ever answers
}
});
let client = ClientInfo {
public_key: Keys::generate().public_key(),
name: None,
url: None,
image: None,
};
assert_eq!(approver.ask(client, Request::Pair).await, Decision::Deny);
drain.abort();
}
}
+201 -49
View File
@@ -1,4 +1,9 @@
//! Showing approval questions and turning the answer into a `Decision`.
//!
//! Everything shown here beyond our own words is client-supplied and
//! unauthenticated. It is rendered as **plain, selectable text** — never as
//! Pango markup — so an application cannot forge formatting that looks like
//! Regent's own interface.
use async_channel::Receiver;
use nostr::nips::nip19::ToBech32;
@@ -20,37 +25,57 @@ pub fn install(questions: Receiver<ApprovalRequest>, widget: gtk::Widget) {
});
}
/// Which buttons a question offers.
enum Choices {
/// Denying or connecting; a connect is always remembered (M3 pairing).
Pair,
/// Deny or allow once. Used for decryption, which never remembers a yes.
Once,
/// Deny, allow once, or allow always (which stores a permission).
OnceAlways,
}
async fn present(widget: &gtk::Widget, question: &ApprovalRequest) -> Decision {
let client = &question.client;
let name = client
.name
.clone()
.unwrap_or_else(|| "An unnamed application".to_string());
let choices = match &question.request {
Request::Pair => Choices::Pair,
request if !request.allows_always() => Choices::Once,
_ => Choices::OnceAlways,
};
let dialog = adw::AlertDialog::builder()
.title(match &question.request {
Request::Pair => format!("Connect {name}?"),
Request::Sign { .. } => format!("Sign for {name}?"),
Request::Encrypt { .. } => format!("Encrypt for {name}?"),
Request::Decrypt { .. } => format!("Decrypt for {name}?"),
})
.body(describe(question))
// Heading and body are plain text too: the heading carries no client
// data today, but the extra child is where all of it belongs.
.heading_use_markup(false)
.body_use_markup(false)
.heading(heading(&question.request))
.body(story(&question.request))
.content_width(460)
.extra_child(&details(question))
.build();
dialog.add_response("deny", "Deny");
dialog.add_response("allow", "Allow");
dialog.set_default_response(Some("allow"));
dialog.set_response_appearance("allow", adw::ResponseAppearance::Suggested);
dialog.set_close_response("deny");
match choices {
Choices::Pair => {
dialog.add_response("allow", "Connect");
dialog.set_response_appearance("allow", adw::ResponseAppearance::Suggested);
}
Choices::Once => {
dialog.add_response("once", "Allow once");
dialog.set_response_appearance("once", adw::ResponseAppearance::Suggested);
}
Choices::OnceAlways => {
dialog.add_response("once", "Allow once");
dialog.set_response_appearance("once", adw::ResponseAppearance::Suggested);
dialog.add_response("always", "Allow always");
}
}
let (sender, answer) = async_channel::bounded(1);
// For a pairing, "allow" means remember the application; for everything else
// it is a one-off decision.
let pairing = matches!(question.request, Request::Pair);
dialog.connect_response(None, move |_, response| {
let decision = match response {
"allow" if pairing => Decision::Always,
"allow" => Decision::Once,
"always" => Decision::Always,
"once" | "allow" => Decision::Once,
_ => Decision::Deny,
};
let _ = sender.try_send(decision);
@@ -61,40 +86,167 @@ async fn present(widget: &gtk::Widget, question: &ApprovalRequest) -> Decision {
answer.recv().await.unwrap_or(Decision::Deny)
}
fn describe(question: &ApprovalRequest) -> String {
let client = &question.client;
let mut lines = Vec::new();
match &question.request {
Request::Pair => lines.push(
"It will be able to ask for signatures and to encrypt or decrypt messages in \
your name."
.to_string(),
),
Request::Sign { kind, preview } => {
lines.push(format!("Kind {kind}"));
if !preview.is_empty() {
lines.push(preview.clone());
}
}
Request::Encrypt { peer } => lines.push(format!("Encrypting to {peer}")),
Request::Decrypt { peer } => lines.push(format!("Decrypting from {peer}")),
fn heading(request: &Request) -> String {
match request {
Request::Pair => "Connect an application?".to_string(),
Request::Sign { .. } => "Sign an event?".to_string(),
Request::Encrypt { .. } => "Encrypt a message?".to_string(),
Request::Decrypt { .. } => "Decrypt a message?".to_string(),
}
}
lines.push(String::new());
lines.push(format!(
"Public key: {}",
client.public_key.to_bech32().unwrap_or_default()
/// Our own words about what the request means. No client data.
fn story(request: &Request) -> &'static str {
match request {
Request::Pair => {
"It would be able to ask Regent for signatures and encryption. Every such \
request will still be shown to you."
}
Request::Sign { .. } => {
"It wants Regent to sign an event with your identity key."
}
Request::Encrypt { .. } => "It wants Regent to encrypt a message in your name.",
Request::Decrypt { .. } => "It wants Regent to decrypt a message for you.",
}
}
/// The selectable, plain-text detail block: who is asking and exactly what.
fn details(question: &ApprovalRequest) -> gtk::Box {
let client = &question.client;
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(10)
.build();
content.append(&field(
"Application",
client.name.as_deref().unwrap_or("(unnamed)"),
));
if let Some(url) = &client.url {
lines.push(format!("Declared URL: {url}"));
content.append(&field("Declared URL", url));
}
lines.push(String::new());
lines.push(
"The name and URL above are supplied by the application itself and cannot be \
trusted."
.to_string(),
content.append(&field(
"Public key",
&client.public_key.to_bech32().unwrap_or_default(),
));
match &question.request {
Request::Pair => {}
Request::Sign {
kind,
preview,
tags,
} => {
content.append(&field("Kind", &format!("{} ({})", kind, kind_name(*kind))));
content.append(&block("Content", preview));
content.append(&field("Tags", tags));
}
Request::Encrypt {
method,
peer,
preview,
} => {
content.append(&field("Method", method));
content.append(&field("Peer", peer));
content.append(&block("Message", preview));
}
Request::Decrypt {
method,
peer,
preview,
} => {
content.append(&field("Method", method));
content.append(&field("Peer", peer));
content.append(&block("Ciphertext", preview));
}
}
content.append(&note(
"The application's name and URL are supplied by the application itself and \
cannot be trusted.",
));
content
}
/// A label/value row. Both halves are plain and selectable.
fn field(title: &str, value: &str) -> gtk::Box {
let row = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(12)
.build();
let title = gtk::Label::builder()
.label(title)
.xalign(0.0)
.valign(gtk::Align::Start)
.width_chars(12)
.css_classes(["dim-label"])
.build();
let value = plain(value);
value.set_hexpand(true);
row.append(&title);
row.append(&value);
row
}
/// A titled block for text that may be long, laid out like a quote.
fn block(title: &str, value: &str) -> gtk::Box {
let container = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(4)
.build();
container.append(
&gtk::Label::builder()
.label(title)
.xalign(0.0)
.css_classes(["dim-label"])
.build(),
);
lines.join("\n")
let body = plain(value);
body.set_margin_top(8);
body.set_margin_bottom(8);
body.set_margin_start(8);
body.set_margin_end(8);
body.set_hexpand(true);
let frame = gtk::Box::builder().css_classes(["card"]).build();
frame.append(&body);
container.append(&frame);
container
}
fn note(text: &str) -> gtk::Label {
let label = plain(text);
label.add_css_class("dim-label");
label
}
/// The one way client-supplied text reaches the screen.
fn plain(text: &str) -> gtk::Label {
gtk::Label::builder()
.label(text)
.use_markup(false)
.selectable(true)
.wrap(true)
.xalign(0.0)
.max_width_chars(56)
.halign(gtk::Align::Start)
.build()
}
/// A short, human name for the common kinds; the bare number otherwise.
fn kind_name(kind: u16) -> &'static str {
match kind {
0 => "profile metadata",
1 => "text note",
3 => "follow list",
4 => "encrypted direct message",
5 => "deletion",
6 => "repost",
7 => "reaction",
24133 => "NIP-46 message",
30023 => "long-form article",
_ => "event",
}
}
+16 -6
View File
@@ -223,11 +223,20 @@ fn start(
let Some(store) = state.store() else {
return;
};
let relays = Config::new().relays();
let settings = Config::new();
let relays = settings.relays();
let auto_approve_limit = settings.auto_approve_limit();
runtime::spawn(
async move {
let config = SignerConfig::from_store(&store, relays, approver, registry).await?;
let config = SignerConfig::from_store(
&store,
relays,
approver,
registry,
auto_approve_limit,
)
.await?;
Signer::start(config).await
},
move |result| match result {
@@ -282,10 +291,11 @@ fn show_running(handles: &Handles, signer: &Signer) {
Err(error) => handles.status.set_subtitle(&format!("QR failed: {error}")),
}
// Loud on purpose: until M4 every request is answered without asking.
handles.banner.set_title(
"Approved applications can sign anything without asking yet — per-request approval arrives next",
);
// Every sensitive request is put to the user; "allow always" only silences
// the exact thing it was granted for.
handles
.banner
.set_title("Regent will ask you before signing, encrypting or decrypting anything");
handles.banner.set_revealed(true);
}