Merge pull request 'Let the user remember a decryption' (#11) from feat/decrypt_allow_always into main
CI / test (push) Successful in 1m20s

Reviewed-on: #11
This commit was merged in pull request #11.
This commit is contained in:
raucao committed 2026-12-01 08:19:54 +00:00
commit f0c02f43cf
9 files changed
+164 -47

No files matched your search

+39 -12
View File
@@ -87,9 +87,10 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
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.
but **every sensitive request is still put to the user** — `sign_event`,
`nip04/nip44_encrypt` and `nip04/nip44_decrypt` — **until the user grants
"always" for it** (the policy model below). `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
@@ -97,11 +98,30 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
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
permission is answered without asking — subject to the rate limit below.
- **Decryption always asks.** It is a content oracle, so `Decrypt` never stores a
permission and the dialog offers only Deny / Allow once. Silently decrypting
is the exact flaw this project exists to replace; do not "optimise" it away.
of **kinds**, for encryption and decryption a **method name**. A request
covered by a stored permission is answered without asking — subject to the
rate limit below.
- **Decryption can be granted (2026-12-01).** It is the most consequential grant
— the ciphertexts already sit on relays, so "always" reaches history the
application was never asked about — but refusing to remember a yes made a chat
client re-read its history one prompt per message, which trains the user to
click through the prompts that matter. So `Decrypt` now stores a
`Permission::Method` like an encryption (per application, per method) and the
dialog offers Deny / Allow once / Allow always. Three things keep it honest:
the dialog carries an **above-the-fold banner** spelling out the scope (every
peer, and older messages fetchable from any relay — `request_warnings`); the
grant is deliberately **not** peer-scoped, because a NIP-17 gift wrap is
signed by a fresh ephemeral key per message, so a peer-scoped rule would match
only the inner seal and still prompt for every wrapper; and the rate limit, the
activity log (`allowed-silently`), the per-permission *Remove* row and the
immediate effect of revocation all still apply. The vault gate is unchanged: a
granted decrypt on a locked vault still raises the unlock prompt, and in
headless a locked vault still denies.
- **The rate limit bites a history sync.** `auto-approve-limit` is per app across
all silent answers, and a NIP-17 DM costs two decrypts (wrap + seal), so a sync
past roughly half the limit — default 30/min, so ~15 messages — asks again.
That is the runaway backstop working as designed; the user can raise it in
Preferences. Accepted and documented rather than special-cased.
- **NIP-04 is flagged (I2).** A `nip04_encrypt`/`nip04_decrypt` request adds an
above-the-fold banner saying NIP-04 is the older, unauthenticated scheme and
NIP-44 is recommended (`request_warnings`, comparing the `nim_name` form
@@ -207,8 +227,13 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
Anything the dialog cannot show in full is disclosed by an `AdwBanner` above the
fold — truncated content (against the responder's `CONTENT_LIMIT`), hidden
tags/tag values, and a timestamp more than an hour from now — so nothing that is
signed or encrypted is invisible (**WYSIWYS**, H2). A pairing whose client declared
no name also gets a **name field** there — under "Application", above the
signed or encrypted is invisible (**WYSIWYS**, H2). Those banners carry
`.warning`, which `data/style.css` maps to a warning tint: `AdwBanner` is tinted
through its `--banner-color` variable (libadwaita mixes it 30% into the window
background), and `.warning` **alone** does nothing on a banner — it only
recolours the foreground, which the banner's inner widget overrides. A pairing
whose client declared no name also gets a **name field** there — under
"Application", above the
Details — because that is the one prompt where the user decides to trust an
app and can still give it a name; the entered name travels back in the
`Answer`. The "name and URL are supplied
@@ -389,7 +414,8 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
registry and a second signer on the same device key.
- The Apps page shows one `AdwExpanderRow` per app, with a per-app `view-more`
menu as its only suffix (*Rename…* and *Revoke*), one *Remove* row per stored
permission (kind for `sign_event`, method for encryption), and *Forget all*.
permission (kind for `sign_event`, method for encryption or decryption), and
*Forget all*.
The list is **newest approval first** (`list_for` sorts by `approved_at`,
descending, ties in reverse insertion order), so a re-pairing moves an app back
to the top and pre-`approved_at` entries (timestamp 0) sit at the bottom.
@@ -1388,7 +1414,8 @@ the UI is tested. `build-aux/deploy-dev.sh` runs on the build host,
port — sharing one port makes the parallel run hang.
- The policy logic itself is also covered by fast, relay-free tests that drive
`handle_request` with a client key they control (denial, allow-always per kind,
encryption remembered vs. decryption always asking, the rate limit, a dropped
encryption and decryption both remembered, a silent answer logged as
`allowed-silently`, the rate limit, a dropped
question denying, revoking a permission bringing the prompt back, `logout`
forgetting the app, `get_permissions`, and registry changes being announced).
The audit has its own tests: a content canary never reaches the log,
+10
View File
@@ -13,6 +13,16 @@ the only place release notes are written.
## [Unreleased]
### Changed
- Decryption requests can be remembered. The approval dialog now offers *Allow
always* for a decryption as it already did for signing and encryption, so a
chat application that re-reads its message history on every launch no longer
prompts once per message. The dialog states what the grant covers, the Apps
page lists it as a permission you can remove, every silently answered request
is still recorded in the activity log, and the auto-approval rate limit still
applies.
### Fixed
- Enter now submits the field-based dialogs — unlock, export, change passphrase,
+15
View File
@@ -34,3 +34,18 @@ label.key-value {
font-family: var(--monospace-font-family);
font-weight: normal;
}
/* A warning banner. libadwaita tints an `AdwBanner`'s background by mixing
`--banner-color` (a neutral gray by default) into the window background, so
the semantic warning tint is one variable override — the same recipe
`GtkInfoBar` uses. libadwaita's own `.warning` class changes nothing here: it
only recolours the foreground, which the banner's inner widget overrides, and
the background comes from this variable. 6px keeps the banner a callout,
well inside the dialog's 18px sheet. */
banner.warning {
--banner-color: var(--warning-bg-color);
}
banner.warning > revealer > widget {
border-radius: 6px;
}
+7 -11
View File
@@ -99,6 +99,13 @@ pub enum Request {
message_chars: usize,
},
/// A message would be decrypted from someone.
///
/// "Always" **is** offered for this, unlike the original design. A chat
/// client re-reads its whole history on every launch, so a prompt per
/// message trains the user to click through — and the prompts it trains
/// them through include the ones that matter. The grant is per application
/// and per method, the dialog discloses its scope, and the rate limit still
/// bounds a silent stream.
Decrypt {
method: &'static str,
peer: String,
@@ -106,17 +113,6 @@ pub enum Request {
},
}
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)]
pub enum Decision {
Deny,
+48 -8
View File
@@ -1083,8 +1083,11 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
Ok(peer) => match app_identity(config, &event.pubkey) {
Err(error) => Err(error),
Ok(identity) => {
// Decryption may never be answered without asking: no
// permission is offered, so it always reaches the user.
// A decrypt can be remembered like an encrypt: a chat client
// re-reads its whole history on every launch, so a prompt per
// message is prompt fatigue, not a control. The grant is per
// application and per method, and the dialog spells out that
// it covers any peer and history fetched from relays.
let request = Request::Decrypt {
method: nim_name(m),
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
@@ -1095,7 +1098,7 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
&client,
identity,
request,
None,
Some(Permission::Method(m.to_string())),
m,
None,
"the user declined to decrypt the message",
@@ -2636,11 +2639,16 @@ mod tests {
assert_eq!(sign_asks(&seen), 2, "a new kind must ask");
}
/// "Always" is remembered for encryption and decryption alike: a chat client
/// re-reads its history on every launch, so a decrypt must not prompt per
/// message any more than an encrypt does.
#[tokio::test]
async fn encryption_can_be_remembered_but_decryption_always_asks() {
async fn encryption_and_decryption_can_be_remembered() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|_| Decision::Always);
let config = config("ws://127.0.0.1:1", approver);
let (log_path, log) = temp_log();
let (changes, _receiver) = async_channel::unbounded();
let config = config_with("ws://127.0.0.1:1", approver, log.clone(), changes);
let device = pair(&client, &config).await;
let user = user_public(&config);
let peer = client.public_key().to_hex();
@@ -2700,9 +2708,20 @@ mod tests {
.count();
assert_eq!(encrypts, 1, "an \"always\" encryption is answered silently");
assert_eq!(
decrypts, 2,
"decryption is a content oracle and must always ask"
decrypts, 1,
"an \"always\" decryption is answered silently too"
);
// Each remembered answer is logged as a silent one, never as allowed:
// the log must not claim a prompt the user was never shown.
let silent = log
.recent(10)
.into_iter()
.filter(|entry| entry.outcome == audit::outcome::SILENT)
.count();
assert_eq!(silent, 2, "both silent answers are recorded as such");
let _ = std::fs::remove_file(&log_path);
}
/// Once the rate limit is spent, an "always" permission asks again.
@@ -3098,6 +3117,27 @@ mod tests {
let device = pair(&client, &config).await;
assert!(sign_once(&client, &device, &config, "one").await["result"].is_string());
// And one remembered decryption, so the reported method set is not empty.
let user = user_public(&config);
let peer = client.public_key().to_hex();
let ciphertext =
nip44::encrypt(client.secret_key(), &user, "hi", nip44::Version::V2).expect("encrypt");
let decrypt = client_request(
&client,
&device,
"nip44_decrypt",
serde_json::json!([peer, ciphertext]),
);
let response = handle_request(&decrypt, &config)
.await
.expect("handle")
.expect("an answer");
assert_eq!(
read_response(&response, &client, &device)["result"].as_str(),
Some("hi"),
"the decryption is remembered"
);
let request = client_request(&client, &device, "get_permissions", serde_json::json!([]));
let response = handle_request(&request, &config)
.await
@@ -3109,7 +3149,7 @@ mod tests {
let policy: serde_json::Value =
serde_json::from_str(answer["result"].as_str().expect("a result")).unwrap();
assert_eq!(policy["kinds"], serde_json::json!([1]));
assert_eq!(policy["methods"], serde_json::json!([]));
assert_eq!(policy["methods"], serde_json::json!(["nip44_decrypt"]));
}
/// A spec-shaped `nostrconnect://` URI parses without rust-nostr's
+4 -3
View File
@@ -18,13 +18,14 @@ pub type Result<T> = std::result::Result<T, Error>;
/// One thing an application was told it may do without asking again.
///
/// This is what an "always" answer in a dialog turns into. It is deliberately
/// coarse: a method name for encryption, a single kind for signing.
/// coarse: a method name for encryption or decryption, a single kind for
/// signing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Permission {
/// Sign events of this kind.
Kind(u16),
/// Encrypt with this NIP method (`nip04_encrypt` / `nip44_encrypt`).
/// Decryption is never stored: it always asks.
/// Encrypt or decrypt with this NIP method (`nip04_encrypt` /
/// `nip44_encrypt` / `nip04_decrypt` / `nip44_decrypt`).
Method(String),
}
+3 -2
View File
@@ -2,8 +2,9 @@
//!
//! Append-only JSON Lines under the user data directory, mode 0600. It records
//! **metadata only**. `Entry` deliberately has a typed `kind: Option<u16>` and
//! no free-form detail field: a signer that kept a log of what was signed and
//! decrypted would be the very content oracle this project exists to replace.
//! no free-form detail field: the log must never hold the content that was
//! signed, encrypted or decrypted, whether or not the request was answered
//! without asking.
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
+34 -9
View File
@@ -275,8 +275,6 @@ fn expire<T: Send + 'static>(
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,
}
@@ -328,7 +326,6 @@ pub async fn present_question(
let request = &question.request;
let choices = match request {
Request::Pair { .. } => Choices::Pair,
request if !request.allows_always() => Choices::Once,
_ => Choices::OnceAlways,
};
@@ -357,10 +354,6 @@ pub async fn present_question(
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);
@@ -816,6 +809,11 @@ fn banner(text: &str) -> adw::Banner {
banner.set_use_markup(false);
banner.set_title(text);
banner.set_revealed(true);
// libadwaita tints a banner by mixing `--banner-color` (a neutral gray by
// default) into the window background; `data/style.css` maps `.warning` to
// the warning colour and rounds the corners. The class also recolours any
// accent-coloured child, though our banners carry only a title.
banner.add_css_class("warning");
banner
}
@@ -890,6 +888,15 @@ fn request_warnings(request: &Request) -> Vec<String> {
message_chars.div_ceil(1024)
));
}
// A decrypt is the one request whose "always" is a confidentiality
// decision: the ciphertexts already sit on relays, so a stored grant
// reaches history the application was never asked about.
Request::Decrypt { .. } => warnings.push(
"If you choose Allow always, this application can decrypt every \
message between you and anyone, including older messages it can \
fetch from any relay, without asking again."
.to_string(),
),
_ => {}
}
// NIP-04 is the unauthenticated legacy scheme; disclose it (I2).
@@ -1113,9 +1120,11 @@ mod tests {
peer: "npub1".to_string(),
preview: "cipher".to_string(),
};
// Two banners stack for a NIP-04 decrypt: the grant's scope, and the
// legacy-scheme flag.
let warnings = request_warnings(&decrypt);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].contains("NIP-04"));
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|warning| warning.contains("NIP-04")));
let nip44 = Request::Encrypt {
method: "nip44",
@@ -1125,4 +1134,20 @@ mod tests {
};
assert!(request_warnings(&nip44).is_empty());
}
/// A decrypt that offers "always" discloses what that grant covers: every
/// peer, and history the application can fetch from any relay.
#[test]
fn a_decrypt_discloses_the_always_grant() {
let decrypt = Request::Decrypt {
method: "nip44",
peer: "npub1".to_string(),
preview: "cipher".to_string(),
};
let warnings = request_warnings(&decrypt);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].contains("anyone"));
assert!(warnings[0].contains("older messages"));
assert!(warnings[0].contains("any relay"));
}
}
+4 -2
View File
@@ -348,7 +348,7 @@ impl Ui {
row.add_row(&self.permission_row(app, Permission::Kind(*kind_number), &title));
}
for method in &app.policy.methods {
let title = encryption_label(method);
let title = method_label(method);
row.add_row(&self.permission_row(app, Permission::Method(method.clone()), &title));
}
}
@@ -522,10 +522,12 @@ impl Ui {
}
}
fn encryption_label(method: &str) -> String {
fn method_label(method: &str) -> String {
match method {
"nip04_encrypt" => "Encrypt (NIP-04)".to_string(),
"nip44_encrypt" => "Encrypt (NIP-44)".to_string(),
"nip04_decrypt" => "Decrypt (NIP-04)".to_string(),
"nip44_decrypt" => "Decrypt (NIP-44)".to_string(),
other => other.to_string(),
}
}