Merge pull request 'Pre-1.0 security review: remediate all findings' (#8) from chore/security_review into main
CI / test (push) Successful in 1m40s

Reviewed-on: #8
This commit was merged in pull request #8.
This commit is contained in:
raucao committed 2026-11-30 08:21:34 +00:00
commit cd666e6fb2
37 files changed
+3744 -441

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
# Continuous integration for Regent (Gitea Actions).
#
# The job runs on the `regent-ci` runner, which is registered with the label
# `regent-ci:docker://gitea.kosmos.org/raucao/regent-ci:latest` (see
# doc/dev/development.md). That image bakes in the GTK 4 / libadwaita
# development headers, the Rust toolchain and cargo-deny, so this workflow
# installs nothing — the old ubuntu-latest job could not build against GTK 4.24
# and spent every run reinstalling the system and Rust dependencies.
#
# The Rust toolchain is pinned *in the image* (1.99.1): the `clippy -- -D
# warnings` gate is calibrated to a specific compiler, so a moving `stable`
# would reintroduce lint drift. `cargo-deny` fetches the RustSec advisory
# database at run time, so the job still needs network.
name: CI
on:
push:
pull_request:
jobs:
test:
runs-on: regent-ci
steps:
- uses: actions/checkout@v4
- name: Cache cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }}
- name: Test
run: cargo test --locked
- name: Clippy
run: cargo clippy --all-targets --locked -- -D warnings
- name: cargo-deny
run: cargo deny check
+191 -31
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
@@ -94,10 +102,31 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
- **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.
- **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
`"nip04"`).
- **Rate limit.** `signer::policy::RateLimiter` caps silent answers per app:
`auto-approve-limit` requests per minute (GSettings, default **30**). Past the
cap the request is asked again, so a runaway or compromised client turns back
into prompts instead of an open tap. Zero means never answer silently.
into prompts instead of an open tap. Zero means never answer silently. The
limit is a live `Arc<AtomicU32>` view of the setting, shared with the running
signer (`AppState::auto_approve_limit`; a `connect_changed` handler keeps it in
step), so setting it to 0 stops silent answers **immediately** — no stop/start,
and an external `gsettings set` is honoured too. The handler is installed on
the `gio::Settings` instance `AppState` holds for the process: it is owned by
that GObject and would die with it, and a bare `SignalHandlerId` keeps nothing
alive.
- **Replay and freshness (H1).** `kind:24133` is ephemeral, so the relay layer
never stores or deduplicates it: every delivery of the same event reaches the
responder again — a second relay, a reconnect, or an attacker replaying a
captured request. `signer::ReplayGuard`, checked in the responder loop before
`handle_request`, drops a wrapper event whose `created_at` is more than
`REQUEST_FRESHNESS` (120 s) from now, one minted before this run started, and
any event id already seen (bounded by `SEEN_CAPACITY`). The dedup is **in
memory only**: a stop/start cycle inside the freshness window re-admits a
request minted shortly before the restart (a persisted high-water mark is the
documented alternative; not implemented).
- Approvals go through `signer::approval::Approver`: the responder asks over a
channel, the dialog answers, and **a timeout or a missing UI denies** — never
allows. Client names/URLs shown in the dialog are client-supplied and must be
@@ -108,6 +137,17 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
overrides them, which is what headless tests use. The default is
`wss://nostr.kosmos.org` because **many public relays reject or rate-limit
`kind:24133`** — pairing silently times out on those.
- **A permission is stored only once the answer is produced (M1).** `gate()`
returns the user's verdict but does **not** write `apps.json`; `authorize_inner`
re-checks `identity_for` (and, for a silent answer, `permits`) after the last
`await` — the approval dialog and the unlock prompt both give the user time to
revoke or rebind the app — and only then stores "always" and fetches the key. A
revocation or rebind during either prompt therefore denies, and a cancelled
unlock leaves no permission behind. **Serialized now (L4):**
the in-app and `nostrconnect://`-link pairing dialogs go through the same
`Approver` queue (`Approver::ask_pairing` → the `Prompt::Pair` arm in
`ui/approval.rs::install`), so a pairing prompt can never stack over a request
prompt; the re-check above still makes the race fail closed.
- Two traps that make a signer look "hung" against a real relay. Both are fixed;
do not reintroduce them:
- **Subscriptions must target relays explicitly.** With gossip enabled (the
@@ -160,9 +200,14 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
our own words — never "it", because the application's name is a row and the
body must not carry client text (it is not selectable) — then the payload as a
bounded, scrollable card, so a long note cannot push the buttons off screen.
"Signing as" and "Application" stay above the fold; the verifiable-but-secondary
fields (client key, declared URL, kind number, raw tags, method, peer, "asked
for") live in a collapsed **Details** expander. A pairing whose client declared
"Signing as", "Application", the event **kind** and its client-requested
**Created at** timestamp stay above the fold (kind and timestamp are part of
what is signed); the verifiable-but-secondary fields (client key, declared URL,
raw tags, method, peer, "asked for") live in a collapsed **Details** expander.
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
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
@@ -658,28 +703,58 @@ 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. `--pair -` reads
the URI from **stdin** (I1), so it need not appear in `argv` or history. The
`bunker://` query is percent-encoded with `url::form_urlencoded` (I3), so a
relay URL cannot smuggle a second query parameter. 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.
- **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`; headless checks
`NameHasOwner` and exits "Regent is already running". With **no session bus**
(a server, an SSH box) the GUI cannot run either, so headless falls back to an
exclusive `flock` on `regent.lock` — which also catches two headless runs
started at once. The kernel drops the lock on exit, so it cannot go stale.
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
guard: a headless run owns no name, and with no session bus (a server, an SSH
box) neither does a GUI. Both the GUI (`application::run`'s `startup` handler)
and headless (`headless::serve`) therefore take an **unconditional** exclusive
`flock` on `regent.lock` (mode 0600) through `instance::claim`, which fails
closed if the lock file cannot be created or locked. That is what catches two
headless runs, a GUI beside a headless one, and a second GUI on a machine with
no session bus. The lock is taken in `startup`, which GLib emits only for the
primary instance, so a secondary forwarding a `nostrconnect://` link still
reaches the primary; a refused instance also short-circuits `activate`/`open`,
because `quit()` alone does not stop them being emitted. The kernel drops the
lock on exit, so it cannot go stale.
- Errors are loud: `--headless`/`--pair` print a message and exit non-zero for a
bad URI, an unreadable vault, no identity key, or a relay that refused the
connect response.
- **Unlocking for an unattended run**: `--passphrase-file <path>` (a small
regular file, mode 0400/0600 — never argv or the environment), or a systemd
credential at `$CREDENTIALS_DIRECTORY/regent-passphrase`, which wins when
present. It is read once, wrapped in `Zeroizing`, and never logged. Without it
present. It is opened **once** (`read_passphrase_file`, so no metadata/read
TOCTOU), **refused** if group/other can read it (not merely warned about), read
via `take(4097)` into a `Zeroizing` buffer, and never logged. Without it
a locked vault simply denies the sensitive methods. `--pair` needs no identity
secret and works while locked.
- **In-app pairing** (Apps page → "Connect an app…" or the primary menu): paste the
`nostrconnect://` string, then the *same* approval dialog used for responder
questions (`ui::approval::present_question`). On allow, the client's relays are
questions, through the same serialized `Approver` queue
(`Approver::ask_pairing`; L4). On allow, the client's relays are
added to the running signer and `signer::pair_client` registers + answers. If
the signer is stopped, it is started with the client's relays first. The
`SignerRunner` has a `Stopped | Starting | Running` state so a second start
@@ -710,25 +785,44 @@ 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)
- **One file, `keys.json`**, at `glib::user_data_dir()/org.kosmos.raucao.Regent/`
(mode **0600**, atomic temp+rename via `write_private`, a corrupt file moved to
`keys.json.corrupt`). It holds `version`, an optional plaintext `device` nsec,
and `keys: [{pubkey, name, ncryptsec}]`. There is **no Secret Service and no
(mode **0600**, written atomically to a **unique** `tempfile::NamedTempFile`
and renamed over the target, a corrupt file moved to a timestamped
`keys.json.corrupt.<secs>.<nanos>` so a second corruption does not erase the
first). It holds `version`, an optional plaintext `device` nsec,
and `keys: [{pubkey, name, ncryptsec}]`. A `version` **above 1** is refused
**in place** (left on disk, not quarantined — a newer vault is intact, not
corrupt), so an older Regent never silently downgrades it. There is **no
Secret Service and no
`oo7`** dependency: the login keyring was never at-rest protection (unlocked at
login for the whole session, keyed off the login password).
login for the whole session, keyed off the login password). The data, config
and cache directories — and the lock file's directory — are created **0700**
through the shared `store::create_private_dir` (L6), not with the process umask.
- **Vault mutations are serialized (M9).** `add_user_key` and `change_passphrase`
hold a `tokio::sync::Mutex` (`writes`) across their whole body, because each
encrypts and then updates state — interleaved, they could write a key under the
old passphrase beside keys re-encrypted under the new one, producing a vault no
passphrase opens. `save()` additionally holds a `std::sync::Mutex`
(`save_lock`, never across an `await`) across read-clone → write → rename, and
the temp file is unique, so concurrent saves cannot collide on a shared
`keys.json.tmp`. (`profiles.json` uses the same unique-temp write.)
- **Identity keys are NIP-49 `ncryptsec`** (`log_n = 16`, rust-nostr's
`MAX_LOG_N = 18` caps a tampered entry), all under **one global passphrase**.
The `pubkey` is stored beside the ciphertext so `list_user_keys` and the
@@ -750,10 +844,23 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
writing, so a typo cannot quietly create a second passphrase that opens only
the new key. `change_passphrase` needs only the *new* one (we hold the keys)
and re-encrypts every entry. `rename`/`forget` need no passphrase at all.
**The unlocked vault is the authorisation (L3):** both `change_passphrase` and
`export_user_key_encrypted` refuse a locked vault and require no re-entry of the
current passphrase while it is open. That is deliberate — the control is the
unlock plus the auto-lock timeout, not a second prompt — and is an accepted
tradeoff recorded from the review, not an oversight.
- **Auto-lock is a hard timeout since the unlock** (`lock-timeout`, default
900 s, 0 = never), checked by a 30 s `glib` timer in `state.rs`, plus "Lock
now". It is deliberately **not** an idle timer that request traffic resets — a
chatty client would hold the vault open forever. Headless never auto-locks
chatty client would hold the vault open forever. The elapsed time is measured
with **`CLOCK_BOOTTIME`** (`store::keys::boottime`), not `Instant`, because
`CLOCK_MONOTONIC` stops while the machine is suspended — a laptop that slept
through the timeout must still lock on resume. `boottime` is the **one `unsafe`
call in the tree** (a `libc::clock_gettime`). The vault also locks immediately
on **suspend** (`org.freedesktop.login1` `PrepareForSleep` on the system bus)
and on the **screen locking** (`org.gnome.ScreenSaver.ActiveChanged` on the
session bus) — both best-effort, since a machine without logind or a screen
saver just keeps the timer. Headless never auto-locks
(there is nobody to re-prompt). Dropping the cache triggers rust-nostr's
`non_secure_erase`, a best-effort volatile overwrite with **no contract**; the
docs must not pretend it is a guarantee.
@@ -781,10 +888,19 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
identities window's add/import dialogs carry the passphrase field
(with a confirmation only when that call *sets* the passphrase). Export needs
the vault open first (`with_unlocked`).
- **Export and import hygiene (L2).** The export password is always confirmed
and at least 8 characters (`PassphraseFields::export`; the pure
`validate_passphrase` is unit-tested), so an accidental empty submit cannot
encrypt a key under `""`. The import key field is an `AdwPasswordEntryRow`
(masked), so a pasted `nsec` is not shown in cleartext. `plain::copy_secret`
copies an exported `ncryptsec` or a `bunker://` string and clears the
clipboard again after 60 s **if it still holds that value**.
- **Never log, print or put the passphrase in argv/env.** The passphrase is
`Zeroizing` where it crosses the vault and the headless path, and is dropped as
soon as the unlock lands; the GTK dialog fields hand it over as a plain
`String`, so this is hygiene, not a blanket guarantee. Verified: on drop,
soon as the unlock lands. The GTK dialogs now **clear their entry rows** on
every response and wrap the extracted passphrase / pasted `nsec` in
`Zeroizing` before the async call (L5) — still hygiene, not a blanket
guarantee. Verified: on drop,
`nostr::SecretKey` calls secp256k1's `non_secure_erase()`, a volatile overwrite
— *not* a guarantee (copies can survive in registers or on the stack, and there
is no `ZeroizeOnDrop` contract). Treat in-memory exposure as a real risk.
@@ -822,13 +938,24 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
reintroduce "no icon file ⇒ fetch": `changes` fires on every answered request,
so that is an unbounded background loop and a multiplied presence leak.
- **Hardening (all of it mandatory).** `https` only (plus inline
`data:image/*;base64`, which never leaves the process); resolve with
`tokio::net::lookup_host` and refuse any non-public address (loopback, private,
link-local, CGNAT `100.64/10`, `192.0.0/24`, `198.18/15`, reserved, multicast,
IPv6 ULA `fc00::/7`, `::1`, mapped-v4) — fail closed on a mixed answer; pin the
`data:image/*;base64`, which never leaves the process, bounded by a length
check **before** base64 decoding so a hostile payload cannot allocate past the
cap — L7); resolve with
`tokio::net::lookup_host` and refuse any non-public address — IPv4 rejects
loopback, private, link-local, CGNAT `100.64/10`, `0.0.0.0/8`, `192.0.0/24`,
`198.18/15`, reserved and multicast; IPv6 is **allow-listed** to global unicast
`2000::/3` minus `2001::/23`, `2001:db8::/32`, `2002::/16` and `3fff::/20`
(which also refuses IPv4-compatible `::/96`, IPv4-translated, NAT64
`64:ff9b::/96`, ULA `fc00::/7`, link-local and discard ranges; IPv4-mapped
`::ffff:0:0/96` is judged as its embedded v4) — fail closed on a mixed answer; pin the
validated addresses; follow ≤3 redirects manually, re-validating and re-pinning
each `Location` (a scheme downgrade or a private address dies at the hop);
`timeout(5s)`, `connect_timeout(3s)`, no cookies/auth/proxy; stream the body
`timeout(5s)`, `connect_timeout(3s)`, no cookies/auth/proxy — **`.no_proxy()`
is mandatory**: without it an `HTTPS_PROXY`/`ALL_PROXY` would override the
pinned addresses and could reach internal hosts, at the cost that a host behind
a mandatory corporate proxy cannot serve icons or NIP-05 (fail-soft: initials /
unverified address). URLs with embedded userinfo are refused on every hop (a
`Location:` can carry it). Stream the body
with a **1 MiB cap**. The format gate is **magic bytes**, not `Content-Type`:
png/jpeg/gif/webp only, SVG and every other vector rejected **before** decode (a
sub-KiB SVG can allocate GBs, so the byte cap alone is not enough); a ≤4096²
@@ -838,13 +965,23 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
`Send`). A cached `.img` may be decoded synchronously on the first paint
(`AppState::hydrate_icon`), bounded by the byte cap; `IconStore` memoises the
sidecar URL and the one-shot hydration so the per-ping path does no disk I/O.
- **Image dimensions are read before decoding.** `sniff_dimensions` parses the
container header (PNG IHDR / GIF screen / JPEG SOF / WebP VP8/VP8L/VP8X) and
anything over `MAX_ICON_DIMENSION` (1024², since icons render at 32 px) is
refused **before** `gdk::Texture::from_bytes` — a sub-1 MiB PNG can describe a
30,000² canvas, and the decode would allocate the full RGBA before any
post-decode check could run. A header that cannot be parsed is refused (fail
closed).
- **No fetch before consent — now a preference, not a rule.** For an
already-approved app the dialog shows the cached icon. For a first pairing it
shows the client's declared icon too, but **only when `load-app-icons` is on**,
fetched through `AppState::preview_icon`, which is **memory only**: no disk cache
is written for an unapproved app, so a denial leaves nothing behind. With the
preference off there is no request and the dialog shows the generic avatar and
the shortened npub. (M9's no-client-text *notification* bodies remain strict.)
is written for an unapproved app **and the texture is not put in
`IconStore.textures`** (it is handed only to the dialog's `apply` closure), so a
denial leaves nothing behind and repeated pairing prompts cannot leak textures.
With the preference off there is no request and the dialog shows the generic
avatar and the shortened npub. (M9's no-client-text *notification* bodies remain
strict.)
- **A metadata-less client is labelled by its key.** When an app declares no usable
`name`, the approval dialog and the Apps row show `plain::shorten_npub` and build
the `AdwAvatar` with `show_initials(false)` (libadwaita's generic glyph) — never
@@ -911,6 +1048,17 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
- Event content and client-supplied metadata are attacker-controlled text. Show
them only as **plain labels** (`use_markup(false)`), never as Pango markup — a
client must not be able to forge formatting that looks like Regent's own UI.
Before it is shown **or stored**, client text is also stripped of control
characters and Unicode bidi/directional markers (`U+061C`, `U+200E`, `U+200F`,
`U+202A..=U+202E`, `U+2066..=U+2069`) and bounded, by `crate::sanitize`
(`clean`/`clean_bound`/`clean_opt`). That covers the `connect` metadata
(`client_info`), the `nostrconnect://` fields and `requested_perms`, a user
label (`apps::bound_label`), the **load** paths of `apps.json`,
`profiles.json` (`display_name`) and the activity log (`audit::bound` +
`recent`), and headless stdout (defence in depth at the print site): an ANSI
escape in a name is a terminal escape in `--pair` output, and a bidi override
makes an app name read as another. An empty-after-cleaning value counts as
absent.
They are deliberately **not** `selectable`: a selectable `GtkLabel` selects its
whole text the moment it takes focus, and a dialog focuses its first focusable
widget on open, so the first value would open with a selection highlight behind
@@ -1148,6 +1296,18 @@ the UI is tested. `build-aux/deploy-dev.sh` runs on the build host,
## Testing
- **CI** (`.gitea/workflows/ci.yaml`, Gitea Actions) runs `cargo test --locked`,
`cargo clippy --all-targets --locked -- -D warnings` and `cargo deny check`
(`deny.toml`). The job runs on the **`regent-ci` runner**, whose label maps to
the image built from `build-aux/ci/Dockerfile` (`build-aux/ci/build-image.sh`
builds and pushes it to the Gitea registry), so the workflow installs nothing.
The image is **Arch-based** because Regent's `v4_24`/`v1_10` crate features
want GTK ≥ 4.23 / libadwaita ≥ 1.10 — newer than the latest stable GNOME
release (GNOME 50 ships GTK 4.22), so the old `ubuntu-latest` job and the GNOME
OS SDK both fail the build. The toolchain is pinned **in the image** (1.99.1)
because the `-D warnings` gate is calibrated to a compiler, and `cargo-deny`
fetches the advisory database at run time. Clippy is **clean** at the pinned
version — keep it that way.
- Against a real relay — the path that actually matters, and the only one that
exposes the two subscription traps above:
```sh
Generated
+7 -4
View File
@@ -701,9 +701,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
@@ -2016,12 +2016,15 @@ dependencies = [
"image",
"ksni",
"libadwaita",
"libc",
"nostr",
"nostr-sdk",
"qrcode",
"reqwest",
"serde",
"serde_json",
"subtle",
"tempfile",
"tokio",
"url",
"zeroize",
@@ -2808,9 +2811,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
version = "2.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
dependencies = [
"form_urlencoded",
"idna",
+10 -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.
@@ -36,6 +36,15 @@ 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`.
libc = "0.2"
# Unique, mode-0600 temp files for the atomic vault write, so concurrent saves
# cannot collide on a fixed `keys.json.tmp` path (M9).
tempfile = "3"
qrcode = { version = "0.14", features = ["image"] }
image = { version = "0.25", default-features = false, features = ["png"] }
+48 -4
View File
@@ -29,7 +29,7 @@ export HOME=$TMP_HOME
export CARGO_HOME=${CARGO_HOME:-$ORIGINAL_HOME/.cargo}
cleanup() {
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} ${BACKGROUND:-} 2>/dev/null
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} ${BACKGROUND:-} ${LOCK_HOLDER:-} 2>/dev/null
wait 2>/dev/null
rm -rf "$TMP_HOME"
}
@@ -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",
@@ -367,6 +368,49 @@ kill "$HEADLESS" "$SUBSCRIBER" 2>/dev/null
HEADLESS=
SUBSCRIBER=
printf '\n== the single-instance lock ==\n'
# A headless run holds the lock, so no second Regent — headless or GUI — may run
# on the same device key. This is the M4 fix: the lock is taken unconditionally,
# not only when there is no session bus.
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_PROFILE_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --headless --passphrase-file "$PASSPHRASE_FILE" \
>"$TMP_HOME/lock-holder.log" 2>&1 &
LOCK_HOLDER=$!
sleep 5
grep -q 'signer listening' "$TMP_HOME/lock-holder.log"
check $? "the lock-holding headless instance is running"
LOCKFILE="$TMP_HOME/.local/share/$DATA_DIR/regent.lock"
[ -f "$LOCKFILE" ] && [ "$(stat -c '%a' "$LOCKFILE")" = 600 ]
check $? "regent.lock exists and is mode 0600"
# A second headless run must refuse and exit non-zero.
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
"$ROOT/$BUILD/regent" --headless --passphrase-file "$PASSPHRASE_FILE" \
>"$TMP_HOME/lock-second.log" 2>&1
[ $? -ne 0 ]
check $? "a second headless run exits non-zero"
grep -q 'already running' "$TMP_HOME/lock-second.log"
check $? "a second headless run says Regent is already running"
# The GUI must refuse too, and must not build a window or pair.
GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
timeout 8 "$ROOT/$BUILD/regent" >"$TMP_HOME/lock-gui.log" 2>&1
grep -q 'already running' "$TMP_HOME/lock-gui.log"
check $? "the GUI refuses while headless holds the lock"
! grep -q 'opening the main window' "$TMP_HOME/lock-gui.log"
check $? "and the refused GUI did not present a window"
kill "$LOCK_HOLDER" 2>/dev/null
sleep 1
LOCK_HOLDER=
printf '\n== first run: no keys, so no signer ==\n'
# With no keys there is nothing to sign with and nothing to listen for, so the
# identities window is the whole app and the signer never starts. A fresh HOME is
+48
View File
@@ -0,0 +1,48 @@
# Regent's CI image (Gitea Actions). Built and pushed by build-aux/ci/build-image.sh;
# referenced by the `regent-ci` runner label in .gitea/workflows/ci.yaml.
#
# Arch is the AUR target and the closest match to the development environment.
# Regent asks for GTK >= 4.23 / libadwaita >= 1.10 (the crate's `v4_24` / `v1_10`
# features), which is *newer* than the latest stable GNOME release (GNOME 50
# ships GTK 4.22 / libadwaita 1.9), so a rolling base is required — the Gitea
# runner's ubuntu-latest image and the GNOME OS SDK both fail the build.
#
# Everything the job needs is baked in: the workflow installs nothing at run
# time. nodejs is for actions/checkout and actions/cache; ca-certificates and
# curl for the crate registry, the RustSec advisory database `cargo deny` fetches,
# and the toolchain downloads below.
FROM archlinux:base-devel
RUN pacman -Syu --noconfirm --needed \
ca-certificates \
curl \
git \
nodejs \
gtk4 \
libadwaita \
pkgconf \
&& rm -rf /var/cache/pacman/pkg/*
# The `-D warnings` gate is calibrated to a compiler, so the toolchain is pinned
# here rather than installed by an action on every run. Keep this in step with
# the `rust-version` in Cargo.toml and the development machine. rustup is used
# instead of the `rust` package precisely so the compiler cannot drift with the
# rolling base.
ENV PATH=/root/.cargo/bin:$PATH
RUN pacman -S --noconfirm --needed rustup \
&& rustup toolchain install 1.99.1 --profile minimal --component clippy \
&& rustup default 1.99.1
# cargo-deny ships as a static binary. Deliberately *not* the Arch `cargo-deny`
# package: it depends on `cargo`, which pulls in the rolling `rust` package we
# are pinning away from (and conflicts with rustup).
ARG CARGO_DENY_VERSION=0.22.2
RUN cd /tmp \
&& curl -fsSLO "https://github.com/EmbarkStudios/cargo-deny/releases/download/${CARGO_DENY_VERSION}/cargo-deny-${CARGO_DENY_VERSION}-x86_64-unknown-linux-musl.tar.gz" \
&& curl -fsSLO "https://github.com/EmbarkStudios/cargo-deny/releases/download/${CARGO_DENY_VERSION}/cargo-deny-${CARGO_DENY_VERSION}-x86_64-unknown-linux-musl.tar.gz.sha256" \
&& printf '%s cargo-deny-%s-x86_64-unknown-linux-musl.tar.gz\n' \
"$(cat "cargo-deny-${CARGO_DENY_VERSION}-x86_64-unknown-linux-musl.tar.gz.sha256")" \
"${CARGO_DENY_VERSION}" | sha256sum -c - \
&& tar -xzf "cargo-deny-${CARGO_DENY_VERSION}-x86_64-unknown-linux-musl.tar.gz" \
&& install -m755 "cargo-deny-${CARGO_DENY_VERSION}-x86_64-unknown-linux-musl/cargo-deny" /usr/local/bin/ \
&& rm -rf /tmp/cargo-deny-*
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Build and push Regent's CI image (see build-aux/ci/Dockerfile).
#
# Runs on the build host, which needs Docker and write access to the registry:
#
# docker login gitea.kosmos.org
# build-aux/ci/build-image.sh # builds and pushes :latest
# build-aux/ci/build-image.sh 2026-11-30 # a dated tag
#
# The image has to be pullable by the `regent-ci` runner, which is registered
# with the label `regent-ci:docker://gitea.kosmos.org/raucao/regent-ci:latest`.
# A label-based runner cannot pass pull credentials, so keep the package public
# (link it to the public raucao/regent repository) — see doc/dev/development.md.
#
# Set NO_PUSH=1 to build only, e.g. to try the Dockerfile locally.
set -eu
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
image=${REGENT_CI_IMAGE:-gitea.kosmos.org/raucao/regent-ci}
tag=${1:-latest}
docker build -t "$image:$tag" "$ROOT/build-aux/ci"
if [ "${NO_PUSH:-}" = 1 ]; then
echo "build-image: built $image:$tag (not pushed)"
exit 0
fi
docker push "$image:$tag"
echo "build-image: pushed $image:$tag"
+1 -1
View File
@@ -19,7 +19,7 @@
<key name="load-app-icons" type="b">
<default>true</default>
<summary>Load application icons</summary>
<description>Fetch and show the icon an application declares in its pairing metadata, from the application's own server, after you approve it. Turning this off stops all icon fetches and leaves the initials in place.</description>
<description>Fetch and show the icon an application declares in its pairing metadata, from the application's own server. While this is on, the icon is also fetched during pairing, before you approve the application, so the dialog can show it. Turning this off stops all icon fetches and leaves the initials in place.</description>
</key>
<key name="close-action" type="s">
<default>'ask'</default>
+40
View File
@@ -0,0 +1,40 @@
[graph]
# Check the dependency graph as the release build sees it.
all-features = false
[advisories]
version = 2
# Add an id here only with a comment explaining why it cannot be fixed.
ignore = []
[licenses]
version = 2
# Our own crate is `publish = false` (Unlicense); the allow-list gates the
# dependency tree, so keep it to permissive licenses that cover it.
allow = [
"0BSD",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"BSL-1.0",
"CC0-1.0",
"CDLA-Permissive-2.0",
"ISC",
"MIT",
"MIT-0",
"MPL-2.0",
"OpenSSL",
"Unicode-3.0",
"Unicode-DFS-2016",
"Unlicense",
"Zlib",
]
confidence-threshold = 0.9
[bans]
multiple-versions = "warn"
[sources]
unknown-registry = "deny"
unknown-git = "deny"
+47
View File
@@ -89,6 +89,53 @@ HOME, using `gtk4-broadwayd` and `nak`:
dbus-run-session -- build-aux/acceptance.sh
```
## Continuous integration
Gitea Actions runs `cargo test --locked`,
`cargo clippy --all-targets --locked -- -D warnings` and `cargo deny check` on
every push and pull request (`.gitea/workflows/ci.yaml`). The job runs on the
`regent-ci` runner, which is registered with the label
```
regent-ci:docker://gitea.kosmos.org/raucao/regent-ci:latest
```
so it executes inside the image built from `build-aux/ci/Dockerfile`. That image
is **Arch-based** and bakes in the GTK/libadwaita development headers, the pinned
Rust toolchain (1.99.1) and `cargo-deny`, so the job installs nothing at run time.
Arch is required because Regent's crate features ask for GTK ≥ 4.23 /
libadwaita ≥ 1.10, which is newer than the latest stable GNOME release.
Rebuild and push it from the build host after changing the Dockerfile or the
pinned toolchain:
```sh
docker login gitea.kosmos.org
build-aux/ci/build-image.sh
```
The package must stay public (linked to `raucao/regent`): a label-based runner
cannot pass pull credentials. `NO_PUSH=1 build-aux/ci/build-image.sh` builds
without pushing, for trying the Dockerfile locally.
### The runner
The runner is an ordinary Gitea runner registered at repository level with that
one label; it needs Docker and nothing else installed. A few settings in its
`config.yaml` are not defaults, and matter:
- `container.force_pull: true` — the registry's `:latest` stays authoritative
instead of a stale local copy.
- `runner.node_download: false` — use the node baked into the image instead of
downloading one per job.
- `container.network: host` with `cache.host: 127.0.0.1` — the runner's cache
server listens on the host, and a job container on an auto-created bridge
network cannot reach it when a host firewall filters container→host traffic.
The cache step then times out on every run (five retries with backoff — about
a minute wasted) and nothing is ever cached. Host networking puts the job on
`127.0.0.1`, where the cache works: a run with a warm cache is ~50 s, against
~3m 40s without one.
## Validating the package metadata
```sh
+2
View File
@@ -52,9 +52,11 @@ cargo_build = custom_target(binary_name,
'src/application.rs',
'src/config.rs',
'src/headless.rs',
'src/instance.rs',
'src/portal.rs',
'src/runner.rs',
'src/runtime.rs',
'src/sanitize.rs',
'src/signer/approval.rs',
'src/signer/mod.rs',
'src/signer/policy.rs',
+27 -1
View File
@@ -136,14 +136,36 @@ pub fn run(args: &[String], background: bool) -> glib::ExitCode {
}
app.add_action(&focus);
app.connect_startup(|_| load_css());
// The single-instance lock is taken here, in `startup`, which GLib emits
// only for the **primary** instance: a secondary that is forwarding a
// `nostrconnect://` link never runs it, so link forwarding is unaffected.
// `quit()` alone does not stop `activate`/`open` from being emitted, so a
// refused instance also short-circuits both handlers below — otherwise it
// would build a window, flash it, and (on the open path) pair before exiting.
let refused = Rc::new(Cell::new(false));
{
let refused = Rc::clone(&refused);
app.connect_startup(move |app| {
if !crate::instance::claim() {
eprintln!("regent: another Regent is already running");
refused.set(true);
app.quit();
return;
}
load_css();
});
}
{
let windows = Rc::clone(&windows);
let refused = Rc::clone(&refused);
// `--background` (an autostart launch) opens with no window, but only
// for the launch itself: a later activation — the app icon, a
// notification click — is the user asking for the window.
let first = Cell::new(true);
app.connect_activate(move |_| {
if refused.get() {
return;
}
windows.build();
if first.replace(false) && background && windows.has_keys() {
// A `--background` launch is what autostart runs, but it is also
@@ -164,7 +186,11 @@ pub fn run(args: &[String], background: bool) -> glib::ExitCode {
// away — the same approval dialog as pasting a code, over the main window.
{
let windows = Rc::clone(&windows);
let refused = Rc::clone(&refused);
app.connect_open(move |_, files, _hint| {
if refused.get() {
return;
}
windows.build();
windows.present_primary();
for file in files {
+9
View File
@@ -49,6 +49,15 @@ impl Config {
}
}
/// The underlying `gio::Settings`.
///
/// The long-lived caller must own this instance for as long as it needs the
/// `connect_changed` handler it installs: the handler is owned by the
/// GObject and dies with it (see `AppState`).
pub(crate) fn settings(&self) -> &gio::Settings {
&self.settings
}
/// The identity selected in the UI: it scopes the Apps/Activity pages and
/// is the default for new pairings. `None` means "the first stored key".
pub fn current_identity(&self) -> Option<PublicKey> {
+112 -62
View File
@@ -14,6 +14,7 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::AtomicU32;
use std::sync::{Arc, Mutex};
use glib::prelude::ToVariant;
@@ -127,6 +128,12 @@ async fn serve(
Prompt::Approve { reply, .. } => {
let _ = reply.send(Answer::denied()).await;
}
// Headless never sends a pairing prompt (`ask_pairing` is
// GUI-only; `--pair` consents via `pair_client`), but the drain
// fails closed regardless.
Prompt::Pair { reply, .. } => {
let _ = reply.send(Answer::denied()).await;
}
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
@@ -155,7 +162,7 @@ async fn serve(
settings.relays(),
approver,
Arc::clone(&registry),
settings.auto_approve_limit(),
Arc::new(AtomicU32::new(settings.auto_approve_limit())),
activity.clone(),
changes.clone(),
names,
@@ -204,14 +211,17 @@ async fn finish_pairing(
.await
.map_err(|error| format!("pairing failed: {error}"))?;
let name = pairing
.name
.clone()
.unwrap_or_else(|| "an unnamed application".to_string());
// Sanitized again here even though `parse_client_uri` already cleaned them:
// this is the one place a client string reaches a terminal, and defence in
// depth is cheap. An ANSI escape in a name would otherwise run in the shell.
let name = crate::sanitize::clean_bound(
pairing.name.as_deref().unwrap_or("an unnamed application"),
64,
);
let asked = pairing
.requested
.as_deref()
.map(|perms| format!(" — it asked for {perms}"))
.map(|perms| format!(" — it asked for {}", crate::sanitize::clean_bound(perms, 200)))
.unwrap_or_default();
println!(
"regent: paired with {name} ({}){asked}",
@@ -230,18 +240,15 @@ async fn finish_pairing(
/// True if another Regent is already running.
///
/// The GUI owns the app's D-Bus name, so that is the first check. With no
/// session bus at all (a server, an SSH box) the GUI cannot run either, so an
/// exclusive lock on `regent.lock` catches a second **headless** run — which the
/// D-Bus check alone never could. The kernel releases the lock on exit, so it
/// cannot go stale.
/// A GUI owns the app's D-Bus name, so that is the specific first check. But a
/// headless run owns no name, and with no session bus (a server, an SSH box)
/// neither does a GUI — so the real guard is the process-wide lock in
/// [`crate::instance`], taken by both the GUI and headless. It is also what
/// catches a GUI starting beside a headless run, which the D-Bus check never
/// could. The kernel releases the lock on exit, so it cannot go stale.
fn another_instance_running() -> Result<bool, String> {
let Some(connection) = session_bus() else {
return Ok(!claim_lock_file());
};
let reply = connection
.call_sync(
if let Some(connection) = session_bus() {
let reply = connection.call_sync(
Some("org.freedesktop.DBus"),
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
@@ -251,47 +258,21 @@ fn another_instance_running() -> Result<bool, String> {
gtk::gio::DBusCallFlags::NONE,
-1,
gtk::gio::Cancellable::NONE,
)
.map_err(|error| error.to_string())?;
let (owned,): (bool,) = reply.get().ok_or("unexpected NameHasOwner reply")?;
Ok(owned)
);
if let Ok(reply) = reply {
let (owned,): (bool,) = reply.get().ok_or("unexpected NameHasOwner reply")?;
if owned {
return Ok(true);
}
}
}
Ok(!crate::instance::claim())
}
fn session_bus() -> Option<gtk::gio::DBusConnection> {
gtk::gio::bus_get_sync(gtk::gio::BusType::Session, gtk::gio::Cancellable::NONE).ok()
}
/// Hold `regent.lock` for the life of the process. False if another process has
/// it. Failing to create the file is not a reason to refuse to run.
fn claim_lock_file() -> bool {
static LOCK: std::sync::OnceLock<std::fs::File> = std::sync::OnceLock::new();
if LOCK.get().is_some() {
return true;
}
let path = KeyStore::default_path().with_file_name("regent.lock");
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let Ok(file) = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&path)
else {
return true;
};
match file.try_lock() {
Ok(()) => {
let _ = LOCK.set(file);
true
}
Err(std::fs::TryLockError::WouldBlock) => false,
Err(std::fs::TryLockError::Error(_)) => true,
}
}
/// The passphrase for an unattended run: a systemd credential
/// (`$CREDENTIALS_DIRECTORY/regent-passphrase`) first, then `--passphrase-file`.
/// Never argv or the environment, and never logged.
@@ -302,11 +283,25 @@ fn read_passphrase(file: Option<&str>) -> Result<Option<Zeroizing<String>>, Stri
Some(path) if path.exists() => Some(path),
_ => file.map(PathBuf::from),
};
let Some(path) = path else {
return Ok(None);
};
match path {
Some(path) => Ok(Some(read_passphrase_file(&path)?)),
None => Ok(None),
}
}
let metadata = std::fs::metadata(&path)
/// Read a passphrase from `path`, refusing anything but a small, private
/// (mode 0400/0600) regular file.
///
/// The file is opened **once** and every check is made on that descriptor: a
/// `metadata(path)` followed by `read_to_string(path)` is a TOCTOU window. The
/// buffer is zeroized.
fn read_passphrase_file(path: &std::path::Path) -> Result<Zeroizing<String>, String> {
use std::io::Read;
let file = std::fs::File::open(path)
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
let metadata = file
.metadata()
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
if !metadata.is_file() {
return Err(format!(
@@ -324,23 +319,27 @@ fn read_passphrase(file: Option<&str>) -> Result<Option<Zeroizing<String>>, Stri
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
eprintln!(
"regent: warning: {} is readable by other users",
return Err(format!(
"--passphrase-file {}: readable by other users (needs mode 0400 or 0600)",
path.display()
);
));
}
}
let text = std::fs::read_to_string(&path)
let mut bytes = Zeroizing::new(Vec::new());
file.take(4097)
.read_to_end(&mut bytes)
.map_err(|error| format!("--passphrase-file {}: {error}", path.display()))?;
let passphrase = text.trim_end_matches(['\n', '\r']).to_string();
let text = std::str::from_utf8(&bytes)
.map_err(|_| format!("--passphrase-file {}: not valid UTF-8", path.display()))?;
let passphrase = Zeroizing::new(text.trim_end_matches(['\n', '\r']).to_string());
if passphrase.is_empty() {
return Err(format!(
"--passphrase-file {}: the passphrase is empty",
path.display()
));
}
Ok(Some(Zeroizing::new(passphrase)))
Ok(passphrase)
}
async fn wait_for_shutdown() {
@@ -358,3 +357,54 @@ async fn wait_for_shutdown() {
_ = terminate.recv() => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch_path() -> PathBuf {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
std::env::temp_dir().join(format!(
"regent-passphrase-{}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
))
}
#[cfg(unix)]
fn write_with_mode(path: &std::path::Path, contents: &[u8], mode: u32) {
use std::os::unix::fs::PermissionsExt;
std::fs::write(path, contents).unwrap();
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
}
/// A passphrase file that other users can read is refused, not warned about.
#[cfg(unix)]
#[test]
fn a_world_readable_passphrase_file_is_refused() {
let path = scratch_path();
write_with_mode(&path, b"hunter2", 0o644);
let error = read_passphrase_file(&path).expect_err("must refuse");
assert!(error.contains("readable by other users"), "got: {error}");
let _ = std::fs::remove_file(&path);
}
#[cfg(unix)]
#[test]
fn a_private_passphrase_file_is_read_and_trimmed() {
let path = scratch_path();
write_with_mode(&path, b"hunter2\n", 0o600);
assert_eq!(read_passphrase_file(&path).unwrap().as_str(), "hunter2");
let _ = std::fs::remove_file(&path);
}
#[cfg(unix)]
#[test]
fn an_oversized_passphrase_file_is_refused() {
let path = scratch_path();
write_with_mode(&path, &vec![b'a'; 4097], 0o600);
let error = read_passphrase_file(&path).expect_err("must refuse");
assert!(error.contains("too large"), "got: {error}");
let _ = std::fs::remove_file(&path);
}
}
+90
View File
@@ -0,0 +1,90 @@
//! The single-instance lock.
//!
//! Two Regents on one device key would both answer requests and race on
//! `apps.json`/`keys.json`, so exactly one process may run — GUI or headless.
//! The app's D-Bus name catches a second **GUI**, but a headless run owns no
//! name, and on a machine with no session bus neither check works at all. An
//! exclusive `flock` on `regent.lock` is the one mechanism that covers every
//! combination, so both the GUI and headless take it. The kernel drops the lock
//! when the process exits, so it cannot go stale.
use std::fs::File;
use std::path::Path;
use std::sync::OnceLock;
use crate::store::keys::KeyStore;
/// The held lock file, kept for the life of the process. `flock` conflicts
/// across two descriptors even within one process, so re-claiming has to be a
/// memo, not a second open.
static LOCK: OnceLock<File> = OnceLock::new();
/// Take the process-wide single-instance lock.
///
/// `true` when this process now holds it — including a repeat call in the same
/// process. **Fails closed:** a lock file that cannot be created or locked
/// returns `false`, so an unreadable data directory refuses to run rather than
/// running unlocked; `WouldBlock` (another process holds it) is the ordinary
/// `false`.
pub fn claim() -> bool {
if LOCK.get().is_some() {
return true;
}
let path = KeyStore::default_path().with_file_name("regent.lock");
match claim_at(&path) {
Ok(file) => {
let _ = LOCK.set(file);
true
}
Err(_) => false,
}
}
/// Open `path` (creating it and its directory, mode 0600) and take an exclusive,
/// non-blocking lock on it. The returned `File` **holds** the lock until it is
/// dropped; the caller keeps it for the life of the process.
fn claim_at(path: &Path) -> std::io::Result<File> {
if let Some(parent) = path.parent() {
// The claim runs before the vault is opened, so on a fresh machine the
// data directory may not exist yet.
crate::store::create_private_dir(parent)?;
}
let mut options = std::fs::OpenOptions::new();
options.create(true).write(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = options.open(path)?;
file.try_lock()?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
/// A second, independent open of the same lock file is refused while the
/// first is held, and succeeds again once it is dropped. Tested on a temp
/// path so it never touches (or races with) the real data directory.
#[test]
fn a_second_lock_on_the_same_file_is_refused() {
let dir = std::env::temp_dir().join(format!("regent-lock-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let path = dir.join("regent.lock");
let held = claim_at(&path).expect("the first claim succeeds");
assert!(
claim_at(&path).is_err(),
"a second claim must be refused while the first is held"
);
drop(held);
assert!(claim_at(&path).is_ok(), "the lock is free again once dropped");
let _ = std::fs::remove_dir_all(&dir);
}
}
+111 -5
View File
@@ -6,9 +6,11 @@
mod application;
mod config;
mod headless;
mod instance;
mod portal;
mod runner;
mod runtime;
mod sanitize;
mod signer;
mod state;
mod store;
@@ -45,13 +47,15 @@ Options:
--headless run the signer with no window; anything not already allowed
with \"Allow always\" is denied, so pre-approve in the GUI first
--pair <uri> pair with a client from its nostrconnect:// URI, then run
headless
headless; `--pair -` reads the URI from stdin (so the pairing
secret need not appear in argv or shell history)
--key <key> identity (npub or hex) that --pair binds the client to; the
current identity is used when omitted
--background start with no window, running in the background (used for
autostart); the tray or a second launch brings the window up
--passphrase-file <path>
read the key-vault passphrase from this file (mode 0400/0600)
read the key-vault passphrase from this file (a small regular
file, mode 0400/0600; refused if group/other can read it)
so an unattended run can sign; a systemd credential named
regent-passphrase is used instead when present
--version, -V print the version and exit
@@ -81,8 +85,18 @@ fn main() -> glib::ExitCode {
}
};
if parsed.headless || parsed.pair.is_some() || parsed.key.is_some() {
return headless::run(parsed.pair, parsed.key, parsed.passphrase_file);
// `--pair -` reads the URI from stdin, so the pairing secret need not appear
// in argv or shell history.
let pair = match resolve_pairing_argument(parsed.pair, std::io::stdin().lock()) {
Ok(pair) => pair,
Err(error) => {
eprintln!("regent: {error}");
return glib::ExitCode::FAILURE;
}
};
if parsed.headless || pair.is_some() || parsed.key.is_some() {
return headless::run(pair, parsed.key, parsed.passphrase_file);
}
register_resources();
@@ -122,7 +136,21 @@ fn parse_args(args: &[String]) -> Result<Args, String> {
match arg.as_str() {
"--headless" => parsed.headless = true,
"--background" => parsed.background = true,
"--pair" => parsed.pair = Some(value_for(&mut iter, "--pair", "a nostrconnect:// URI")?),
"--pair" => {
// `-` means "read the URI from stdin" and is the one literal
// value that starts with `-`; `value_for` would reject it.
let value = iter
.next()
.ok_or("--pair needs a nostrconnect:// URI, or - for stdin")?
.clone();
if value != "-" && value.starts_with('-') {
return Err(
"--pair needs a nostrconnect:// URI, or - for stdin, not a flag"
.to_string(),
);
}
parsed.pair = Some(value);
}
"--key" => parsed.key = Some(value_for(&mut iter, "--key", "an npub or hex key")?),
"--passphrase-file" => {
parsed.passphrase_file =
@@ -148,6 +176,32 @@ fn parse_args(args: &[String]) -> Result<Args, String> {
Ok(parsed)
}
/// Resolve the `--pair` argument.
///
/// `-` reads one line from `reader` (stdin): the pairing URI embeds the pairing
/// secret, so it need not appear in `argv` or shell history. Anything else is
/// the URI as given. Pure so it is testable.
fn resolve_pairing_argument(
arg: Option<String>,
mut reader: impl std::io::BufRead,
) -> Result<Option<String>, String> {
match arg {
None => Ok(None),
Some(value) if value == "-" => {
let mut line = String::new();
reader
.read_line(&mut line)
.map_err(|error| format!("reading the pairing URI from stdin: {error}"))?;
let uri = line.trim().to_string();
if uri.is_empty() {
return Err("no pairing URI was given on stdin".to_string());
}
Ok(Some(uri))
}
Some(value) => Ok(Some(value)),
}
}
/// The value after a flag, rejecting a following flag so `--pair --headless`
/// fails loudly instead of pairing with the literal string `--headless`.
fn value_for(
@@ -216,3 +270,55 @@ fn register_resources() {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `--pair -` is accepted as the literal value, while a following flag is
/// still rejected (I1).
#[test]
fn parse_args_accepts_a_pair_dash_and_keeps_flags_strict() {
let dash = vec!["--pair".to_string(), "-".to_string()];
assert_eq!(parse_args(&dash).unwrap().pair.as_deref(), Some("-"));
// The `--pair=-` spelling also works.
let equals = vec!["--pair=-".to_string()];
assert_eq!(parse_args(&equals).unwrap().pair.as_deref(), Some("-"));
assert!(parse_args(&["--pair".to_string()]).is_err(), "needs a value");
assert!(
parse_args(&["--pair".to_string(), "--headless".to_string()]).is_err(),
"--pair must not take a flag"
);
}
/// `-` reads one line from the reader; empty input is an error, and a normal
/// value passes through.
#[test]
fn a_pair_dash_reads_the_uri_from_stdin() {
let uri = resolve_pairing_argument(
Some("-".to_string()),
std::io::Cursor::new(b"nostrconnect://abc\n".to_vec()),
)
.unwrap();
assert_eq!(uri.as_deref(), Some("nostrconnect://abc"));
assert!(
resolve_pairing_argument(Some("-".to_string()), std::io::Cursor::new(Vec::<u8>::new()))
.is_err(),
"empty stdin is an error"
);
let normal = resolve_pairing_argument(
Some("nostrconnect://x".to_string()),
std::io::Cursor::new(Vec::<u8>::new()),
)
.unwrap();
assert_eq!(normal.as_deref(), Some("nostrconnect://x"));
assert_eq!(
resolve_pairing_argument(None, std::io::Cursor::new(Vec::<u8>::new())).unwrap(),
None
);
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ fn request(autostart: bool, commandline: Vec<String>) -> Result<(), String> {
)
.map_err(|error| error.to_string())?;
let _: (String,) = reply
let _: (glib::variant::ObjectPath,) = reply
.get()
.ok_or("the portal returned an unexpected reply")?;
Ok(())
+14 -3
View File
@@ -32,6 +32,9 @@ pub enum Status {
type Listener = Rc<dyn Fn()>;
/// The callback `start` runs once the signer is up (or failed to start).
type StartedCallback = Box<dyn FnOnce(Result<Arc<Signer>, String>)>;
pub struct SignerRunner {
state: Rc<AppState>,
/// The main window: the drain presents it for a prompt and hides it again
@@ -127,11 +130,17 @@ 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,
}
}
/// The approval queue, so a user-initiated pairing can go through the same
/// serialized drain as responder prompts (L4).
pub fn approver(&self) -> Approver {
self.approver.clone()
}
/// Register a callback for lifecycle changes. It runs immediately, so the
/// caller does not need a separate initial refresh.
pub fn listen(self: &Rc<Self>, listener: impl Fn() + 'static) {
@@ -152,7 +161,7 @@ impl SignerRunner {
pub fn start(
self: &Rc<Self>,
extra: Vec<String>,
after: Option<Box<dyn FnOnce(Result<Arc<Signer>, String>)>>,
after: Option<StartedCallback>,
) {
// No key, no responder: starting one would leave the approval drain
// parented to a hidden window. The key listener and the toggle both
@@ -180,7 +189,9 @@ impl SignerRunner {
let settings = Config::new();
let relays = settings.relays();
let auto_approve_limit = settings.auto_approve_limit();
// A live handle: the signer enforces the auto-approval limit from this
// `Arc`, so a change in Preferences applies without a restart.
let auto_approve_limit = self.state.auto_approve_limit();
// Only `Send` handles go into the async task; the runner and its widget
// stay on the main thread.
+82
View File
@@ -0,0 +1,82 @@
//! Stripping and bounding attacker-controlled text.
//!
//! Event content and client metadata are supplied by an application we do not
//! trust. They are already rendered as plain text — never Pango markup — but two
//! other tricks survive that:
//!
//! - **Control characters.** A `\x1b[2J` in a client name is an ANSI escape in
//! the terminal (`regent --pair` prints it to stdout), and a newline forges a
//! second line in a log or a dialog.
//! - **Unicode bidi overrides.** `U+202E` and friends reorder a rendered label,
//! so a declared app name can *look* like a different app or a trusted path.
//!
//! This is the one place that decides what "clean" means; every client string
//! that reaches a dialog, `apps.json`, the activity log or stdout goes through
//! it. Empty-after-cleaning counts as absent at the call sites.
/// Remove control characters and Unicode bidi/directional formatting
/// characters, then trim.
///
/// `char::is_control` covers C0/C1 (`\n`, `\r`, `\t`, `\x1b`, …); the explicit
/// set is the bidi controls and directional marks it does not.
pub fn clean(value: &str) -> String {
value
.chars()
.filter(|c| !c.is_control() && !is_bidi(*c))
.collect::<String>()
.trim()
.to_string()
}
/// [`clean`], then cap to at most `limit` characters.
pub fn clean_bound(value: &str, limit: usize) -> String {
clean(value).chars().take(limit).collect()
}
/// [`clean_bound`] for an optional field: `None`, or the cleaned value when it
/// is non-empty afterwards. An all-control value counts as absent.
pub fn clean_opt(value: Option<String>, limit: usize) -> Option<String> {
value
.map(|value| clean_bound(&value, limit))
.filter(|value| !value.is_empty())
}
/// Whether a character reorders or overrides text direction.
fn is_bidi(c: char) -> bool {
matches!(
c,
'\u{061C}' // Arabic letter mark
| '\u{200E}' // left-to-right mark
| '\u{200F}' // right-to-left mark
| '\u{202A}'..='\u{202E}' // embeddings / overrides / pop
| '\u{2066}'..='\u{2069}' // isolates
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn control_and_bidi_characters_are_stripped() {
assert_eq!(clean("a\nb\tc"), "abc");
assert_eq!(clean("\u{1b}[2Jclear"), "[2Jclear", "the escape byte goes");
assert_eq!(clean("safe\u{202E}name"), "safename", "the override goes");
assert_eq!(clean("iso\u{2066}late"), "isolate");
assert_eq!(clean("mark\u{200F}"), "mark");
// Trimming is part of cleaning.
assert_eq!(clean(" spaced "), "spaced");
// Ordinary non-ASCII is kept.
assert_eq!(clean("café ☕"), "café ☕");
}
#[test]
fn clean_bound_bounds_after_cleaning() {
let hostile = format!("{}\n{}", "n".repeat(10_000), "evil");
let cleaned = clean_bound(&hostile, 64);
assert_eq!(cleaned.chars().count(), 64);
assert!(!cleaned.contains('\n'));
// The bound applies to the cleaned text, not the input.
assert_eq!(clean_bound("a\u{202E}b\u{202E}c", 2), "ab");
}
}
+108 -5
View File
@@ -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 {
@@ -70,15 +74,29 @@ pub enum Request {
/// show it in full; it is **not** reduced to a short preview, because
/// the original bytes are what gets signed.
content: String,
/// Total characters in the full content, so the UI can disclose a cut
/// against the bound the responder applied.
content_chars: usize,
/// The event's tags, in order, for the Tags group below the content.
/// Empty when the event has none.
tags: Vec<TagView>,
/// Tags dropped by the display cap, and tag values dropped by the field
/// cap or the strict parser. Shown so nothing signed is hidden silently.
tags_omitted: usize,
tag_fields_omitted: usize,
/// The client-requested NIP-01 `created_at`. Displayed, because a
/// replaceable event with a far-future timestamp is a real hazard.
created_at: Timestamp,
},
/// A message would be encrypted to someone.
Encrypt {
method: &'static str,
peer: String,
preview: String,
/// The full plaintext, bounded by the responder's content limit and shown
/// in a scrollable view (not a short preview that could hide payload).
message: String,
/// Total characters in the full plaintext, for the same disclosure.
message_chars: usize,
},
/// A message would be decrypted from someone.
Decrypt {
@@ -163,6 +181,15 @@ pub enum Prompt {
/// backstop, leaving the dialog with buttons that no longer do anything.
deadline: Instant,
},
/// A **user-initiated** pairing question (`nostrconnect://` paste or link).
///
/// Sent through the same queue as every other prompt, so a pairing dialog
/// can never stack over a request prompt (L4). No deadline: the user opened
/// it deliberately, so they may take their time.
Pair {
question: Question,
reply: Sender<Answer>,
},
/// Open the vault. `true` means it is now unlocked.
Unlock {
reply: Sender<bool>,
@@ -219,6 +246,24 @@ impl Approver {
self.ask_within(ASK_TIMEOUT, ASK_BACKSTOP, question).await
}
/// Ask a **user-initiated** pairing question, serialized with every other
/// prompt.
///
/// No timeout: the user pasted the code or opened the link themselves, so
/// they may take their time. A missing UI still denies.
pub async fn ask_pairing(&self, question: Question) -> Answer {
let (reply, answer) = bounded(1);
if self
.inbox
.send(Prompt::Pair { question, reply })
.await
.is_err()
{
return Answer::denied();
}
answer.recv().await.unwrap_or_else(|_| Answer::denied())
}
/// The same, with explicit deadlines so tests can exercise both without
/// waiting a minute: `deadline` is what the UI is told, `within` is this
/// side's own backstop. Both are anchored **now**, so a prompt that waits in
@@ -314,7 +359,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());
@@ -327,7 +375,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();
@@ -342,6 +390,61 @@ mod tests {
assert!(ASK_BACKSTOP > ASK_TIMEOUT);
}
/// A pairing prompt goes through the same queue as a request prompt, so the
/// two are serialized (L4); with no UI at all it denies.
#[tokio::test]
async fn a_pairing_prompt_shares_the_queue_and_a_gone_queue_denies() {
let (approver, prompts, _notices) = Approver::new();
let drain = tokio::spawn(async move {
let mut order = Vec::new();
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
order.push("approve");
let _ = reply.send(Answer::denied()).await;
}
Prompt::Pair { reply, .. } => {
order.push("pair");
let _ = reply.send(Answer::denied()).await;
}
Prompt::Unlock { .. } => {}
}
if order.len() == 2 {
break;
}
}
order
});
// `ask` (a responder request) and `ask_pairing` (user-initiated) share
// the one inbox.
let request = approver.ask(question(Request::Pair {
requested: None,
relays: Vec::new(),
}));
let pairing = approver.ask_pairing(question(Request::Pair {
requested: None,
relays: Vec::new(),
}));
let (first, second) = tokio::join!(request, pairing);
assert_eq!(first, Answer::denied());
assert_eq!(second, Answer::denied());
assert_eq!(drain.await.unwrap(), ["approve", "pair"]);
// With the queue gone, a pairing ask denies.
let (approver, prompts, _notices) = Approver::new();
drop(prompts);
assert_eq!(
approver
.ask_pairing(question(Request::Pair {
requested: None,
relays: Vec::new(),
}))
.await,
Answer::denied()
);
}
/// A prompt can wait in the queue behind another one, so the deadline the
/// UI is handed has to be anchored **when the ask starts**, not when the
/// dialog finally opens: otherwise a queued prompt's dialog would outlive
@@ -355,8 +458,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());
+1269 -152
View File
File diff suppressed because it is too large. Load diff
+33 -3
View File
@@ -8,7 +8,8 @@
//! [`Permission`]: crate::store::apps::Permission
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
/// The window over which auto-approvals are counted.
@@ -17,13 +18,24 @@ pub const WINDOW: Duration = Duration::from_secs(60);
/// Caps how many requests a stored "always" permission answers silently, per
/// application. Past the cap Regent asks again, so a runaway or compromised
/// client turns back into prompts instead of an open tap.
///
/// The limit is a shared [`AtomicU32`], not a stored value, so lowering it in
/// Preferences — to 0, say, to stop a runaway client — applies to the running
/// signer immediately, without a stop/start.
pub struct RateLimiter {
limit: u32,
limit: Arc<AtomicU32>,
recent: Mutex<HashMap<String, VecDeque<Instant>>>,
}
impl RateLimiter {
/// A limiter with a fixed limit. Used by the test configs.
#[cfg(test)]
pub fn new(limit: u32) -> Self {
Self::with_limit(Arc::new(AtomicU32::new(limit)))
}
/// A limiter whose limit is a live view of a shared value.
pub fn with_limit(limit: Arc<AtomicU32>) -> Self {
Self {
limit,
recent: Mutex::new(HashMap::new()),
@@ -34,6 +46,7 @@ impl RateLimiter {
/// [`WINDOW`] is still under the limit. `false` means the request must be
/// put to the user after all.
pub fn claim(&self, app: &str) -> bool {
let limit = self.limit.load(Ordering::Relaxed);
let now = Instant::now();
let mut recent = self.recent.lock().unwrap();
let answers = recent.entry(app.to_string()).or_default();
@@ -43,7 +56,7 @@ impl RateLimiter {
{
answers.pop_front();
}
if answers.len() as u32 >= self.limit {
if answers.len() as u32 >= limit {
return false;
}
answers.push_back(now);
@@ -69,4 +82,21 @@ mod tests {
let limiter = RateLimiter::new(0);
assert!(!limiter.claim("a"));
}
/// The limit is live: lowering it (to 0) must stop silent answers on the
/// next claim, without a restart — that is the whole point of M6.
#[test]
fn the_limit_can_change_while_the_limiter_is_alive() {
let shared = Arc::new(AtomicU32::new(2));
let limiter = RateLimiter::with_limit(Arc::clone(&shared));
assert!(limiter.claim("a"));
assert!(limiter.claim("a"));
assert!(!limiter.claim("a"), "at the cap");
shared.store(0, Ordering::Relaxed);
assert!(!limiter.claim("b"), "zero halts silent answers at once");
shared.store(5, Ordering::Relaxed);
assert!(limiter.claim("b"), "and raising it resumes");
}
}
+150 -8
View File
@@ -6,12 +6,15 @@ use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};
use nostr::nips::nip19::ToBech32;
use nostr::prelude::PublicKey;
use gtk::gdk;
use gtk::gio;
use gtk::gio::prelude::SettingsExt;
use crate::config::Config;
use crate::runtime;
@@ -69,6 +72,16 @@ pub struct AppState {
change_listeners: RefCell<Vec<Listener>>,
/// The responder pings this after it changes the registry or the log.
changes: async_channel::Sender<()>,
/// The suspend and screen-lock hooks that lock the vault. Kept for the
/// process: a `gio::SignalSubscription` unsubscribes when dropped.
sleep_subscriptions: RefCell<Vec<gio::SignalSubscription>>,
/// Preferences, held for the process: the `auto-approve-limit`
/// `connect_changed` handler is owned by its `gio::Settings` instance and
/// dies when that instance is finalized. Never read after construction —
/// the underscore is deliberate.
_config: Config,
/// A live view of `auto-approve-limit`, shared with the running signer.
auto_approve_limit: Arc<AtomicU32>,
}
impl AppState {
@@ -80,11 +93,28 @@ impl AppState {
pub fn new() -> Result<Rc<Self>, KeyError> {
let store = Arc::new(KeyStore::connect()?);
let (changes, changes_rx) = async_channel::bounded(1);
// The auto-approval limit is a live view of the setting: the signer
// shares this `Arc`, so a change — including 0, or one made outside the
// UI — applies immediately. `Config` is held on the state because the
// handler is owned by its `gio::Settings`, which must stay alive.
let config = Config::new();
let auto_approve_limit = Arc::new(AtomicU32::new(config.auto_approve_limit()));
{
let limit = Arc::clone(&auto_approve_limit);
let _ = config
.settings()
.connect_changed(Some("auto-approve-limit"), move |settings, _key| {
let value = settings.int("auto-approve-limit").max(0) as u32;
limit.store(value, Ordering::Relaxed);
});
}
let state = Rc::new(Self {
store,
registry: Arc::new(Mutex::new(AppRegistry::load())),
activity: ActivityLog::new(),
current: Arc::new(Mutex::new(Config::new().current_identity())),
current: Arc::new(Mutex::new(config.current_identity())),
names: Arc::new(Mutex::new(HashMap::new())),
profiles: Profiles::new(),
icons: Rc::new(IconStore::new()),
@@ -93,6 +123,9 @@ impl AppState {
listeners: RefCell::new(Vec::new()),
change_listeners: RefCell::new(Vec::new()),
changes,
sleep_subscriptions: RefCell::new(Vec::new()),
_config: config,
auto_approve_limit,
});
{
@@ -106,6 +139,7 @@ impl AppState {
state.refresh_identities();
state.watch_auto_lock();
state.watch_lock_on_sleep();
Ok(state)
}
@@ -113,7 +147,8 @@ impl AppState {
///
/// A **hard** timeout measured from the unlock, not an idle timer that
/// request traffic resets: otherwise a client that keeps asking would hold
/// the keys open forever.
/// the keys open forever. Measured with [`crate::store::keys::boottime`], so
/// time spent suspended counts — `Instant` would not.
fn watch_auto_lock(self: &Rc<Self>) {
let state = Rc::clone(self);
glib::timeout_add_seconds_local(30, move || {
@@ -122,9 +157,10 @@ impl AppState {
return glib::ControlFlow::Continue;
}
let store = state.store();
let now = crate::store::keys::boottime();
let expired = store
.unlocked_at()
.map(|at| at.elapsed() >= std::time::Duration::from_secs(timeout as u64))
.map(|at| crate::store::keys::lock_expired(at, now, timeout))
.unwrap_or(false);
if expired {
store.lock();
@@ -135,6 +171,57 @@ impl AppState {
});
}
/// Lock the vault the moment the machine suspends or the screen locks.
///
/// The 30 s timer above would catch a long suspend eventually, but the vault
/// should not stay open through one at all. Both hooks are best-effort: a
/// machine without logind, or without a screen saver on the session bus,
/// simply gets no hook and keeps the timer. The subscriptions are stored on
/// the state because a `gio::SignalSubscription` unsubscribes when dropped.
fn watch_lock_on_sleep(self: &Rc<Self>) {
let mut subscriptions = Vec::new();
if let Ok(connection) =
gio::bus_get_sync(gio::BusType::System, gio::Cancellable::NONE)
{
let state = Rc::clone(self);
subscriptions.push(connection.subscribe_to_signal(
Some("org.freedesktop.login1"),
Some("org.freedesktop.login1.Manager"),
Some("PrepareForSleep"),
Some("/org/freedesktop/login1"),
None,
gio::DBusSignalFlags::NONE,
move |signal: gio::DBusSignalRef| {
if signal.parameters.child_value(0).get::<bool>().unwrap_or(false) {
lock_on_sleep(&state, "suspend");
}
},
));
}
if let Ok(connection) =
gio::bus_get_sync(gio::BusType::Session, gio::Cancellable::NONE)
{
let state = Rc::clone(self);
subscriptions.push(connection.subscribe_to_signal(
Some("org.gnome.ScreenSaver"),
Some("org.gnome.ScreenSaver"),
Some("ActiveChanged"),
Some("/org/gnome/ScreenSaver"),
None,
gio::DBusSignalFlags::NONE,
move |signal: gio::DBusSignalRef| {
if signal.parameters.child_value(0).get::<bool>().unwrap_or(false) {
lock_on_sleep(&state, "the screen locking");
}
},
));
}
*self.sleep_subscriptions.borrow_mut() = subscriptions;
}
/// Whether the vault still needs the passphrase.
pub fn is_locked(&self) -> bool {
self.store.is_locked()
@@ -401,11 +488,14 @@ impl AppState {
async move { crate::store::icons::fetch(&fetch_url).await },
move |result| {
icons.end_preview(&key, &url);
if let Ok(bytes) = result {
if let Ok(texture) = crate::store::icons::decode(&bytes) {
icons.set_texture(&key, texture.clone());
apply(texture);
}
if let Ok(bytes) = result
&& let Ok(texture) = crate::store::icons::decode(&bytes)
{
// Deliberately **not** cached: this is a pre-consent
// fetch for an unapproved client, so a denial must leave
// no texture behind (and repeated prompts must not leak
// memory). The texture lives only as long as the dialog.
apply(texture);
}
},
);
@@ -603,6 +693,13 @@ impl AppState {
self.changes.clone()
}
/// The auto-approval limit as a live, shared value. The running signer reads
/// it on every silent answer; a settings change updates it through the
/// `connect_changed` handler installed in `AppState::new`.
pub fn auto_approve_limit(&self) -> Arc<AtomicU32> {
Arc::clone(&self.auto_approve_limit)
}
/// Register a listener for key/store changes. It runs immediately: the
/// vault is already open by the time any view is built.
pub fn listen(&self, listener: impl Fn() + 'static) {
@@ -633,6 +730,16 @@ impl AppState {
}
}
/// Lock the vault because the machine is going away (suspend, screen lock).
fn lock_on_sleep(state: &AppState, reason: &str) {
let store = state.store();
if !store.is_locked() {
store.lock();
eprintln!("regent: the key vault locked on {reason}");
state.notify();
}
}
/// Which identity to keep selected after a refresh.
///
/// Prefer the **live** selection (a pick made while the refresh was in flight),
@@ -728,4 +835,39 @@ mod tests {
"the identity's avatar stays"
);
}
/// The auto-approval limit is a live view of the setting: a change on the
/// `gio::Settings` instance the handler is installed on updates the shared
/// `Arc` synchronously (M6). Skipped when the schema is not installed — a
/// plain `cargo test` without `GSETTINGS_SCHEMA_DIR`, where `Settings::new`
/// aborts rather than erroring.
#[test]
fn the_auto_approval_limit_round_trips_through_the_setting() {
if gio::SettingsSchemaSource::default()
.and_then(|source| source.lookup(crate::APP_ID, true))
.is_none()
{
return;
}
let config = Config::new();
let original = config.auto_approve_limit();
let limit = Arc::new(AtomicU32::new(original));
{
let limit = Arc::clone(&limit);
let _ = config
.settings()
.connect_changed(Some("auto-approve-limit"), move |settings, _key| {
limit.store(
settings.int("auto-approve-limit").max(0) as u32,
Ordering::Relaxed,
);
});
}
let changed = if original == 7 { 8 } else { 7 };
config.set_auto_approve_limit(changed);
assert_eq!(limit.load(Ordering::Relaxed), changed);
// Leave the setting as it was found.
config.set_auto_approve_limit(original);
assert_eq!(limit.load(Ordering::Relaxed), original);
}
}
+47 -4
View File
@@ -86,10 +86,10 @@ impl App {
}
}
/// Trim a user- or client-supplied name and cap it, because it reaches
/// `apps.json`, a dialog and the activity log.
/// Trim and sanitize a user- or client-supplied name and cap it, because it
/// reaches `apps.json`, a dialog and the activity log.
fn bound_label(value: &str) -> Option<String> {
let value: String = value.trim().chars().take(64).collect();
let value = crate::sanitize::clean_bound(value, 64);
(!value.is_empty()).then_some(value)
}
@@ -133,6 +133,7 @@ impl AppRegistry {
Ok(contents) => match serde_json::from_str::<Self>(&contents) {
Ok(mut registry) => {
registry.path = path;
registry.sanitize_metadata();
registry
}
Err(error) => {
@@ -158,7 +159,7 @@ impl AppRegistry {
return Ok(());
}
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
crate::store::create_private_dir(parent)?;
}
let contents = serde_json::to_string_pretty(self)?;
let temporary = self.path.with_extension("json.tmp");
@@ -167,6 +168,20 @@ impl AppRegistry {
Ok(())
}
/// Re-clean the stored client metadata on load.
///
/// `apps.json` is on disk and could be hand-edited, or written by an older
/// build; these are display fields and must not carry control or bidi
/// characters into the UI. Same bounds `approve` applies to what it stores.
fn sanitize_metadata(&mut self) {
for app in &mut self.apps {
app.name = crate::sanitize::clean_opt(app.name.take(), 64);
app.label = crate::sanitize::clean_opt(app.label.take(), 64);
app.url = crate::sanitize::clean_opt(app.url.take(), 256);
app.image = crate::sanitize::clean_opt(app.image.take(), 256);
}
}
pub fn contains(&self, public_key: &PublicKey) -> bool {
let hex = public_key.to_hex();
self.apps.iter().any(|app| app.public_key == hex)
@@ -657,4 +672,32 @@ mod tests {
.all(|app| app.identity == identity.to_hex()));
assert_eq!(registry.list_for(identity).len(), 1);
}
/// `apps.json` is on disk and could be hand-edited or written by an older
/// build: its display fields are cleaned on load (M7).
#[test]
fn hostile_metadata_is_cleaned_when_the_registry_loads() {
let path = temp_path();
let key = Keys::generate().public_key().to_hex();
let json = serde_json::json!({
"apps": [{
"public_key": key,
"name": "bad\u{202E}name".to_string(),
"image": "https://x.example/i\u{1b}.png".to_string(),
"url": format!("{}{}", "u".repeat(500), "url"),
"approved_at": 1,
"identity": key,
"policy": {"methods": [], "kinds": []},
}],
})
.to_string();
std::fs::write(&path, json).expect("write");
let registry = AppRegistry::at(path.clone());
let app = &registry.list()[0];
assert_eq!(app.name.as_deref(), Some("badname"), "bidi stripped");
assert!(!app.image.as_deref().unwrap().contains('\u{1b}'));
assert_eq!(app.url.as_deref().unwrap().chars().count(), 256);
std::fs::remove_file(path).ok();
}
}
+33 -6
View File
@@ -70,10 +70,7 @@ const KEEP_ENTRIES: usize = 500;
const MAX_NAME_CHARS: usize = 64;
fn bound(text: &str) -> String {
text.chars()
.filter(|c| !c.is_control())
.take(MAX_NAME_CHARS)
.collect()
crate::sanitize::clean_bound(text, MAX_NAME_CHARS)
}
/// A handle to the on-disk log.
@@ -109,7 +106,7 @@ impl ActivityLog {
return;
}
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
let _ = crate::store::create_private_dir(parent);
}
if self.size() > MAX_BYTES {
self.trim_unlocked();
@@ -149,7 +146,15 @@ impl ActivityLog {
let mut entries: Vec<Entry> = BufReader::new(file)
.lines()
.map_while(std::result::Result::ok)
.filter_map(|line| serde_json::from_str(&line).ok())
.filter_map(|line| serde_json::from_str::<Entry>(&line).ok())
// Entries written before the name was sanitized — or a hand-edited
// log — must not render control/bidi characters either.
.map(|mut entry| {
if let Some(name) = &entry.name {
entry.name = Some(bound(name));
}
entry
})
.collect();
entries.reverse();
entries.truncate(limit);
@@ -293,6 +298,28 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// A name written before sanitization (or by hand) is cleaned when the log
/// is read, so the Activity view cannot render bidi/control characters.
#[test]
fn a_bidi_name_is_cleaned_when_the_log_is_read() {
let (dir, log) = scratch();
std::fs::create_dir_all(&dir).unwrap();
let line = serde_json::json!({
"at": 1,
"app": "aa",
"name": "evil\u{202E}name".to_string(),
"method": "sign_event",
"kind": 1,
"outcome": "allowed-once",
})
.to_string();
std::fs::write(dir.join("activity.jsonl"), format!("{line}\n")).unwrap();
let entry = &log.recent(1)[0];
assert_eq!(entry.name.as_deref(), Some("evilname"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn clearing_one_identity_keeps_the_others() {
let (dir, log) = scratch();
+261 -17
View File
@@ -5,8 +5,8 @@
//! a bounded body, and raster formats only. A refused or undecodable icon simply
//! falls back to the initials an `AdwAvatar` draws.
//!
//! Cache layout (`glib::user_cache_dir()/<app id>/icons/`, the directory 0700),
//! keyed by the client's public key:
//! Cache layout (`glib::user_cache_dir()/<app id>/icons/`; the directory is
//! created mode 0700, the files are mode 0600), keyed by the client's public key:
//!
//! - `<hex>.img` — the bytes that decoded, mode 0600.
//! - `<hex>.url` — the URL last **attempted** (success *or* failure), mode 0600.
@@ -37,6 +37,11 @@ const MAX_REDIRECTS: usize = 3;
/// Decoded textures larger than this are dropped. A backstop only: the byte cap
/// and the raster allow-list are the real limits.
const MAX_DIMENSION: i32 = 4096;
/// The largest canvas an icon or avatar may declare. Icons render at 32 px, so
/// this is generous — and it is checked from the *header* before decoding, which
/// is what stops a sub-1 MiB file describing a 30,000×30,000 canvas from
/// allocating gigabytes of RGBA on the main thread.
const MAX_ICON_DIMENSION: u32 = 1024;
const TIMEOUT: Duration = Duration::from_secs(5);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
@@ -82,7 +87,7 @@ pub async fn fetch(url: &str) -> Result<Vec<u8>> {
/// Fetch bytes over `https`, hardened: public addresses only (resolved and then
/// pinned into the per-fetch client), ≤3 redirects re-validated and re-pinned at
/// every hop, a bounded body, no cookies/auth/proxy.
/// every hop, a bounded body, no cookies/auth/**proxy**.
///
/// The **only** HTTP fetch path in the app: the icon fetcher and the NIP-05
/// verifier (`store::nip05`) both go through here, so there is one place to
@@ -93,6 +98,12 @@ pub async fn fetch_https(url: &str, expect: Content) -> Result<Vec<u8>> {
if url.scheme() != "https" {
return Err(format!("refusing to fetch a {} URL", url.scheme()));
}
// Reject userinfo on **every** hop: a `Location:` can carry it, and
// reqwest would send it as Basic auth. Checked here, before any DNS or
// network work.
if !url.username().is_empty() || url.password().is_some() {
return Err("refusing a URL with embedded credentials".to_string());
}
let host = url.host_str().ok_or("the URL has no host")?.to_string();
let port = url.port_or_known_default().ok_or("the URL has no port")?;
let addrs = resolve_public(&host, port).await?;
@@ -100,8 +111,13 @@ pub async fn fetch_https(url: &str, expect: Content) -> Result<Vec<u8>> {
// `resolve_to_addrs` is baked in at build time, so the *client* is what
// carries the pin — a shared, process-wide client could not. Building one
// per hop is fine: icon fetches are rare and not latency-sensitive.
//
// `no_proxy` is mandatory: without it an `HTTPS_PROXY`/`ALL_PROXY`
// environment variable would override the pinned addresses and route the
// request through a proxy that can reach internal hosts.
let client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.no_proxy()
.timeout(TIMEOUT)
.connect_timeout(CONNECT_TIMEOUT)
.resolve_to_addrs(&host, &addrs)
@@ -133,10 +149,9 @@ pub async fn fetch_https(url: &str, expect: Content) -> Result<Vec<u8>> {
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
&& !content_type.starts_with("image/")
{
if !content_type.starts_with("image/") {
return Err("the server did not send an image".to_string());
}
return Err("the server did not send an image".to_string());
}
return read_capped(response).await;
@@ -203,6 +218,10 @@ fn is_public_v4(ip: Ipv4Addr) -> bool {
return false;
}
let o = ip.octets();
// 0.0.0.0/8 "this network" — `is_unspecified` only catches 0.0.0.0 itself.
if o[0] == 0 {
return false;
}
// 100.64.0.0/10 carrier-grade NAT.
if o[0] == 100 && (o[1] & 0xc0) == 64 {
return false;
@@ -231,22 +250,37 @@ fn is_public_v6(ip: Ipv6Addr) -> bool {
return false;
}
let segments = ip.segments();
// fc00::/7 unique local.
if (segments[0] & 0xfe00) == 0xfc00 {
let o = ip.octets();
// IPv4-mapped ::ffff:0:0/96 — judge the embedded v4. Evaluated **before** the
// global-unicast allow-list below, which would otherwise reject a
// mapped-public address (a test depends on `::ffff:8.8.8.8` staying public).
if o[..10].iter().all(|byte| *byte == 0) && o[10] == 0xff && o[11] == 0xff {
return is_public_v4(Ipv4Addr::new(o[12], o[13], o[14], o[15]));
}
// Allow only global unicast 2000::/3, then exclude the special ranges inside
// it. Everything else falls outside 2000::/3 and is refused — including
// ::/96 (IPv4-compatible), ::ffff:0:0:0/96 (IPv4-translated), NAT64
// 64:ff9b::/96 and 64:ff9b:1::/48, ULA fc00::/7, link-local fe80::/10,
// discard 100::/64 and site-local fec0::/10.
if (segments[0] & 0xe000) != 0x2000 {
return false;
}
// fe80::/10 link-local.
if (segments[0] & 0xffc0) == 0xfe80 {
// 2001::/23 (IETF protocol assignments / Teredo).
if segments[0] == 0x2001 && (segments[1] & 0xfe00) == 0 {
return false;
}
// 2001:db8::/32 documentation.
if segments[0] == 0x2001 && segments[1] == 0x0db8 {
return false;
}
// IPv4-mapped ::ffff:0:0/96 — judge the embedded v4.
let o = ip.octets();
if o[..10].iter().all(|byte| *byte == 0) && o[10] == 0xff && o[11] == 0xff {
return is_public_v4(Ipv4Addr::new(o[12], o[13], o[14], o[15]));
// 2002::/16 6to4.
if segments[0] == 0x2002 {
return false;
}
// 3ff0::/12 (covers 3fff::/20 and the deprecated 6bone 3ffe::/16) — an
// over-broad but fail-closed refusal of the top of 2000::/3.
if (segments[0] & 0xfff0) == 0x3ff0 {
return false;
}
true
}
@@ -278,6 +312,12 @@ fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
if !meta.contains(";base64") {
return Err("only base64 data URLs are supported".to_string());
}
// Reject an over-sized payload **before** decoding: base64 expands 3 bytes
// to 4, so this bound is exactly the encoded length of `MAX_BYTES` plus
// padding. Decoding first would allocate the whole payload only to reject it.
if payload.len() > ((MAX_BYTES / 3) + 1) * 4 {
return Err("the body is larger than 1 MiB".to_string());
}
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD
.decode(payload)
@@ -289,11 +329,118 @@ fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
Ok(bytes)
}
/// Read an image's pixel dimensions from its container header, **without
/// decoding any pixels**.
///
/// `None` means the header could not be read (truncated, or a variant we do not
/// parse); the caller fails closed. This is the gate that stops a decompression
/// bomb: a small file can describe a huge canvas, and `gdk::Texture::from_bytes`
/// allocates the full uncompressed image before any post-decode check runs.
fn sniff_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.starts_with(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
// IHDR is the first chunk: length(4) "IHDR"(4) width(4) height(4), BE.
let width = u32::from_be_bytes(bytes.get(16..20)?.try_into().ok()?);
let height = u32::from_be_bytes(bytes.get(20..24)?.try_into().ok()?);
return Some((width, height));
}
if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
// Logical screen width/height, little-endian.
let width = u16::from_le_bytes(bytes.get(6..8)?.try_into().ok()?) as u32;
let height = u16::from_le_bytes(bytes.get(8..10)?.try_into().ok()?) as u32;
return Some((width, height));
}
if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
return jpeg_dimensions(bytes);
}
if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
return webp_dimensions(bytes);
}
None
}
/// Walk the JPEG segments to the first Start-Of-Frame marker.
fn jpeg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
let mut i = 2;
while i + 4 <= bytes.len() {
if bytes[i] != 0xff {
i += 1;
continue;
}
let marker = bytes[i + 1];
if marker == 0xff {
// A fill byte.
i += 1;
continue;
}
// Standalone markers carry no length.
if marker == 0x01 || (0xd0..=0xd7).contains(&marker) {
i += 2;
continue;
}
let length = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
// Every SOF variant carries the frame size — excluding DHT (C4),
// JPG (C8) and DAC (CC), which are not SOF.
if (0xc0..=0xcf).contains(&marker) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) {
// FF Cx, length(2), precision(1), height(2), width(2).
let height = u16::from_be_bytes([*bytes.get(i + 5)?, *bytes.get(i + 6)?]) as u32;
let width = u16::from_be_bytes([*bytes.get(i + 7)?, *bytes.get(i + 8)?]) as u32;
return Some((width, height));
}
if length < 2 {
return None;
}
i += 2 + length;
}
None
}
/// Read a WebP canvas size from its first chunk (`VP8 `, `VP8L` or `VP8X`).
fn webp_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
match bytes.get(12..16)? {
b"VP8 " => {
// Lossy: 3-byte frame tag, start code 9d 01 2a, then 14-bit
// width/height, little-endian.
let p = bytes.get(20..30)?;
if p[3..6] != [0x9d, 0x01, 0x2a] {
return None;
}
let width = (u16::from_le_bytes([p[6], p[7]]) & 0x3fff) as u32;
let height = (u16::from_le_bytes([p[8], p[9]]) & 0x3fff) as u32;
Some((width, height))
}
b"VP8L" => {
// Lossless: signature 0x2f, then 14-bit (width-1) and (height-1).
let p = bytes.get(20..25)?;
if p[0] != 0x2f {
return None;
}
let bits = u32::from_le_bytes([p[1], p[2], p[3], p[4]]);
Some(((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1))
}
b"VP8X" => {
// Extended: 4 flag/reserved bytes, then 24-bit (width-1) and
// (height-1), little-endian.
let p = bytes.get(24..30)?;
let width = u32::from_le_bytes([p[0], p[1], p[2], 0]) + 1;
let height = u32::from_le_bytes([p[3], p[4], p[5], 0]) + 1;
Some((width, height))
}
_ => None,
}
}
/// Turn icon bytes into a `GdkTexture`.
///
/// Must run on the main thread (`gdk::Texture` is not `Send`); the caller does
/// this in a `runtime::spawn` `then`, or while painting a cached icon.
pub fn decode(bytes: &[u8]) -> Result<gdk::Texture> {
// Gate on the header first: `from_bytes` allocates the whole uncompressed
// image, so the dimension check has to happen before it, not after.
let (width, height) =
sniff_dimensions(bytes).ok_or("could not read the image dimensions".to_string())?;
if width > MAX_ICON_DIMENSION || height > MAX_ICON_DIMENSION {
return Err(format!("the icon is {width}×{height}, too large to render"));
}
let bytes = glib::Bytes::from(bytes);
let texture = gdk::Texture::from_bytes(&bytes)
.map_err(|error| format!("could not decode the icon: {error}"))?;
@@ -473,7 +620,7 @@ impl IconStore {
let Some(key) = Self::valid_key(key) else {
return;
};
let _ = std::fs::create_dir_all(&self.dir);
let _ = crate::store::create_private_dir(&self.dir);
if write_private(&self.img_path(&key), bytes).is_err() {
return;
}
@@ -487,7 +634,7 @@ impl IconStore {
let Some(key) = Self::valid_key(key) else {
return;
};
let _ = std::fs::create_dir_all(&self.dir);
let _ = crate::store::create_private_dir(&self.dir);
let _ = std::fs::remove_file(self.img_path(&key));
let _ = write_private(&self.url_path(&key), url.as_bytes());
self.textures.borrow_mut().remove(&key);
@@ -599,10 +746,22 @@ mod tests {
"255.255.255.255",
"192.0.2.1",
"198.18.0.1",
"0.1.2.3",
"::1",
"fc00::1",
"fe80::1",
"::ffff:127.0.0.1",
// IPv4-compatible and IPv4-translated, NAT64, 6to4, Teredo/IETF,
// discard and site-local must all be refused.
"::127.0.0.1",
"::ffff:0:0:0:1",
"64:ff9b::169.254.169.254",
"64:ff9b:1::10.0.0.1",
"2002::1",
"2001::1",
"100::1",
"fec0::1",
"3fff::1",
] {
assert!(!is_public(parse_ip(text)), "{text} must not be public");
}
@@ -615,6 +774,16 @@ mod tests {
}
}
/// A URL with embedded credentials is refused before any DNS or network work
/// (the check runs before `resolve_public`, so this needs no network).
#[tokio::test]
async fn a_url_with_userinfo_is_refused() {
let error = fetch_https("https://user:pass@example.com/i.png", Content::Image)
.await
.expect_err("userinfo must be refused");
assert!(error.contains("credentials"), "{error}");
}
#[test]
fn only_raster_magic_bytes_pass() {
assert!(sniff_raster(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]).is_ok());
@@ -638,6 +807,24 @@ mod tests {
assert!(decode_data_url("image/png;base64").is_err(), "no comma");
}
/// An over-sized inline data URL is refused **before** base64 decoding (L7):
/// the size error fires, not the base64 error, even for invalid base64.
#[test]
fn an_oversized_data_url_is_refused_before_decoding() {
use base64::Engine;
let too_long = ((MAX_BYTES / 3) + 1) * 4 + 1;
let error = decode_data_url(&format!("image/png;base64,{}", "!".repeat(too_long)))
.expect_err("must refuse");
assert!(error.contains("larger than 1 MiB"), "got: {error}");
// A small valid PNG data URL still decodes.
let png =
base64::engine::general_purpose::STANDARD.encode([0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
let ok = decode_data_url(&format!("image/png;base64,{png}")).expect("decode");
assert_eq!(&ok, &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
}
#[test]
fn a_failed_url_is_not_retried_until_it_changes() {
let store = IconStore::at(temp_dir());
@@ -724,7 +911,7 @@ mod tests {
store.store(&live, url, b"x");
store.store(&dead, url, b"x");
store.gc(&[live.clone()]);
store.gc(std::slice::from_ref(&live));
assert!(
dir.join(format!("{live}.img")).exists(),
"the live key is kept"
@@ -777,4 +964,61 @@ mod tests {
assert!(!store.needs_fetch("short", "https://x/i.png"));
assert!(!dir.exists(), "no directory is created for an invalid key");
}
/// A PNG header carrying a 30,000×30,000 canvas: `decode` must refuse it
/// from the header, before `gdk::Texture::from_bytes` allocates gigabytes.
fn png_header(width: u32, height: u32) -> Vec<u8> {
let mut bytes = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
bytes.extend_from_slice(&[0, 0, 0, 13]); // IHDR length
bytes.extend_from_slice(b"IHDR");
bytes.extend_from_slice(&width.to_be_bytes());
bytes.extend_from_slice(&height.to_be_bytes());
bytes.extend_from_slice(&[8, 6, 0, 0, 0]); // bit depth, colour, …
bytes
}
#[test]
fn dimensions_are_read_from_each_format_header() {
assert_eq!(sniff_dimensions(&png_header(1200, 800)), Some((1200, 800)));
let mut gif = b"GIF89a".to_vec();
gif.extend_from_slice(&300u16.to_le_bytes());
gif.extend_from_slice(&200u16.to_le_bytes());
gif.extend_from_slice(&[0; 4]);
assert_eq!(sniff_dimensions(&gif), Some((300, 200)));
// JPEG: SOI, an APP0 segment, then SOF0 with height 100, width 150.
let mut jpeg = vec![0xff, 0xd8];
jpeg.extend_from_slice(&[0xff, 0xe0, 0x00, 0x10]); // APP0, length 16
jpeg.extend_from_slice(&[0; 14]);
jpeg.extend_from_slice(&[0xff, 0xc0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
jpeg.extend_from_slice(&100u16.to_be_bytes()); // height
jpeg.extend_from_slice(&150u16.to_be_bytes()); // width
jpeg.extend_from_slice(&[0; 6]);
assert_eq!(sniff_dimensions(&jpeg), Some((150, 100)));
// WebP lossy (VP8): RIFF/WEBP, a 10-byte VP8 payload.
let mut webp = b"RIFF".to_vec();
webp.extend_from_slice(&0u32.to_le_bytes());
webp.extend_from_slice(b"WEBP");
webp.extend_from_slice(b"VP8 ");
webp.extend_from_slice(&0u32.to_le_bytes());
webp.extend_from_slice(&[0, 0, 0]); // frame tag
webp.extend_from_slice(&[0x9d, 0x01, 0x2a]);
webp.extend_from_slice(&320u16.to_le_bytes());
webp.extend_from_slice(&240u16.to_le_bytes());
assert_eq!(sniff_dimensions(&webp), Some((320, 240)));
assert_eq!(sniff_dimensions(&[0x89, b'P', b'N', b'G']), None);
}
/// A huge declared canvas is refused, and a truncated header is refused too
/// (fail closed) — without either reaching the decoder.
#[test]
fn a_decompression_bomb_is_refused_before_decoding() {
let bomb = png_header(30_000, 30_000);
let error = decode(&bomb).expect_err("a 30,000² header must be refused");
assert!(error.contains("too large"), "{error}");
assert!(decode(&[0x89, b'P', b'N', b'G']).is_err());
}
}
+295 -35
View File
@@ -21,7 +21,7 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::Instant;
use std::time::Duration;
use nostr::prelude::*;
use serde::{Deserialize, Serialize};
@@ -93,8 +93,18 @@ pub struct KeyStore {
path: PathBuf,
state: Mutex<State>,
unlocked: Mutex<Option<Unlocked>>,
/// When the vault was opened, for the auto-lock timeout.
unlocked_at: Mutex<Option<Instant>>,
/// When the vault was opened, for the auto-lock timeout. Measured as
/// [`boottime`] (seconds since boot, including suspend), not an `Instant`,
/// so a machine that sleeps through the timeout still locks on resume.
unlocked_at: Mutex<Option<Duration>>,
/// Serializes the mutations that can interleave into a mixed-passphrase
/// vault: `add_user_key` and `change_passphrase` both encrypt, then update
/// state and save. Held across their `spawn_blocking` awaits (M9).
writes: tokio::sync::Mutex<()>,
/// Serializes the read-clone → write → rename in [`KeyStore::save`], so the
/// last writer always has the newest state snapshot. Never held across an
/// await: `save` is synchronous.
save_lock: Mutex<()>,
}
impl KeyStore {
@@ -125,7 +135,7 @@ impl KeyStore {
Ok(vault) => vault,
Err(error) => {
eprintln!("regent: moving unreadable {} aside: {error}", path.display());
let _ = std::fs::rename(&path, path.with_extension("json.corrupt"));
let _ = std::fs::rename(&path, corrupt_path(&path));
Vault::default()
}
},
@@ -138,6 +148,19 @@ impl KeyStore {
}
};
// A future vault version is intact, not corrupt: refuse to run rather
// than silently downgrade it — and do **not** move it to
// `keys.json.corrupt.*` (that is for an unreadable file). A missing or
// older version (0, the serde default) still loads.
if vault.version > 1 {
return Err(format!(
"{} was written by a newer Regent (version {}); refusing to downgrade it",
path.display(),
vault.version
)
.into());
}
let device = vault
.device
.as_deref()
@@ -153,6 +176,8 @@ impl KeyStore {
}),
unlocked: Mutex::new(None),
unlocked_at: Mutex::new(None),
writes: tokio::sync::Mutex::new(()),
save_lock: Mutex::new(()),
})
}
@@ -188,7 +213,7 @@ impl KeyStore {
}
/// When the vault was opened, for the auto-lock timer.
pub fn unlocked_at(&self) -> Option<Instant> {
pub fn unlocked_at(&self) -> Option<Duration> {
*self.unlocked_at.lock().unwrap()
}
@@ -204,7 +229,7 @@ impl KeyStore {
.map_err(|error| format!("the unlock task failed: {error}"))??;
*self.unlocked.lock().unwrap() = Some(Unlocked { keys });
*self.unlocked_at.lock().unwrap() = Some(Instant::now());
*self.unlocked_at.lock().unwrap() = Some(boottime());
Ok(())
}
@@ -345,8 +370,11 @@ impl KeyStore {
/// Re-encrypt every key under a new passphrase.
///
/// Only possible while unlocked — we hold the decrypted keys, so the *old*
/// passphrase is not needed.
/// passphrase is not needed. Serialized with `add_user_key` behind the
/// `writes` mutex, so a key being added cannot be written under the old
/// passphrase beside keys re-encrypted under the new one (M9).
pub async fn change_passphrase(&self, new_passphrase: &str) -> Result<()> {
let _write = self.writes.lock().await;
let keys: Vec<(PublicKey, Keys)> = {
let unlocked = self.unlocked.lock().unwrap();
let unlocked = unlocked
@@ -393,7 +421,12 @@ impl KeyStore {
}
/// Encrypt and store one identity key, then unlock the vault.
///
/// Serialized with `change_passphrase` behind the `writes` mutex: both
/// encrypt and then update state, and letting them interleave produced a
/// vault no passphrase could open (M9).
async fn add_user_key(&self, name: &str, keys: &Keys, passphrase: &str) -> Result<()> {
let _write = self.writes.lock().await;
self.verify_passphrase(passphrase).await?;
let keys = keys.clone();
@@ -453,10 +486,15 @@ impl KeyStore {
/// Write the vault out atomically. An ephemeral vault (no path) does
/// nothing.
///
/// Serialized by `save_lock`, and the temp file is unique
/// ([`tempfile::NamedTempFile`]) so two concurrent saves cannot collide on a
/// shared path (M9).
fn save(&self) -> Result<()> {
if self.path.as_os_str().is_empty() {
return Ok(());
}
let _guard = self.save_lock.lock().unwrap();
let (device, keys) = {
let state = self.state.lock().unwrap();
let device = state
@@ -472,17 +510,75 @@ impl KeyStore {
keys,
};
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
let parent = self
.path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
crate::store::create_private_dir(parent)?;
let contents = serde_json::to_string_pretty(&vault)?;
let temporary = self.path.with_extension("json.tmp");
write_private(&temporary, contents.as_bytes())?;
std::fs::rename(&temporary, &self.path)?;
use std::io::Write;
let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
temporary.write_all(contents.as_bytes())?;
temporary.as_file().sync_all()?;
temporary.persist(&self.path).map_err(|error| error.error)?;
// Belt-and-braces: the file is 0600 from tempfile already, but the
// permission must not depend on the umask.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));
}
Ok(())
}
}
/// Monotonic time since boot, **including time spent suspended**.
///
/// The auto-lock timeout must count a laptop that slept through it, so it cannot
/// use [`std::time::Instant`]: that is `CLOCK_MONOTONIC`, which on Linux stops
/// while the machine is suspended. `CLOCK_BOOTTIME` keeps advancing. This is the
/// single `unsafe` call in the tree.
#[cfg(target_os = "linux")]
pub(crate) fn boottime() -> Duration {
let mut ts = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
// SAFETY: `ts` is a valid, writable `timespec` and `CLOCK_BOOTTIME` is a
// valid clock id, so the call cannot read or write outside `ts`.
let rc = unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut ts) };
if rc == 0 {
Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32)
} else {
wall_clock()
}
}
/// Non-Linux fallback: the wall clock, in the same unit as [`boottime`].
#[cfg(not(target_os = "linux"))]
pub(crate) fn boottime() -> Duration {
wall_clock()
}
/// Seconds since the Unix epoch. Coarser than [`boottime`] across a wall-clock
/// step, but the same unit — and a vault that over-locks is safe.
fn wall_clock() -> Duration {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
}
/// Whether the vault has been open longer than `timeout_secs`.
///
/// A `timeout_secs` of 0 means "never lock". A `now` before `unlocked_at` (a
/// clock anomaly, which `CLOCK_BOOTTIME` cannot produce) does not lock: the
/// timeout is best-effort safety, and the ordinary poll still runs.
pub(crate) fn lock_expired(unlocked_at: Duration, now: Duration, timeout_secs: u32) -> bool {
timeout_secs != 0 && now.saturating_sub(unlocked_at) >= Duration::from_secs(timeout_secs as u64)
}
/// Decrypt every entry, so a wrong passphrase fails before anything is cached.
///
/// Each decrypted key is checked against the pubkey stored beside it: a
@@ -507,26 +603,16 @@ fn decrypt_all(entries: &[StoredKey], passphrase: &str) -> Result<HashMap<Public
Ok(keys)
}
/// Write a file that is private from the moment it exists.
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
Ok(())
/// A unique name for a quarantined unreadable vault.
///
/// Sub-second precision (or the pid) so a second corruption does not rename over
/// the first backup, which is the only copy of the keys (M9).
fn corrupt_path(path: &std::path::Path) -> PathBuf {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| format!("{}.{}", since.as_secs(), since.subsec_nanos()))
.unwrap_or_else(|_| format!("pid{}", std::process::id()));
PathBuf::from(format!("{}.corrupt.{stamp}", path.display()))
}
#[cfg(test)]
@@ -553,6 +639,21 @@ mod tests {
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}
/// The timestamped backups of an unreadable vault, if any.
fn corrupt_backups(path: &Path) -> Vec<PathBuf> {
std::fs::read_dir(path.parent().unwrap())
.unwrap()
.filter_map(std::result::Result::ok)
.filter(|entry| {
entry
.file_name()
.to_string_lossy()
.starts_with("keys.json.corrupt.")
})
.map(|entry| entry.path())
.collect()
}
#[tokio::test]
async fn the_device_key_is_generated_once_and_survives_a_reopen() {
let (path, store) = scratch();
@@ -784,10 +885,169 @@ mod tests {
let reopened = KeyStore::at(path.clone()).expect("open");
assert!(reopened.list_user_keys().is_empty(), "it starts empty");
let backups = corrupt_backups(&path);
assert_eq!(backups.len(), 1, "the unreadable file is kept for recovery");
// A second corruption gets its own timestamped backup: the first is not
// overwritten.
std::fs::write(&path, b"{ not json either").expect("corrupt it again");
let _ = KeyStore::at(path.clone()).expect("open");
assert_eq!(
corrupt_backups(&path).len(),
2,
"each corruption keeps its own backup"
);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A vault written by a newer Regent is refused **in place** — not
/// quarantined (it is intact) and not downgraded (I3).
#[tokio::test]
async fn a_future_vault_version_is_refused_without_quarantine() {
let (path, store) = scratch();
store.generate_user_key("Work", "hunter2").await.expect("generate");
let mut vault: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&path).expect("read")).expect("parse");
vault["version"] = serde_json::Value::from(2u64);
std::fs::write(&path, serde_json::to_string(&vault).expect("serialize")).expect("write");
let error = KeyStore::at(path.clone())
.err()
.expect("must refuse a newer version");
assert!(error.to_string().contains("newer Regent"), "got: {error}");
assert!(path.exists(), "the vault is left in place");
assert!(
path.with_extension("json.corrupt").exists(),
"the unreadable file is kept for recovery"
corrupt_backups(&path).is_empty(),
"a newer vault is not quarantined as corrupt"
);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// The auto-lock timeout is measured from the unlock: under it, no lock; at
/// it, lock. Zero means never, and a clock anomaly does not lock.
#[test]
fn the_auto_lock_timeout_counts_time_since_the_unlock() {
let unlocked = Duration::from_secs(100);
assert!(!lock_expired(unlocked, Duration::from_secs(130), 60));
assert!(!lock_expired(unlocked, Duration::from_secs(159), 60));
assert!(lock_expired(unlocked, Duration::from_secs(160), 60));
assert!(lock_expired(unlocked, Duration::from_secs(500), 60));
assert!(
!lock_expired(unlocked, Duration::from_secs(86_400), 0),
"zero means never lock"
);
assert!(
!lock_expired(unlocked, Duration::from_secs(50), 60),
"a clock anomaly must not lock"
);
}
/// `boottime` is monotonic; the auto-lock comparison relies on it.
#[test]
fn boottime_does_not_go_backwards() {
let first = boottime();
let second = boottime();
assert!(second >= first);
}
/// The unlocked vault **is** the authorisation for changing the passphrase
/// and exporting a key (L3): both refuse a locked vault, and both work once
/// it is open — deliberately with no second passphrase prompt.
#[tokio::test]
async fn a_locked_vault_cannot_change_its_passphrase_or_export() {
let (path, store) = scratch();
let key = store.generate_user_key("Work", "hunter2").await.expect("generate");
store.lock();
assert!(
store.change_passphrase("new").await.is_err(),
"changing the passphrase needs an open vault"
);
assert!(
store
.export_user_key_encrypted(&key, "export-password")
.await
.is_err(),
"exporting needs an open vault"
);
// Both succeed once it is unlocked.
store.unlock("hunter2").await.expect("unlock");
store.change_passphrase("new").await.expect("change");
assert!(
store
.export_user_key_encrypted(&key, "export-password")
.await
.is_ok()
);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// Two concurrent `add_user_key` calls leave a valid vault with both keys,
/// and no temp file behind (M9).
#[tokio::test]
async fn concurrent_adds_do_not_collide() {
let (path, store) = scratch();
let store = std::sync::Arc::new(store);
let (a, b) = tokio::join!(
store.generate_user_key("A", "hunter2"),
store.generate_user_key("B", "hunter2"),
);
a.expect("a");
b.expect("b");
assert_eq!(store.list_user_keys().len(), 2);
let reopened = KeyStore::at(path.clone()).expect("reopen");
assert_eq!(reopened.list_user_keys().len(), 2);
let leftovers: Vec<_> = std::fs::read_dir(path.parent().unwrap())
.unwrap()
.filter_map(std::result::Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().contains(".tmp"))
.collect();
assert!(leftovers.is_empty(), "no temp file is left behind");
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
/// A concurrent add and passphrase change must never leave a
/// mixed-passphrase vault. Whichever order they serialise in, exactly one
/// passphrase opens the file and every stored key decrypts under it — never
/// a vault that opens with neither (M9).
#[tokio::test]
async fn a_concurrent_add_and_change_never_mix_passphrases() {
// Few iterations: each runs several NIP-49 scrypt operations (slow in a
// debug build). The invariant holds deterministically under the `writes`
// mutex; the loop only widens the interleavings a regression could use.
for _ in 0..2 {
let (path, store) = scratch();
store.generate_user_key("Work", "old").await.expect("generate");
let store = std::sync::Arc::new(store);
let changing = store.change_passphrase("new");
let secret = Keys::generate().secret_key().to_bech32().unwrap();
let adding = store.import_user_key("Sneaky", &secret, "old");
let _ = tokio::join!(changing, adding);
let reopened = KeyStore::at(path.clone()).expect("reopen");
let opens_new = reopened.unlock("new").await.is_ok();
let opens_old = if opens_new {
false
} else {
reopened.unlock("old").await.is_ok()
};
assert!(
opens_new ^ opens_old,
"exactly one passphrase opens the vault (new={opens_new} old={opens_old})"
);
for key in reopened.list_user_keys() {
assert!(
reopened.user_key(&key.public_key).expect("load").is_some(),
"every stored key decrypts under the one passphrase"
);
}
drop(store);
let _ = std::fs::remove_dir_all(path.parent().unwrap());
}
}
}
+65
View File
@@ -1,9 +1,74 @@
//! Persistent state: the encrypted key vault, the application registry, and the
//! activity log.
use std::path::Path;
pub mod apps;
pub mod audit;
pub mod icons;
pub mod keys;
pub mod nip05;
pub mod profiles;
/// Create a directory (and its parents) that is private to the user, mode 0700.
///
/// The data, config and cache directories hold keys, the app registry, the
/// activity log and per-key icon files; on a multi-user machine the process
/// umask (typically 0755) would let another local user list them. A directory
/// that already exists is tightened to 0700 as well. Fails closed on error.
pub(crate) fn create_private_dir(path: &Path) -> std::io::Result<()> {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(path)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch() -> std::path::PathBuf {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
std::env::temp_dir().join(format!(
"regent-private-dir-{}-{}",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
))
}
#[cfg(unix)]
fn mode(path: &Path) -> u32 {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[cfg(unix)]
#[test]
fn a_private_dir_is_created_0700_and_tightens_an_existing_one() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch();
let nested = dir.join("a").join("b");
create_private_dir(&nested).expect("create");
assert!(nested.is_dir());
assert_eq!(mode(&nested), 0o700);
// A directory that already exists with looser permissions is tightened.
let loose = dir.join("loose");
std::fs::create_dir(&loose).expect("create");
std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).unwrap();
create_private_dir(&loose).expect("create");
assert_eq!(mode(&loose), 0o700);
let _ = std::fs::remove_dir_all(&dir);
}
}
+65 -32
View File
@@ -157,11 +157,12 @@ impl Profiles {
}
/// The profile name for display, if one was fetched.
///
/// Sanitized and bounded on **read**: `profiles.json` is on disk and could
/// be hand-edited, and a kind-0 name is attacker-controlled data that
/// renders in the switcher and the identities list.
pub fn display_name(&self, key: &PublicKey) -> Option<String> {
self.get(key)
.and_then(|profile| profile.display_name)
.map(|name| name.trim().to_string())
.filter(|name| !name.is_empty())
crate::sanitize::clean_opt(self.get(key).and_then(|profile| profile.display_name), 64)
}
/// The identity's picture URL, if one was fetched and is still well formed.
@@ -378,16 +379,38 @@ impl Profiles {
if self.path.as_os_str().is_empty() {
return;
}
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
// A unique temp file (M9): a fixed `profiles.json.tmp` would collide
// when two fetch completions save at once. Atomic rename keeps the file
// valid throughout; last-writer-wins on concurrent completions is
// acceptable here (the watermarks make a lost write re-fetchable).
let parent = self
.path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
let _ = crate::store::create_private_dir(parent);
let entries = self.entries.lock().unwrap().clone();
let Ok(contents) = serde_json::to_string_pretty(&entries) else {
return;
};
let temporary = self.path.with_extension("json.tmp");
if write_private(&temporary, contents.as_bytes()).is_ok() {
let _ = std::fs::rename(&temporary, &self.path);
use std::io::Write;
match tempfile::NamedTempFile::new_in(parent) {
Ok(mut temporary) => {
if temporary.write_all(contents.as_bytes()).is_ok()
&& temporary.as_file().sync_all().is_ok()
&& temporary.persist(&self.path).is_ok()
{
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(
&self.path,
std::fs::Permissions::from_mode(0o600),
);
}
}
}
Err(error) => eprintln!("regent: could not write profiles: {error}"),
}
}
}
@@ -890,17 +913,15 @@ fn profile_from_metadata(metadata: &Metadata) -> Profile {
}
}
/// Trim and drop a blank name, so the store never holds a padded one.
/// Trim, sanitize and drop a blank name, so the store never holds a padded one
/// or one carrying control/bidi characters.
fn bound_name(value: Option<String>) -> Option<String> {
let value = value?;
let value = value.trim();
(!value.is_empty()).then(|| value.to_string())
crate::sanitize::clean_opt(value, 64)
}
/// Trim, cap and drop a blank picture URL.
/// Trim, sanitize, cap and drop a blank picture URL.
fn bound_picture(value: Option<&str>) -> Option<String> {
let value: String = value?.trim().chars().take(MAX_PICTURE_LEN).collect();
(!value.is_empty()).then_some(value)
crate::sanitize::clean_opt(value.map(str::to_string), MAX_PICTURE_LEN)
}
#[cfg(test)]
@@ -931,6 +952,33 @@ mod tests {
profiles.get(key).unwrap()
}
/// A cached `display_name` is sanitized and bounded on **read**: the file is
/// on disk and a kind-0 name is attacker-controlled (M7).
#[test]
fn a_cached_display_name_is_cleaned_on_read() {
let dir = std::env::temp_dir().join(format!(
"regent-profiles-name-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let public_key = key();
let path = dir.join("profiles.json");
let json = serde_json::json!({
public_key.to_hex(): {
"display_name": format!("{}\u{202E}evil", "n".repeat(500)),
},
})
.to_string();
std::fs::write(&path, json).unwrap();
let profiles = Profiles::at(path);
let name = profiles.display_name(&public_key).unwrap();
assert_eq!(name.chars().count(), 64, "bounded on read");
assert!(!name.contains('\u{202E}'), "bidi stripped on read");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profiles_round_trip_and_refresh_after_a_day() {
let dir = std::env::temp_dir().join(format!("regent-profiles-{}", std::process::id()));
@@ -1876,18 +1924,3 @@ mod tests {
}
}
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}
+346 -14
View File
@@ -10,12 +10,14 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use async_channel::Receiver;
use nostr::types::Timestamp;
use nostr::nips::nip19::ToBech32;
use zeroize::Zeroizing;
use adw::prelude::*;
use gtk::gio;
use gtk::gio::prelude::ApplicationExt;
use gtk::glib;
use gtk::prelude::*;
use libadwaita as adw;
@@ -81,6 +83,21 @@ pub fn install(
}
let _ = reply.send(answer).await;
}
Prompt::Pair { question, reply } => {
// A user-initiated pairing (L4): same serialized drain, but
// no deadline. It can arrive while the window is hidden
// (background/autostart), so mirror the `Approve` arm —
// notify when away and present the window for the dialog.
let notified = notify_pending(&widget, notification_body(&question.request));
primary.present_for_prompt();
runner.set_pending(true);
let answer = present_question(&widget, &question, None, &state).await;
runner.set_pending(false);
if notified {
withdraw_pending(&widget);
}
let _ = reply.send(answer).await;
}
Prompt::Unlock { reply, deadline } => {
if expired(deadline) {
let _ = reply.send(false).await;
@@ -273,7 +290,7 @@ fn name_entry(question: &Question) -> Option<adw::EntryRow> {
.name
.as_deref()
.map(str::trim)
.map_or(true, str::is_empty);
.is_none_or(str::is_empty);
(paired && unnamed).then(|| adw::EntryRow::builder().title("Name").build())
}
@@ -524,6 +541,12 @@ fn details(
.spacing(12)
.build();
// Anything the dialog cannot show in full is disclosed up front (H2): a
// truncated payload or an out-of-range timestamp must not be invisible.
for warning in request_warnings(&question.request) {
content.append(&banner(&warning));
}
content.append(&identity_field(state, &question.identity));
content.append(&application_field(state, client));
// A client that declared no name: naming it sits right under "Application",
@@ -531,13 +554,17 @@ fn details(
if let Some(entry) = name_entry {
content.append(&name_field(entry));
}
// The kind is part of what is being signed, so it sits with the payload
// rather than collapsed under Details.
if let Request::Sign { kind, .. } = &question.request {
// The kind and the client-requested timestamp are part of what is being
// signed, so they sit above the fold with the payload, not under Details.
if let Request::Sign {
kind, created_at, ..
} = &question.request
{
content.append(&plain::text_field(
"Kind",
&format!("{} ({})", kind, kind::name(*kind)),
));
content.append(&plain::text_field("Created at", &when(*created_at)));
}
match &question.request {
@@ -549,10 +576,18 @@ fn details(
Request::Sign {
kind,
content: signed,
content_chars,
tags,
..
} => {
if content::has_content(signed) {
content.append(&content::card(signed, *kind, widget, deadline));
content.append(&content::card(
signed,
*kind,
*content_chars > crate::signer::CONTENT_LIMIT,
widget,
deadline,
));
}
// Tags stay in view rather than collapsed under Details, because for
// some kinds they are the payload itself.
@@ -560,7 +595,9 @@ fn details(
content.append(&content::tags_card(tags, widget, deadline));
}
}
Request::Encrypt { preview, .. } => content.append(&block("Message", preview)),
Request::Encrypt { message, .. } => {
content.append(&message_block("Message", message, widget, deadline));
}
Request::Decrypt { preview, .. } => content.append(&block("Ciphertext", preview)),
}
@@ -601,10 +638,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, .. } => {
@@ -697,13 +739,13 @@ fn application_field(state: &Rc<AppState>, client: &ClientInfo) -> gtk::Box {
.build();
let texture = state.icons().texture(&public_key);
let avatar = plain::avatar(32, name, texture.as_ref());
if texture.is_none() {
if let Some(image) = client.image.as_deref() {
let avatar = avatar.clone();
state.preview_icon(&public_key, image, move |texture| {
avatar.set_custom_image(Some(&texture));
});
}
if texture.is_none()
&& let Some(image) = client.image.as_deref()
{
let avatar = avatar.clone();
state.preview_icon(&public_key, image, move |texture| {
avatar.set_custom_image(Some(&texture));
});
}
let label = match name {
@@ -761,6 +803,203 @@ fn note(text: &str) -> gtk::Label {
label
}
/// A prominent warning banner for something the dialog cannot show in full.
///
/// `AdwBanner` renders its title as Pango markup **by default**, so markup is
/// turned off before the title is set. The text here is our own words (never
/// client-supplied), but the discipline is the same everywhere.
fn banner(text: &str) -> adw::Banner {
let banner = adw::Banner::new("");
banner.set_use_markup(false);
banner.set_title(text);
banner.set_revealed(true);
banner
}
/// A client-requested timestamp as local time, for the "Created at" row.
fn when(created_at: Timestamp) -> String {
glib::DateTime::from_unix_local(created_at.as_secs() as i64)
.and_then(|time| time.format("%Y-%m-%d %H:%M"))
.map(|formatted| formatted.to_string())
.unwrap_or_else(|_| created_at.to_string())
}
/// A coarse "3 days" / "2 hours" / "40 minutes" for a warning.
fn human_delta(seconds: u64) -> String {
if seconds >= 86_400 {
format!("{} days", seconds / 86_400)
} else if seconds >= 3_600 {
format!("{} hours", seconds / 3_600)
} else {
format!("{} minutes", seconds / 60)
}
}
/// What the dialog cannot show in full, as banner texts (H2).
///
/// Pure apart from reading the clock for the timestamp check, so the wording and
/// the predicate are unit-testable. The point is that nothing Regent signs or
/// encrypts is invisible without disclosure.
fn request_warnings(request: &Request) -> Vec<String> {
let limit = crate::signer::CONTENT_LIMIT;
let mut warnings = Vec::new();
match request {
Request::Sign {
content_chars,
tags,
tags_omitted,
tag_fields_omitted,
created_at,
..
} => {
if *content_chars > limit {
warnings.push(format!(
"Showing the first {} KiB of {} KiB of event content.",
limit / 1024,
content_chars.div_ceil(1024)
));
}
if *tags_omitted > 0 {
warnings.push(format!(
"{} of {} tags are not shown.",
tags_omitted,
tags.len() + tags_omitted
));
}
if *tag_fields_omitted > 0 {
warnings.push(format!("{} tag values are not shown.", tag_fields_omitted));
}
let now = Timestamp::now().as_secs() as i64;
let delta = created_at.as_secs() as i64 - now;
if delta.unsigned_abs() > 3_600 {
let when = human_delta(delta.unsigned_abs());
warnings.push(if delta > 0 {
format!("The event is timestamped {when} in the future.")
} else {
format!("The event is timestamped {when} in the past.")
});
}
}
Request::Encrypt { message_chars, .. } if *message_chars > limit => {
warnings.push(format!(
"Showing the first {} KiB of {} KiB of the message.",
limit / 1024,
message_chars.div_ceil(1024)
));
}
_ => {}
}
// NIP-04 is the unauthenticated legacy scheme; disclose it (I2).
if let Request::Encrypt { method, .. } | Request::Decrypt { method, .. } = request
&& *method == "nip04"
{
warnings.push(
"This application asked for NIP-04, an older scheme without \
authentication. NIP-44 is recommended."
.to_string(),
);
}
warnings
}
/// A titled, bounded, scrollable block for a long client string, with a button
/// that opens the same text in a larger dialog — so the full message is always
/// reachable and never hidden after a short preview.
fn message_block(
title: &str,
value: &str,
parent: &impl IsA<gtk::Widget>,
deadline: Option<Instant>,
) -> gtk::Box {
let container = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(4)
.build();
let header = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(12)
.build();
header.append(
&gtk::Label::builder()
.label(title)
.xalign(0.0)
.hexpand(true)
.css_classes(["dim-label"])
.build(),
);
let view_button = gtk::Button::builder()
.label("View full message")
.css_classes(["flat"])
.valign(gtk::Align::Center)
.build();
view_button.set_tooltip_text(Some("Show the full message"));
header.append(&view_button);
container.append(&header);
let body = plain::label(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 scrolled = gtk::ScrolledWindow::builder()
.child(&body)
.propagate_natural_height(true)
.max_content_height(160)
.hscrollbar_policy(gtk::PolicyType::Never)
.build();
let frame = gtk::Box::builder().css_classes(["card"]).build();
frame.append(&scrolled);
container.append(&frame);
let window = parent.root().and_downcast::<gtk::Window>();
let full = value.to_string();
view_button.connect_clicked(move |_| {
present_message(window.as_ref(), &full, deadline);
});
container
}
/// The full message in its own dialog, so a structure that grows on click can
/// never be clipped by the approval dialog.
fn present_message(parent: Option<&gtk::Window>, text: &str, deadline: Option<Instant>) {
let body = plain::label(text);
body.set_margin_top(12);
body.set_margin_bottom(12);
body.set_margin_start(12);
body.set_margin_end(12);
let scrolled = gtk::ScrolledWindow::builder()
.child(&body)
.propagate_natural_height(true)
.max_content_height(400)
.hscrollbar_policy(gtk::PolicyType::Never)
.build();
let header = adw::HeaderBar::new();
let toolbar = adw::ToolbarView::new();
toolbar.add_top_bar(&header);
toolbar.set_content(Some(&scrolled));
toolbar.set_size_request(plain::DIALOG_WIDTH, -1);
let dialog = adw::Dialog::builder()
.title("Message")
.follows_content_size(true)
.child(&toolbar)
.build();
dialog.present(parent);
if let Some(left) = remaining(deadline) {
let dialog = dialog.clone();
glib::timeout_add_local_once(left.max(Duration::from_millis(1)), move || {
dialog.force_close();
});
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -790,4 +1029,97 @@ mod tests {
"An application was disconnected"
);
}
fn sign_request(
content_chars: usize,
tags: usize,
tags_omitted: usize,
tag_fields_omitted: usize,
created_at: Timestamp,
) -> Request {
Request::Sign {
kind: 1,
content: "hi".to_string(),
content_chars,
tags: vec![crate::signer::approval::TagView {
name: "t".to_string(),
values: vec!["nostr".to_string()],
}; tags],
tags_omitted,
tag_fields_omitted,
created_at,
}
}
/// A request the dialog can show in full carries no banners.
#[test]
fn a_fully_shown_request_has_no_warnings() {
let request = sign_request(10, 1, 0, 0, Timestamp::now());
assert!(request_warnings(&request).is_empty());
}
/// Everything the dialog hides is disclosed: a truncated payload, hidden
/// tags/fields, and an out-of-range timestamp.
#[test]
fn hidden_payload_and_time_are_disclosed() {
let request = sign_request(
crate::signer::CONTENT_LIMIT + 5,
1,
3,
2,
Timestamp::now() + Duration::from_secs(3 * 86_400),
);
let warnings = request_warnings(&request);
assert_eq!(warnings.len(), 4, "{warnings:?}");
assert!(warnings[0].contains("32 KiB"));
assert!(warnings[1].contains("3 of 4 tags"));
assert!(warnings[2].contains("2 tag values"));
assert!(warnings[3].contains("future"));
}
/// An encrypt message past the bound is disclosed too.
#[test]
fn a_long_encrypt_message_is_disclosed() {
let request = Request::Encrypt {
method: "nip44_encrypt",
peer: "npub1".to_string(),
message: "hi".to_string(),
message_chars: crate::signer::CONTENT_LIMIT + 1,
};
let warnings = request_warnings(&request);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].contains("32 KiB"));
}
/// A NIP-04 request is disclosed as the legacy scheme (I2). The `method` is
/// the `nim_name` form ("nip04"/"nip44"), not the full method name.
#[test]
fn a_nip04_request_is_flagged() {
let encrypt = Request::Encrypt {
method: "nip04",
peer: "npub1".to_string(),
message: "hi".to_string(),
message_chars: 2,
};
let warnings = request_warnings(&encrypt);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].contains("NIP-04"));
let decrypt = Request::Decrypt {
method: "nip04",
peer: "npub1".to_string(),
preview: "cipher".to_string(),
};
let warnings = request_warnings(&decrypt);
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(warnings[0].contains("NIP-04"));
let nip44 = Request::Encrypt {
method: "nip44",
peer: "npub1".to_string(),
message: "hi".to_string(),
message_chars: 2,
};
assert!(request_warnings(&nip44).is_empty());
}
}
+3 -4
View File
@@ -313,10 +313,9 @@ impl Ui {
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty()),
) {
if label != declared {
row.add_row(&plain::row("Declared name", declared));
}
) && label != declared
{
row.add_row(&plain::row("Declared name", declared));
}
// Which identity this app signs as. This is the binding the responder
+24 -17
View File
@@ -26,7 +26,7 @@ use crate::runtime;
use crate::signer::approval::{Decision, Question, Request, SigningKey};
use crate::signer::{pair_client, parse_client_uri, ClientPairing, Signer};
use crate::state::AppState;
use crate::ui::{approval, plain, qr};
use crate::ui::{plain, qr};
use crate::window::Windows;
pub struct ConnectDialog {
@@ -220,10 +220,10 @@ impl ConnectDialog {
{
let listener = Rc::clone(&connect);
copy.connect_clicked(move |_| {
if let Some(uri) = listener.runner.bunker_uri() {
if let Some(window) = listener.window() {
window.clipboard().set_text(&uri);
}
if let Some(uri) = listener.runner.bunker_uri()
&& let Some(window) = listener.window()
{
plain::copy_secret(&window.clipboard(), &uri);
}
listener
.overlay
@@ -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());
}
}
}
@@ -356,13 +356,15 @@ impl ConnectDialog {
if text.trim().is_empty() {
return;
}
self.begin_pairing(text.trim(), &self.dialog.clone().upcast::<gtk::Widget>());
self.begin_pairing(text.trim());
}
/// Pair from a `nostrconnect://` URI, asked over `parent`: the "Connect an
/// app" dialog passes itself, an opened link passes the main window (that
/// dialog is not open then).
pub(crate) fn begin_pairing(self: &Rc<Self>, uri: &str, parent: &gtk::Widget) {
/// Pair from a `nostrconnect://` URI.
///
/// The question goes through the responder's serialized `Approver` queue
/// (L4), so it can never stack over another prompt; it is presented over the
/// primary window by the drain.
pub(crate) fn begin_pairing(self: &Rc<Self>, uri: &str) {
let pairing = match parse_client_uri(uri) {
Ok(pairing) => pairing,
Err(error) => {
@@ -398,6 +400,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,
@@ -406,13 +413,13 @@ impl ConnectDialog {
rebind_from,
};
let parent = parent.clone();
let approver = self.runner.approver();
let connect = Rc::clone(self);
glib::MainContext::default().spawn_local(async move {
// The same approval dialog as a responder question: the app is
// registered *before* the response goes out, and the user is the
// one who decides.
let answer = approval::present_question(&parent, &question, None, &connect.state).await;
// The same approval dialog as a responder question, through the same
// serialized queue: the app is registered *before* the response goes
// out, and the user is the one who decides.
let answer = approver.ask_pairing(question).await;
if answer.decision == Decision::Deny {
return;
}
+19 -3
View File
@@ -158,6 +158,7 @@ fn collapse(fields: Vec<Field>) -> Vec<Field> {
pub fn card(
content: &str,
kind_number: u16,
truncated: bool,
parent: &impl IsA<gtk::Widget>,
deadline: Option<Instant>,
) -> gtk::Box {
@@ -206,7 +207,7 @@ pub fn card(
let window = parent.root().and_downcast::<gtk::Window>();
let content = content.to_string();
view_button.connect_clicked(move |_| {
present_preview(window.as_ref(), &content, kind_number, deadline);
present_preview(window.as_ref(), &content, kind_number, truncated, deadline);
});
container
@@ -446,6 +447,7 @@ fn present_preview(
parent: Option<&gtk::Window>,
content: &str,
kind_number: u16,
truncated: bool,
deadline: Option<Instant>,
) {
let classified = view(content, kind_number);
@@ -461,7 +463,17 @@ fn present_preview(
let original = padded_scroller(&monospace(content));
let stack = gtk::Stack::builder().build();
stack.add_titled(&formatted, Some("formatted"), "Formatted");
stack.add_titled(&original, Some("original"), "Original");
// The "Original" page shows the *bounded* copy, so say so when a cut
// happened: the full event content is what gets signed, not this view.
stack.add_titled(
&original,
Some("original"),
if truncated {
"Original (first 32 KiB)"
} else {
"Original"
},
);
header.set_title_widget(Some(&gtk::StackSwitcher::builder().stack(&stack).build()));
toolbar.set_content(Some(&stack));
} else {
@@ -472,7 +484,11 @@ fn present_preview(
toolbar.set_size_request(plain::DIALOG_WIDTH, -1);
let dialog = adw::Dialog::builder()
.title("Event content")
.title(if truncated {
"Event content (first 32 KiB)"
} else {
"Event content"
})
.follows_content_size(true)
.child(&toolbar)
.build();
+83 -16
View File
@@ -20,6 +20,7 @@ use nostr::prelude::{Keys, PublicKey};
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use zeroize::Zeroizing;
use crate::runtime;
use crate::state::AppState;
@@ -378,6 +379,22 @@ impl PassphraseFields {
}
}
/// The export password: always confirmed and at least 8 characters, because a
/// typo (or an empty submit) would make the backup unrecoverable and an
/// accidental empty password is not a protection.
fn export() -> Self {
Self {
passphrase: adw::PasswordEntryRow::builder()
.title("Export password")
.build(),
confirm: Some(
adw::PasswordEntryRow::builder()
.title("Confirm password")
.build(),
),
}
}
fn append_to(&self, list: &gtk::ListBox) {
list.append(&self.passphrase);
if let Some(confirm) = &self.confirm {
@@ -387,17 +404,32 @@ impl PassphraseFields {
/// The typed passphrase, or an error to show instead of proceeding.
fn value(&self) -> Result<String, String> {
let passphrase = self.passphrase.text().to_string();
if passphrase.chars().count() < 8 {
return Err("Use a passphrase of at least 8 characters.".to_string());
}
if let Some(confirm) = &self.confirm {
if confirm.text().to_string() != passphrase {
return Err("The two passphrases do not match.".to_string());
}
}
Ok(passphrase)
let confirm = self.confirm.as_ref().map(|row| row.text().to_string());
validate_passphrase(&self.passphrase.text(), confirm.as_deref())
}
/// Wipe the typed secrets from the fields; a dialog's fields must not keep a
/// passphrase after it closes.
fn clear(&self) {
self.passphrase.set_text("");
if let Some(confirm) = &self.confirm {
confirm.set_text("");
}
}
}
/// Validate a passphrase/confirmation pair. Pure so it is testable without
/// constructing widgets (a plain `cargo test` has no GTK display).
fn validate_passphrase(passphrase: &str, confirm: Option<&str>) -> Result<String, String> {
if passphrase.chars().count() < 8 {
return Err("Use a passphrase of at least 8 characters.".to_string());
}
if let Some(confirm) = confirm
&& confirm != passphrase
{
return Err("The two passphrases do not match.".to_string());
}
Ok(passphrase.to_string())
}
/// The vault is opened for these dialogs; an import that sets the passphrase
@@ -447,6 +479,8 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
Ok(passphrase) => passphrase,
Err(error) => return report_error(&handles, &error),
};
fields.clear();
let passphrase = Zeroizing::new(passphrase);
let name = name.text().trim().to_string();
let after = Rc::clone(&state);
let handles = handles.clone();
@@ -467,7 +501,10 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
let store = state.store();
let first = !store.has_vault();
let entry = adw::EntryRow::builder()
// Masked: the field accepts an `nsec`/hex private key, which must not be
// shown in cleartext on screen (`AdwPasswordEntryRow` is an `AdwEntryRow`,
// so the prefill `connect_changed` handler below is unchanged).
let entry = adw::PasswordEntryRow::builder()
.title("nsec, hex, or ncryptsec")
.build();
// Prefilled from the *discovered* profile once the pasted key can be decoded,
@@ -531,7 +568,15 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
Err(error) => return report_error(&handles, &error),
};
let text = entry.text().to_string();
let import_password = import_password.text().to_string();
let import_password_text = import_password.text().to_string();
// Wipe what was read from the widgets: a pasted `nsec` and the
// passphrases must not linger.
fields.clear();
entry.set_text("");
import_password.set_text("");
let text = Zeroizing::new(text);
let import_password = Zeroizing::new(import_password_text);
let passphrase = Zeroizing::new(passphrase);
// Empty means "no label": the discovered profile name is what the app
// shows, and a label is only for keys with no profile.
let label = name.text().trim().to_string();
@@ -624,12 +669,14 @@ fn present_export(handles: Handles, state: Rc<AppState>, public_key: PublicKey)
}
fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: PublicKey) {
let password = adw::PasswordEntryRow::builder().title("Password").build();
// Confirmed and ≥8 characters: an accidental empty submit must not encrypt
// the key under `""`, and a typo must not produce an unrecoverable backup.
let fields = PassphraseFields::export();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
.css_classes(["boxed-list"])
.build();
list.append(&password);
fields.append_to(&list);
let dialog = adw::AlertDialog::builder()
.heading("Export identity key")
@@ -653,9 +700,15 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: Publ
if response != "export" {
return;
}
let password = match fields.value() {
Ok(password) => password,
Err(error) => return report_error(&handles, &error),
};
fields.clear();
let password = Zeroizing::new(password);
let store = state.store();
let (password, handles, window) =
(password.text().to_string(), handles.clone(), window.clone());
(password, handles.clone(), window.clone());
runtime::spawn(
async move {
store
@@ -665,7 +718,7 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: Publ
move |result| match result {
Ok(ncryptsec) => {
if let Some(window) = &window {
window.clipboard().set_text(&ncryptsec);
plain::copy_secret(&window.clipboard(), &ncryptsec);
}
let label = gtk::Label::builder()
.label(ncryptsec.as_str())
@@ -796,6 +849,20 @@ fn report_error(handles: &Handles, message: &str) {
mod tests {
use super::*;
/// The export/passphrase validation is pure, so it is testable without a GTK
/// display (L2).
#[test]
fn passphrase_validation_requires_length_and_a_match() {
assert!(validate_passphrase("short", None).is_err());
assert!(validate_passphrase("longenough", Some("different")).is_err());
assert!(validate_passphrase("short", Some("short")).is_err(), "length first");
assert_eq!(
validate_passphrase("longenough", Some("longenough")).unwrap(),
"longenough"
);
assert_eq!(validate_passphrase("longenough", None).unwrap(), "longenough");
}
#[test]
fn a_manual_refetch_has_three_things_to_say() {
assert_eq!(fetched_toast(FetchOutcome::Updated), "Profile updated");
+21
View File
@@ -22,6 +22,27 @@ use libadwaita as adw;
/// them. 480 fits comfortably inside the main window (560 px wide).
pub const DIALOG_WIDTH: i32 = 480;
/// Copy a secret (an exported `ncryptsec`, a `bunker://` string) to the
/// clipboard and clear it again after 60 s if it still holds that value.
///
/// The clipboard is readable by any process the user runs while it is set, so a
/// secret does not belong there indefinitely: 60 s is long enough to paste it,
/// short enough that a forgotten copy does not persist.
pub fn copy_secret(clipboard: &gtk::gdk::Clipboard, text: &str) {
clipboard.set_text(text);
let clipboard = clipboard.clone();
let text = text.to_string();
gtk::glib::timeout_add_seconds_local_once(60, move || {
gtk::glib::MainContext::default().spawn_local(async move {
if let Ok(Some(current)) = clipboard.read_text_future().await
&& current.as_str() == text
{
clipboard.set_text("");
}
});
});
}
/// A plain "Something went wrong" dialog, parented to the widget's window.
///
/// The message is our own text, but it can carry a client-supplied name or a
+6 -1
View File
@@ -23,6 +23,7 @@ use crate::runner::{SignerRunner, Status};
use crate::runtime;
use crate::state::AppState;
use crate::ui::plain;
use zeroize::Zeroizing;
/// The auto-lock choices: the timeout in seconds, and what to call it. `0` means
/// never lock, which is the user's call to make — but not the default.
@@ -520,9 +521,13 @@ impl Preferences {
if passphrase.chars().count() < 8 {
return preferences.error("Use a passphrase of at least 8 characters.");
}
if confirm.text().to_string() != passphrase {
if confirm.text() != passphrase {
return preferences.error("The two passphrases do not match.");
}
// Wipe the fields; the new passphrase must not linger in a widget.
new.set_text("");
confirm.set_text("");
let passphrase = Zeroizing::new(passphrase);
let store = preferences.state.store();
let preferences = Rc::clone(&preferences);
runtime::spawn(
+4 -11
View File
@@ -332,22 +332,15 @@ impl Windows {
}
}
/// Pair from a `nostrconnect://` URI — what opening a link does. Goes
/// straight to the approval dialog, over the window the app is.
/// Pair from a `nostrconnect://` URI — what opening a link does. The
/// question goes through the serialized approval queue, which presents the
/// window itself if it is hidden.
pub fn pair_uri(self: &Rc<Self>, uri: &str) {
let Some(connect) = self.connect_dialog() else {
return;
};
// A link can arrive while the window is hidden in the background, and a
// dialog parented to a hidden window is invisible.
self.present_primary();
let Some(parent) = self
.visible_parent()
.map(|window| window.upcast::<gtk::Widget>())
else {
return;
};
connect.begin_pairing(uri, &parent);
connect.begin_pairing(uri);
}
/// Bring the Apps page to the front. A pairing closes the "Connect an app"